### Setup Class Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/WorkSheet.md Defines the setup parameters for a worksheet, including text size, margins, and other layout properties. ```APIDOC ## Setup ### Description Represents the configuration for a worksheet's layout and appearance. ### Class `Setup` ### Attributes - `textSize` (WksFontSize) - Default text size for the worksheet. - `margins` (WksPosition) - Page margins for the worksheet. - `rightMargin` (float) - The width of the right margin. - `bottomMargin` (float) - The height of the bottom margin. ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/mvnmgrx/kiutils/blob/master/CONTRIBUTING.md Install the necessary development dependencies for KiUtils using pip and the requirements_dev.txt file. ```bash pip install -r requirements_dev.txt ``` -------------------------------- ### Install kiutils Source: https://github.com/mvnmgrx/kiutils/blob/master/README.md Install the kiutils library using pip. This command installs the latest version. ```bash pip install kiutils ``` -------------------------------- ### Setup Class for Worksheet Configuration Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/WorkSheet.md Defines parameters for worksheet setup, including text size and margins. Use this to configure global worksheet properties. ```python @dataclass class Setup(): """Worksheet setup parameters.""" textSize: WksFontSize = WksFontSize() # Default text size margins: WksPosition = WksPosition() # Page margins rightMargin: float = 0 bottomMargin: float = 0 ``` -------------------------------- ### Install HtmlTestRunner with pip Source: https://github.com/mvnmgrx/kiutils/blob/master/tests/reporter/README.md Use this command to install the HtmlTestRunner package. This is the recommended method for obtaining the latest stable release. ```batch $ pip install html-testRunner ``` -------------------------------- ### Library URI Path Examples Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/LibraryTable.md Illustrates different ways to specify library URIs, including project-relative, KiCad built-in, absolute paths, and user home directory paths, utilizing environment variables. ```python library.uri = "${KIPRJMOD}/libraries/custom.kicad_sym" # Project-relative ``` ```python library.uri = "${KICAD}/share/kicad/symbols/power.kicad_sym" # KiCad built-in ``` ```python library.uri = "/absolute/path/to/library.kicad_sym" # Absolute path ``` ```python library.uri = "~/user/kicad/libraries/my.kicad_sym" # User home ``` -------------------------------- ### Create a New KiCad Board Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Initialize a new, empty KiCad board object using `Board.create_new()`. This is the starting point for creating a board programmatically. ```python Board.create_new() ``` -------------------------------- ### Board Constructor Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/Board.md Initializes a new Board object. This constructor allows for setting various board properties upon creation, including version, generator, general settings, page settings, title block information, layers, setup data, properties, nets, footprints, graphic items, trace items, zones, dimensions, targets, groups, and the file path. ```APIDOC ## Board Constructor ### Description Initializes a new Board object with various optional parameters to define the PCB layout. ### Parameters - **version** (str, optional): The board version using YYYYMMDD date format. Defaults to "". - **generator** (str, optional): The program used to write the file. Defaults to "". - **general** (GeneralSettings, optional): General information about the board. Defaults to `GeneralSettings()`. - **paper** (PageSettings, optional): Page size and orientation settings. Defaults to `PageSettings()`. - **titleBlock** (Optional[TitleBlock], optional): Author, date, revision, company and comments. Defaults to `None`. - **layers** (List[LayerToken], optional): All layers used by the board. Defaults to `[]`. - **setup** (SetupData, optional): Current settings and configuration used by the board. Defaults to `SetupData()`. - **properties** (Dict[str, str], optional): Key-value properties of the board. Defaults to `{}`. - **nets** (List[Net], optional): List of nets used in the layout. Defaults to `[]`. - **footprints** (List[Footprint], optional): List of footprints used in the layout. Defaults to `[]`. - **graphicItems** (List, optional): Graphical items (text, lines, rectangles, circles, arcs, polygons, curves, images). Defaults to `[]`. - **traceItems** (List, optional): Segments, arcs and vias used in the layout. Defaults to `[]`. - **zones** (List[Zone], optional): Copper zones used in the layout. Defaults to `[]`. - **dimensions** (List[Dimension], optional): Dimension annotations on the PCB. Defaults to `[]`. - **targets** (List[Target], optional): Target markers on the PCB. Defaults to `[]`. - **groups** (List[Group], optional): Groups of objects on the PCB. Defaults to `[]`. - **filePath** (Optional[str], optional): Path to the `.kicad_pcb` file. Defaults to `None`. ``` -------------------------------- ### Run Tests with Test Suites and HtmlTestRunner Source: https://github.com/mvnmgrx/kiutils/blob/master/tests/reporter/README.md Use HtmlTestRunner with test suites by creating a runner instance and calling its run method with your suite. This example loads tests from ExampleTest and Example2Test. ```python from unittest import TestLoader, TestSuite from HtmlTestRunner import HTMLTestRunner import ExampleTest import Example2Test example_tests = TestLoader().loadTestsFromTestCase(ExampleTest) example2_tests = TestLoader().loadTestsFromTestCase(Example2Test) suite = TestSuite([example_tests, example2_tests]) runner = HTMLTestRunner(output='example_suite') runner.run(suite) ``` -------------------------------- ### Extend Board Class for Custom Functionality Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/advanced-topics.md Create a custom board class by inheriting from `kiutils.board.Board` to add new methods. This example shows how to implement methods for finding footprints by position and retrieving specific layer types. ```python from kiutils.board import Board from kiutils.items.common import Position class MyBoard(Board): """Custom board class with additional methods.""" def find_footprint_at(self, x: float, y: float, tolerance: float = 1.0): """Find footprint at approximate position.""" for fp in self.footprints: if fp.position is None: continue distance = ((fp.position.X - x)**2 + (fp.position.Y - y)**2)**0.5 if distance < tolerance: return fp return None def get_copper_layers(self): """Get all copper layers.""" return [l for l in self.layers if l.type in ('signal', 'power')] def get_silkscreen_layers(self): """Get all silkscreen layers.""" return [l for l in self.layers if 'SilkS' in l.name] # Usage board = MyBoard.from_file('design.kicad_pcb') fp = board.find_footprint_at(50.0, 40.0) copper = board.get_copper_layers() ``` -------------------------------- ### Accessing Data Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/README.md Provides examples of how to iterate through and access data within loaded `Board` and `Schematic` objects, as well as generic elements like nets. ```APIDOC ## Accessing Data ### Description Accesses elements within loaded KiCad objects. ### Board Elements - `board.footprints`: Iterate through footprints on the board. - `board.nets`: Iterate through nets on the board. ### Schematic Elements - `sch.schematicSymbols`: Iterate through schematic symbols. ### Example Usage ```python # Accessing board footprints for footprint in board.footprints: print(f"{footprint.reference}: {len(footprint.pads)} pads") # Accessing schematic symbols for symbol in sch.schematicSymbols: print(f"{symbol.reference}: {symbol.value}") # Accessing nets for net in board.nets: print(f"Net: {net.name}") ``` ``` -------------------------------- ### Load, Modify, and Save KiCad Worksheet Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/WorkSheet.md Demonstrates loading an existing worksheet, accessing and modifying its setup and text elements, adding new text and lines, and saving the changes to a new file. Ensure the 'kicad_template.kicad_wks' file exists in the same directory or provide a full path. ```python from kiutils.wks import WorkSheet, Setup, WksPosition, TbText, Line # Load an existing worksheet worksheet = WorkSheet.from_file('kicad_template.kicad_wks') # Access setup parameters if worksheet.setup: print(f"Page margins: {worksheet.setup.margins.X}mm x {worksheet.setup.margins.Y}mm") # Iterate over text elements for text in worksheet.texts: if text.name == "Title": print(f"Title position: ({text.position.X}, {text.position.Y})") # Modify worksheet worksheet.setup.margins = WksPosition(X=10, Y=10) # Add a new title block text field new_text = TbText( name="Company", position=WksPosition(X=50, Y=20) ) worksheet.texts.append(new_text) # Add a border line border_line = Line( startX=10, startY=10, endX=200, endY=10, linewidth=0.3 ) worksheet.lines.append(border_line) # Save modified worksheet worksheet.to_file('custom_template.kicad_wks') ``` -------------------------------- ### Generate Documentation Source: https://github.com/mvnmgrx/kiutils/blob/master/docs/usage/development.md Build the project's HTML documentation using Sphinx. Navigate to the docs directory and run the make command. ```text cd docs make html ``` -------------------------------- ### Core Patterns: Loading Files Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Demonstrates how to load a KiCad PCB file using the Board.from_file class method. ```APIDOC ## Loading Files ### Description Loads a KiCad PCB file from the specified path. ### Method `Board.from_file(path: str)` ### Parameters #### Path Parameters - **path** (str) - Required - The file path to the KiCad PCB file. ### Request Example ```python from kiutils.board import Board board = Board.from_file('path/to/your/file.kicad_pcb') ``` ``` -------------------------------- ### Creating New Objects Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/README.md Illustrates how to create new, empty instances of `Board` and `Schematic` objects. ```APIDOC ## Creating New Objects ### Description Creates new, empty KiCad objects. ### Methods - `Board.create_new()` - `Schematic.create_new()` ### Returns - A new `Board` object with standard layers. - A new `Schematic` object. ``` -------------------------------- ### WorkSheet Constructor Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/WorkSheet.md Initializes a new WorkSheet object. It can be created with default values or by providing specific graphic elements and setup. ```APIDOC ## WorkSheet() ### Description Initializes a new WorkSheet object. It can be created with default values or by providing specific graphic elements and setup. ### Parameters - **version** (str) - Optional - Default: KIUTILS_CREATE_NEW_VERSION_STR - Worksheet version using YYYYMMDD date format - **generator** (str) - Optional - Default: KIUTILS_CREATE_NEW_GENERATOR_STR - Program used to write the file - **setup** (Optional[Setup]) - Optional - Default: None - Worksheet setup parameters (margins, scale, etc.) - **lines** (List[Line]) - Optional - Default: [] - Line graphic elements - **rectangles** (List[Rect]) - Optional - Default: [] - Rectangle graphic elements - **polygons** (List[Polygon]) - Optional - Default: [] - Polygon graphic elements - **bitmaps** (List[Bitmap]) - Optional - Default: [] - Embedded bitmap images - **texts** (List[TbText]) - Optional - Default: [] - Text elements (typically title block fields) - **filePath** (Optional[str]) - Optional - Default: None - Path to the `.kicad_wks` file (set by `from_file()`) ### Returns `WorkSheet` - A new WorkSheet object. ``` -------------------------------- ### Load KiCad Board from File Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Use `Board.from_file()` to load a KiCad PCB file. Ensure the file path is correct. ```python Board.from_file('path.kicad_pcb') ``` -------------------------------- ### Define Dimension Type Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/types.md Defines the Dimension dataclass for PCB measurements and annotations, specifying start and end points, units, and layer. ```python @dataclass class Dimension(): """PCB dimension/annotation.""" name: str = "" value: str = "" units: str = "mm" # "mm", "mils", "inches" start: Position = Position() end: Position = Position() layer: str = "Cmts.User" ``` -------------------------------- ### Create Footprint from S-Expression Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/Footprint.md Use this method to convert a parsed S-Expression into a Footprint object. Ensure the S-Expression is a list and starts with 'footprint'. ```python from kiutils.utils import sexpr sexp_data = sexpr.parse_sexp(file_content) footprint = Footprint.from_sexpr(sexp_data) ``` -------------------------------- ### Core Patterns: Creating New Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Illustrates how to create a new, empty KiCad board object. ```APIDOC ## Creating New Board ### Description Creates a new, empty KiCad board object. ### Method `Board.create_new()` ### Request Example ```python from kiutils.board import Board new_board = Board.create_new() ``` ``` -------------------------------- ### Upgrade kiutils Source: https://github.com/mvnmgrx/kiutils/blob/master/README.md Upgrade an existing kiutils installation to the latest version using pip. The --no-cache-dir flag ensures a fresh download. ```bash pip install --no-cache-dir --upgrade kiutils ``` -------------------------------- ### Instantiate and Modify a Library Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/LibraryTable.md Create a Library instance and then deactivate it. Use this to programmatically define and manage library configurations. ```python library = Library( name="My_Resistors", type="KiCad", uri="${KIPRJMOD}/libraries/resistors.kicad_mod", description="Custom resistor footprints" ) # Disable library without removing library.active = False ``` -------------------------------- ### Symbol.libId Property Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/Symbol.md Gets or sets the unique library identifier for the symbol. The format varies depending on whether it's a top-level or child symbol. ```APIDOC ## Symbol.libId Property ### Description Gets or sets the unique library identifier for the symbol. The format of the identifier depends on the symbol's context within the library. ### Method `Symbol.libId` (property) ### Parameters None (This is a property getter/setter) ### Example ```python # Setting the libId for a top-level symbol with a library nickname symbol.libId = "custom:MyOpAmp" # Accessing components of the libId print(symbol.libraryNickname) # Output: "custom" print(symbol.entryName) # Output: "MyOpAmp" # Setting the libId for a child symbol (unit) symbol.libId = "MyOpAmp_1_0" # Accessing components of the libId print(symbol.entryName) # Output: "MyOpAmp" print(symbol.unitId) # Output: 1 print(symbol.styleId) # Output: 0 ``` ### Response #### Success Response - **libId** (str) - The formatted library identifier string. ``` -------------------------------- ### Create and Export a New Board File Source: https://github.com/mvnmgrx/kiutils/blob/master/docs/usage/getting-started.md Use the `create_new()` method to initialize a Board object and then save it to a file with the correct KiCad extension. ```python from kiutils.board import Board board = Board.create_new() # Do stuff .. board.to_file('/my/fancy/project/title.kicad_pcb') ``` -------------------------------- ### Load and Save KiCad Board Source: https://github.com/mvnmgrx/kiutils/blob/master/docs/usage/examples.md Demonstrates how to load a KiCad board file from a specified path and save it. ```python from kiutils.board import Board board = Board().from_file("path/to/board.kicad_pcb") # Do stuff ... board.to_file() ``` -------------------------------- ### Rect Class for Drawing Rectangles Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/WorkSheet.md Represents a rectangle graphic element defined by start and end coordinates, and linewidth. Use this to draw rectangular shapes. ```python @dataclass class Rect(): """Represents a rectangle graphic element.""" startX: float = 0 startY: float = 0 endX: float = 0 endY: float = 0 linewidth: float = 0.15 ``` -------------------------------- ### Line Class for Drawing Lines Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/WorkSheet.md Represents a line graphic element with start and end coordinates, and linewidth. Use this to draw straight lines on the worksheet. ```python @dataclass class Line(): """Represents a line graphic element.""" startX: float = 0 startY: float = 0 endX: float = 0 endY: float = 0 linewidth: float = 0.15 ``` -------------------------------- ### Create New KiCad Files Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/INDEX.md Create new, empty KiCad files for boards and schematics with default settings. These new files must then be explicitly saved. ```python board = Board.create_new() # New board with standard layers sch = Schematic.create_new() # New schematic with root sheet board.to_file('new_board.kicad_pcb') sch.to_file('new_schematic.kicad_sch') ``` -------------------------------- ### Create Board from S-Expression Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/Board.md Use this method to convert a parsed S-Expression, typically from a KiCad PCB file, into a Board object. Ensure the S-Expression is a list and starts with 'kicad_pcb'. ```python from kiutils.utils import sexpr # Parse S-Expression from file content sexp_data = sexpr.parse_sexp(file_content) board = Board.from_sexpr(sexp_data) ``` -------------------------------- ### Activate Virtual Environment Source: https://github.com/mvnmgrx/kiutils/blob/master/CONTRIBUTING.md Activate the newly created virtual environment to manage project dependencies. ```bash source env/bin/activate ``` -------------------------------- ### Convert S-Expression to Schematic Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/Schematic.md Use this method to convert a parsed S-Expression, typically from a KiCad schematic file, into a Schematic object. Ensure the input is a list starting with 'kicad_sch'. ```python from kiutils.utils import sexpr sexp_data = sexpr.parse_sexp(file_content) schematic = Schematic.from_sexpr(sexp_data) ``` -------------------------------- ### Load, Access, Modify, and Save KiCad Board Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/Board.md Demonstrates loading an existing board from a file, accessing its properties like version and counts of footprints and nets, modifying properties and the title block, and saving the changes to the same or a new file. Also shows how to create a new board from scratch. ```python from kiutils.board import Board # Load an existing board board = Board.from_file('circuit.kicad_pcb') # Access board data print(f"Board version: {board.version}") print(f"Number of footprints: {len(board.footprints)}") print(f"Number of nets: {len(board.nets)}") # Modify the board board.properties['custom_key'] = 'custom_value' board.titleBlock.date = '2024-06-26' # Save changes board.to_file() # Or save to a new file board.to_file('modified_circuit.kicad_pcb') # Create a new board from scratch new_board = Board.create_new() new_board.to_file('new_design.kicad_pcb') ``` -------------------------------- ### Get Symbol Library Identifier Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/Symbol.md Retrieves the unique library identifier for a symbol. The format varies based on whether the symbol is top-level and includes a library nickname, or if it's a child symbol (unit). ```python @property def libId(self) -> str ``` -------------------------------- ### Loading Files Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/README.md Demonstrates how to load various KiCad file types into their corresponding Python objects using the `from_file` class method. ```APIDOC ## Loading Files ### Description Loads KiCad files into Python objects. ### Methods - `Board.from_file(filepath)` - `Schematic.from_file(filepath)` - `Footprint.from_file(filepath)` - `Symbol.from_file(filepath)` ### Parameters - **filepath** (string) - The path to the KiCad file to load. ``` -------------------------------- ### Core Patterns: Saving Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Demonstrates saving the board object to a file, optionally specifying a path. ```APIDOC ## Saving Board ### Description Saves the current board object to a KiCad PCB file. ### Method `board.to_file(path: str = None)` ### Parameters #### Path Parameters - **path** (str) - Optional - The file path to save the board to. If not provided, a default path might be used or an error could occur depending on implementation. ### Request Example ```python # Save to a specific file board.to_file('path/to/save/new_file.kicad_pcb') # Save using default path (if applicable) board.to_file() ``` ``` -------------------------------- ### Optimize Lookup with Dictionary Indexing Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/INDEX.md For batch processing large numbers of files, consider creating dictionaries for O(1) lookup of board elements by reference or net name. This improves performance when frequently accessing specific components. ```python # Index for O(1) lookup by_reference = {fp.reference: fp for fp in board.footprints} by_net_name = {net.name: net for net in board.nets} ``` -------------------------------- ### Clone Repository Source: https://github.com/mvnmgrx/kiutils/blob/master/docs/usage/development.md Clone the kiutils repository to your local machine to begin development. ```text git clone https://github.com/mvnmgrx/kiutils.git cd kiutils ``` -------------------------------- ### Run Tests and Generate Report Source: https://github.com/mvnmgrx/kiutils/blob/master/docs/usage/development.md Execute the test suite using the provided script. This will run unittests and generate an HTML report. ```text python3 test.py ``` -------------------------------- ### Add Schematic Symbol from Library Source: https://github.com/mvnmgrx/kiutils/blob/master/docs/usage/examples.md Shows how to load a symbol library, find a specific symbol, create a new schematic, add the symbol to the library and schematic, set its properties, and save the schematic. ```python from kiutils.schematic import Schematic, SymbolInstance, SchematicSymbol from kiutils.symbol import SymbolLib from kiutils.items.common import Property, Position # Load the symbol library symbol_lib = SymbolLib().from_file('/usr/share/kicad/symbols/Device.kicad_sym') # Find the symbol in the library symbol = None for s in symbol_lib.symbols: if s.entryName == 'R_Small_US': symbol = s break if symbol is None: raise ValueError('Symbol not found in library') # Create a new schematic schematic = Schematic.create_new() # Add the symbol to the schematic schematic.libSymbols.append(symbol) schematic_symbol = SchematicSymbol() schematic_symbol.libName = 'R_Small_US' schematic_symbol.libId = 'Device:R_Small_US' schematic_symbol.position = Position(X=0, Y=0, angle=0) schematic_symbol.properties.append(Property(key='Reference', value='R?', id=0)) schematic_symbol.properties.append(Property(key='Value', value='R_Small_US', id=1)) schematic.schematicSymbols.append(schematic_symbol) # Save the schematic to a file schematic.to_file('path_to_save_schematic.kicad_sch') ``` -------------------------------- ### Load, Find, Modify, and Save Library Table Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/LibraryTable.md Demonstrates loading a symbol library table from a file, finding a specific library by name, modifying its description, adding a new library, and saving the updated table. Also shows how to disable inactive libraries. ```python from kiutils.libraries import LibTable, Library # Load symbol library table sym_table = LibTable.from_file('sym_lib_table') # Find specific library custom_lib = None for lib in sym_table.libs: if lib.name == 'custom_components': custom_lib = lib break if custom_lib: print(f"Library: {custom_lib.name}") print(f"Type: {custom_lib.type}") print(f"URI: {custom_lib.uri}") print(f"Active: {custom_lib.active}") # Modify library custom_lib.description = "Updated description" # Add new library new_lib = Library( name="New_Lib", type="KiCad", uri="${KIPRJMOD}/libraries/new.kicad_sym", description="Newly added library" ) sym_table.libs.append(new_lib) # Save changes sym_table.to_file() # Disable all inactive libraries for lib in sym_table.libs: if lib.name.startswith('Old_'): lib.active = False sym_table.to_file() ``` -------------------------------- ### Load and Add Footprint to Board Source: https://github.com/mvnmgrx/kiutils/blob/master/docs/usage/examples.md Illustrates loading a KiCad board and a footprint from their respective files, setting the footprint's position, modifying its text, and appending it to the board. ```python from kiutils.board import Board from kiutils.footprint import Footprint from kiutils.items.common import Position from kiutils.items.fpitems import FpText from os import path # Get current working directory tests_path = path.join(path.dirname(path.realpath(__file__)), 'tests') # Load board file and footprint file board = Board().from_file(path.join(tests_path, "example-project/example/example.kicad_pcb")) footprint = Footprint().from_file(path.join(tests_path, "example-project/example/C_0805.kicad_mod")) # Set new footprint's position footprint.position = Position(X=127.0, Y=85.0) # Change identifier to C105 for item in footprint.graphicItems: if isinstance(item, FpText): if item.type == 'reference': item.text = "C105" # Append footprint to board and save board board.footprints.append(footprint) board.to_file() ``` -------------------------------- ### Analyze PCB Design with Kiutils Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/INDEX.md Load a KiCad PCB file and perform analysis such as counting components, finding specific components, accessing net information, and listing layers. Requires the 'kiutils.board' module. ```python from kiutils.board import Board board = Board.from_file('design.kicad_pcb') # Count components print(f"Footprints: {len(board.footprints)}") # Find specific components resistors = [fp for fp in board.footprints if 'R' in fp.reference] # Access nets for net in board.nets: print(f"Net: {net.name}") # Analyze layers for layer in board.layers: print(f"Layer {layer.ordinal}: {layer.name}") ``` -------------------------------- ### Define Board Design Rules and Settings Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/types.md Stores comprehensive board design rules and manufacturing parameters. Includes stackup details, solder mask and paste margins, track widths, and via sizes. ```python from dataclasses import dataclass from typing import Optional, List @dataclass class SetupData(): """Board design rules and settings.""" stackup: Optional[List] = None solderMaskMargin: Optional[float] = None solderPasteMargin: Optional[float] = None solderPasteMarginRatio: Optional[float] = None trackWidth: Optional[float] = None minTrackWidth: Optional[float] = None viaSize: Optional[float] = None minViaSize: Optional[float] = None # ... many other design parameters ``` -------------------------------- ### Accessing Board Elements with Python Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/getting-started.md Iterate through footprints, pads, nets, layers, graphical items, and zones in a KiCad PCB file. Requires the 'pcb.kicad_pcb' file. ```python from kiutils.board import Board board = Board.from_file('pcb.kicad_pcb') # Iterate footprints for footprint in board.footprints: print(f"{footprint.reference} at ({footprint.position.X}, {footprint.position.Y})") # Access pads for pad in footprint.pads: if pad.type == "smd": print(f" Pad {pad.number}: SMD {pad.shape}") # Find nets for net in board.nets: print(f"Net {net.number}: {net.name}") # Access layers for layer in board.layers: print(f"Layer {layer.ordinal}: {layer.name} ({layer.type})") # Access graphical items for item in board.graphicItems: print(f"Graphic item: {type(item).__name__}") # Access zones for zone in board.zones: print(f"Zone connected to net: {zone.net.name if zone.net else 'None'}") ``` -------------------------------- ### Load, Access, Modify, and Save Symbol Libraries Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/Symbol.md Demonstrates loading a symbol library from a file, iterating through symbols and pins, modifying symbol properties, and saving the library. ```python from kiutils.symbol import Symbol, SymbolLib # Load a symbol library lib = SymbolLib.from_file('custom_components.kicad_sym') # Access symbols for symbol in lib.symbols: print(f"Symbol: {symbol.entryName}") print(f" Pins: {len(symbol.pins)}") for pin in symbol.pins: print(f" {pin.number}: {pin.name} ({pin.electricalType})") # Modify a symbol symbol = lib.symbols[0] symbol.inBom = True symbol.onBoard = True # Access properties for prop in symbol.properties: if prop.key == 'Reference': print(f"Reference: {prop.value}") # Save library lib.to_file('custom_components_modified.kicad_sym') # Work with single symbol from schematic symbol = Symbol() symbol.libId = "Device:R" symbol.entryName # Returns "R" symbol.libraryNickname # Returns "Device" # Work with unit symbols symbol.libId = "IC_OpAmp_1_1" # Now it's a unit symbol with unitId=1, styleId=1 ``` -------------------------------- ### Create a Library Object Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/LibraryTable.md Instantiate a Library object with its properties. This is useful for defining custom library entries. ```python from dataclasses import dataclass @dataclass class Library(): """Represents a single library entry in a library table.""" name: str type: str uri: str options: str = "" description: str = "" active: bool = True @classmethod def from_sexpr(cls, exp: list) -> Library: pass # Implementation omitted for brevity def to_sexpr(self, indent: int = 2, newline: bool = True) -> str: pass # Implementation omitted for brevity ``` -------------------------------- ### Load KiCad Files Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/README.md Load KiCad PCB, schematic, footprint, and symbol files using their respective classes. Ensure the files exist in the specified path. ```python from kiutils.board import Board from kiutils.schematic import Schematic from kiutils.footprint import Footprint from kiutils.symbol import Symbol board = Board.from_file('design.kicad_pcb') sch = Schematic.from_file('circuit.kicad_sch') fp = Footprint.from_file('component.kicad_mod') sym = Symbol.from_file('symbol.kicad_sym') ``` -------------------------------- ### Create Complex PCB Structures Programmatically Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/advanced-topics.md Use KiUtils to programmatically create new PCB designs, add nets, traces, and vias. This is useful for automated board generation or complex design modifications. ```python from kiutils.board import Board from kiutils.footprint import Footprint from kiutils.items.brditems import Segment, Via from kiutils.items.common import Position, Net board = Board.create_new() # Add nets net_power = Net(number=1, name="VCC") net_gnd = Net(number=2, name="GND") board.nets.extend([net_power, net_gnd]) # Add traces segment = Segment( start=Position(X=10.0, Y=10.0), end=Position(X=20.0, Y=20.0), layer="F.Cu", width=0.25, net=net_power ) board.traceItems.append(segment) # Add vias via = Via( position=Position(X=15.0, Y=15.0), diameter=0.3, drill=0.15, layers=["F.Cu", "B.Cu"], net=net_gnd ) board.traceItems.append(via) board.to_file('generated_board.kicad_pcb') ``` -------------------------------- ### Parse, Modify, and Re-export a Board File Source: https://github.com/mvnmgrx/kiutils/blob/master/docs/usage/getting-started.md Load an existing board file using `from_file()`, make modifications, and then save the changes. If no path is provided to `to_file()`, the original file path is used. ```python from kiutils.board import Board board = Board.from_file('/my/fancy/project/title.kicad_pcb') # Do stuff .. board.to_file() ``` -------------------------------- ### Complete File Reading with Board.from_file Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/utilities.md Reads and parses a KiCad PCB file in a single step using the Board.from_file method. Ensure the file path is correct. ```python from kiutils.utils import sexpr from kiutils.board import Board # Read and parse in one step board = Board.from_file('circuit.kicad_pcb') ``` -------------------------------- ### Load Board from File Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/Board.md Load a KiCad PCB design directly from a file path. This method automatically sets the `filePath` attribute of the returned Board object. An optional encoding can be specified. ```python board = Board.from_file('/path/to/design.kicad_pcb') print(f"Board loaded from: {board.filePath}") ``` -------------------------------- ### Compare KiCad Designs for Differences Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/advanced-topics.md Compare two KiCad PCB designs to identify added or removed footprints and nets. Requires two design files as input. ```python from kiutils.board import Board from dataclasses import asdict board1 = Board.from_file('design_v1.kicad_pcb') board2 = Board.from_file('design_v2.kicad_pcb') # Compare footprints refs_v1 = {fp.reference for fp in board1.footprints} refs_v2 = {fp.reference for fp in board2.footprints} added = refs_v2 - refs_v1 removed = refs_v1 - refs_v2 print(f"Added components: {added}") print(f"Removed components: {removed}") # Compare nets nets_v1 = {net.name for net in board1.nets} nets_v2 = {net.name for net in board2.nets} print(f"New nets: {nets_v2 - nets_v1}") print(f"Removed nets: {nets_v1 - nets_v2}") ``` -------------------------------- ### Create New KiCad Designs Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/README.md Create new, empty KiCad board and schematic designs. The new board includes standard layers. ```python board = Board.create_new() # New board with standard layers sch = Schematic.create_new() # New schematic ``` -------------------------------- ### Footprint Constructor Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/Footprint.md Initializes a new Footprint object. All parameters are optional and have default values. ```APIDOC ## Footprint Constructor ### Description Initializes a new Footprint object with various attributes. ### Parameters - **entryName** (str) - Optional - The name of the footprint from the library. - **reference** (str) - Optional - Reference designator (e.g., "U1", "R5"). Defaults to "REF**". - **value** (str) - Optional - Component value (e.g., "100k", "STM32H743"). - **datasheet** (str) - Optional - URL or path to component datasheet. - **attributes** (Optional[Attributes]) - Optional - Footprint attributes (SMD, through-hole, etc.). - **position** (Optional[Position]) - Optional - X, Y coordinates and rotation angle. - **locked** (bool) - Optional - Whether the footprint is locked for editing. Defaults to False. - **placed** (bool) - Optional - Whether the footprint has been placed. Defaults to False. - **layer** (str) - Optional - Layer the footprint resides on (typically "F.Cu" or "B.Cu"). Defaults to "F.Cu". - **tstamp** (Optional[str]) - Optional - Unique timestamp identifier. - **uuid** (Optional[str]) - Optional - Universally unique identifier. - **properties** (List[Property]) - Optional - Custom key-value properties. Defaults to an empty list. - **pads** (List[Pad]) - Optional - List of pads in the footprint. Defaults to an empty list. - **zones** (List[Zone]) - Optional - Zones defined within the footprint. Defaults to an empty list. - **models** (List[Model]) - Optional - 3D model references for visualization. Defaults to an empty list. - **graphicItems** (List) - Optional - Silkscreen, courtyard, and other graphical elements. Defaults to an empty list. - **filePath** (Optional[str]) - Optional - Path to the `.kicad_mod` file (set by `from_file()`). ``` -------------------------------- ### Batch Process PCB Files Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/getting-started.md Iterate through all PCB files in a directory, load them, and print component counts. Includes basic error handling for individual files. ```python from kiutils.board import Board from pathlib import Path # Process all PCB files in a directory pcb_dir = Path('projects/') for pcb_file in pcb_dir.glob('*.kicad_pcb'): try: board = Board.from_file(str(pcb_file)) print(f"{pcb_file.name}: {len(board.footprints)} components") # Perform analysis or modifications for fp in board.footprints: if fp.attributes.excludeFromBom: print(f" - {fp.reference} excluded from BOM") except Exception as e: print(f"Error processing {pcb_file}: {e}") ``` -------------------------------- ### Saving Files Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/README.md Shows how to save `Board` objects back to files, either to their original location or a new specified path. ```APIDOC ## Saving Files ### Description Saves `Board` objects to KiCad PCB files. ### Methods - `board.to_file()` - `board.to_file(new_filepath)` ### Parameters - **new_filepath** (string, Optional) - The new path to save the file to. If not provided, saves to the original file location. ``` -------------------------------- ### Load and Save PCB Board Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/getting-started.md Load an existing PCB file, access its data, modify the title block, and save it. Also shows how to create and save a new, blank board. ```python from kiutils.board import Board # Load an existing board board = Board.from_file('circuit.kicad_pcb') # Access board data print(f"Footprints: {len(board.footprints)}") print(f"Nets: {len(board.nets)}") # Modify and save board.titleBlock.date = '2024-06-26' board.to_file() # Saves to original location # Save to a different file board.to_file('modified.kicad_pcb') # Create new board new_board = Board.create_new() new_board.to_file('blank_board.kicad_pcb') ``` -------------------------------- ### Analyze Large PCB Designs by Footprint Prefix Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/advanced-topics.md Optimize analysis of large PCB designs by indexing footprints using a defaultdict. This allows for fast lookup and aggregation of components based on their reference prefix. ```python from kiutils.board import Board from collections import defaultdict board = Board.from_file('large_design.kicad_pcb') # Index footprints by reference prefix for fast lookup footprints_by_prefix = defaultdict(list) for fp in board.footprints: prefix = ''.join([c for c in fp.reference if not c.isdigit()]) footprints_by_prefix[prefix].append(fp) # Analyze by prefix for prefix, fps in footprints_by_prefix.items(): print(f"{prefix}: {len(fps)} components") # Create net name mapping net_map = {net.number: net.name for net in board.nets} # Process pads with fast net lookup for fp in board.footprints: for pad in fp.pads: if pad.net: net_name = net_map.get(pad.net.number, "Unknown") ``` -------------------------------- ### Board.create_new Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/Board.md Creates a new, empty Board object with default attributes and all standard KiCad layers initialized. ```APIDOC ## Board.create_new ### Description Creates a new empty board with default attributes and all standard KiCad layers. ### Method `classmethod` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Returns - `Board` — A new board with version, generator, and standard layers initialized ### Example ```python board = Board.create_new() # Board now has 29 standard layers (F.Cu, B.Cu, F.SilkS, etc.) # and a default net (net0) ``` ``` -------------------------------- ### Accessing and Adding Board Properties Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/advanced-topics.md Demonstrates how to access existing board properties and add new custom properties to a KiCad board file using KiUtils. Requires importing 'Board' from 'kiutils.board'. ```python from kiutils.board import Board from kiutils.items.common import Property board = Board.from_file('design.kicad_pcb') # Access board properties for key, value in board.properties.items(): print(f"Property: {key} = {value}") # Add custom properties board.properties['design_version'] = '1.0' board.properties['designer'] = 'John Doe' board.properties['status'] = 'prototype' # Iterate symbols with properties from kiutils.schematic import Schematic sch = Schematic.from_file('circuit.kicad_sch') for symbol in sch.schematicSymbols: for prop in symbol.properties: print(f"{symbol.reference}: {prop.key} = {prop.value}") ``` -------------------------------- ### Board.from_file Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/Board.md Loads a board directly from a KiCad PCB file. This method automatically sets the `filePath` attribute of the resulting Board object. ```APIDOC ## Board.from_file ### Description Loads a board directly from a KiCad PCB file and automatically sets the `filePath` attribute. ### Method `classmethod` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **filepath** (`str`) - Required - Path to the `.kicad_pcb` file - **encoding** (`Optional[str]`) - Optional - File encoding (defaults to platform encoding) ### Returns - `Board` — Object loaded from the file with `filePath` attribute set ### Raises - `Exception` — If the given path is not a valid file ### Example ```python board = Board.from_file('/path/to/design.kicad_pcb') print(f"Board loaded from: {board.filePath}") ``` ``` -------------------------------- ### Initialize Symbol Constructor Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/Symbol.md Initializes a new Symbol object with various optional and required parameters. This includes library information, display settings, BOM properties, graphical items, pins, and child units. ```python Symbol( libraryNickname: Optional[str] = None, entryName: str = None, unitId: Optional[int] = None, styleId: Optional[int] = None, extends: Optional[str] = None, hidePinNumbers: bool = False, pinNames: bool = False, pinNamesHide: bool = False, pinNamesOffset: Optional[float] = None, inBom: Optional[bool] = None, onBoard: Optional[bool] = None, isPower: bool = False, properties: List[Property] = [], graphicItems: List = [], pins: List[SymbolPin] = [], units: List[Symbol] = [], filePath: Optional[str] = None ) ``` -------------------------------- ### Create New Empty Board Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/Board.md Instantiate a new, empty Board object with default attributes and all standard KiCad layers pre-initialized. This is useful for creating new designs programmatically. ```python board = Board.create_new() # Board now has 29 standard layers (F.Cu, B.Cu, F.SilkS, etc.) # and a default net (net0) ``` -------------------------------- ### Run KiUtils Tests Source: https://github.com/mvnmgrx/kiutils/blob/master/CONTRIBUTING.md Execute the unittests for KiUtils from the project's root directory. A test report will be automatically generated. ```bash python test.py ``` -------------------------------- ### Load, Iterate, and Modify KiCad Design Rules Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/api-reference/DesignRules.md Demonstrates loading design rules from a file, iterating through rules and constraints, finding specific constraints, modifying them, creating new rules with constraints, and saving the modified rules back to a file. Constraints can include units like 'mm', 'mil', or 'in'. ```python from kiutils.dru import DesignRules, Rule, Constraint # Load existing design rules dru = DesignRules.from_file('design_rules.kicad_dru') # Iterate over rules for rule in dru.rules: print(f"Rule: {rule.name}") for constraint in rule.constraints: print(f" {constraint.type}:") print(f" Min: {constraint.min}") print(f" Opt: {constraint.opt}") print(f" Max: {constraint.max}") # Find specific rule trace_width_rule = None for rule in dru.rules: for constraint in rule.constraints: if constraint.type == 'track_width': trace_width_rule = rule break # Modify constraint if trace_width_rule: for constraint in trace_width_rule.constraints: if constraint.type == 'track_width': constraint.min = '0.15mm' constraint.opt = '0.25mm' # Create new rule with constraints new_rule = Rule(name="HighSpeed") new_rule.constraints.append(Constraint( type="track_width", min="0.3mm", opt="0.5mm", max="1.0mm", elements=["track"] )) new_rule.constraints.append(Constraint( type="clearance", min="0.2mm", elements=["track", "pad"] )) dru.rules.append(new_rule) # Save modified rules dru.to_file('design_rules_modified.kicad_dru') ``` -------------------------------- ### Clone KiUtils Repository Source: https://github.com/mvnmgrx/kiutils/blob/master/CONTRIBUTING.md Clone the KiUtils repository to your local machine and navigate into the project directory. ```bash git clone https://github.com//kiutils cd kiutils ``` -------------------------------- ### Analyze PCB Design with Kiutils Source: https://github.com/mvnmgrx/kiutils/blob/master/_autodocs/README.md Read a KiCad PCB file and print basic design information such as the number of components, nets, and layers. It also iterates through footprints to show their reference and pad count. ```python from kiutils.board import Board board = Board.from_file('design.kicad_pcb') print(f"Components: {len(board.footprints)}") print(f"Nets: {len(board.nets)}") print(f"Layers: {len(board.layers)}") for fp in board.footprints: print(f" {fp.reference}: {len(fp.pads)} pads") ```