API Referenceο
This section contains the complete API reference for Circuit Synth.
Core Moduleο
Core circuit primitives and utilities
- class circuit_synth.core.Circuit(name=None, description=None, auto_comments=True)[source]ο
Bases:
object- class Component(symbol: str, ref: str | None = None, value: str | None = None, footprint: str | None = None, datasheet: str | None = None, description: str | None = None, **kwargs)ο
Bases:
SimplifiedPinAccessRepresents an electronic component that references a KiCad symbol.
If multiple pins share the same name (e.g. βGNDβ), __getitem__ returns a PinGroup, so something like:
comp[βGNDβ] += net
will connect all GND pins to that net.
Additional fields can be passed as keyword arguments and will be stored in _extra_fields for later access (e.g., mfg_part_num, tolerance, etc.).
- ALLOWED_REASSIGN = {'value'}ο
- __call__(*args, **kwargs)ο
Cloning a prefix-based ref is allowed, but final references are not.
- __init__(symbol: str, ref: str | None = None, value: str | None = None, footprint: str | None = None, datasheet: str | None = None, description: str | None = None, **kwargs)ο
Initialize Component with support for arbitrary additional fields.
- Parameters:
symbol β KiCad symbol reference (e.g., βDevice:Rβ)
ref β Component reference (e.g., βR1β)
value β Component value (e.g., β10kβ)
footprint β KiCad footprint reference
datasheet β URL to component datasheet
description β Component description
**kwargs β Additional fields (e.g., mfg_part_num, tolerance, etc.)
- add_annotation(annotation)[source]ο
Add a text annotation (TextProperty, TextBox, etc.) to this circuit.
- add_image(image_path: str, position: tuple, scale: float = 1.0)[source]ο
Add an embedded image to the schematic.
Images are embedded as base64-encoded data in the KiCad schematic file. The image file is read when the schematic is generated, so it only needs to exist at generation time.
- Parameters:
image_path β Path to image file (PNG, JPG, etc.)
position β Tuple of (x, y) position in mm
scale β Scale factor (1.0 = original size, 2.0 = 2x larger, etc.)
- Returns:
The created Image annotation object
- Return type:
Image
Example
>>> circuit.add_image("logo.png", position=(100, 50), scale=2.0)
- add_subcircuit(subcirc: Circuit)[source]ο
Add a subcircuit and establish parent-child relationship
- property componentsο
Get components dictionary for compatibility.
- generate_bom(output_file: str | None = None, project_name: str | None = None, fields: str | None = None, labels: str | None = None, group_by: str | None = None, exclude_dnp: bool = False) Dict[str, Any][source]ο
Generate a Bill of Materials (BOM) from this circuit as a CSV file.
This method creates a KiCad project if one doesnβt already exist, then exports the schematic to a CSV BOM file using kicad-cli.
- Parameters:
output_file β Path where CSV BOM should be written. If not provided, defaults to {project_name}/{project_name}.csv
project_name β Name of the KiCad project directory. If not provided, defaults to the circuit name. Required if output_file is provided but needs a project.
fields β Comma-separated fields to export from schematic. If not specified, KiCad will export default fields (Refs, Value, Footprint, etc.)
labels β Comma-separated column headers for the BOM. Must match the number of fields if fields are specified.
group_by β Field to group references by when exporting. Common values: βValueβ (group by component value), βFootprintβ, etc.
exclude_dnp β If True, exclude βDo not populateβ components from BOM
- Returns:
- Result dictionary containing:
success (bool): True if BOM was successfully generated
file (Path): Path to the generated CSV file
component_count (int): Number of components in the BOM
project_path (Path): Path to the KiCad project directory
error (str, optional): Error message if generation failed
- Return type:
Example
>>> circuit = led_blinker() >>> result = circuit.generate_bom(project_name="led_blinker") >>> print(f"BOM exported to: {result['file']}") >>> print(f"Component count: {result['component_count']}")
- Raises:
FileNotFoundError β If kicad-cli is not available
RuntimeError β If BOM export fails
- generate_flattened_json_netlist(filename: str) None[source]ο
Produce a flattened JSON representation for this circuit + subcircuits.
- generate_full_netlist() str[source]ο
- Print a hierarchical netlist showing:
Each circuit + subcircuit (name, components, and optional description)
A single combined net listing from all circuits
- generate_gerbers(output_dir: str | None = None, project_name: str | None = None, include_drill: bool = True, drill_format: str = 'excellon') Dict[str, Any][source]ο
Generate Gerber files for PCB manufacturing from this circuit.
This method creates a complete KiCad project (including PCB) if one doesnβt already exist, then exports Gerber files for manufacturing using kicad-cli. Gerbers can be submitted directly to manufacturers like JLCPCB, PCBWay, etc.
- Parameters:
output_dir β Directory where Gerber files should be written. If not provided, defaults to {project_name}/gerbers
project_name β Name of the KiCad project directory. If not provided, defaults to the circuit name.
include_drill β Also export drill files along with Gerbers (default: True)
drill_format β Format for drill files: βexcellonβ (default) or βgerberβ
- Returns:
- Result dictionary containing:
success (bool): True if Gerbers were successfully generated
gerber_files (list): List of Path objects to generated .gbr files
drill_files (tuple): Tuple of (plated_holes_file, non_plated_holes_file) or None
project_path (Path): Path to the KiCad project directory
output_dir (Path): Directory where Gerbers were exported
error (str, optional): Error message if generation failed
- Return type:
Example
>>> circuit = esp32_board() >>> result = circuit.generate_gerbers(project_name="esp32_board") >>> print(f"Gerbers exported to: {result['output_dir']}") >>> print(f"Files: {len(result['gerber_files'])} Gerber files")
- Requirements:
KiCad 8.0 or later
kicad-cli must be available in PATH
Circuit must be complete with all components and connections
Notes
First run generates full KiCad project including PCB (slower)
Subsequent runs reuse existing project (faster)
Default layers: F.Cu, B.Cu, F.Mask, B.Mask, F.SilkS, B.SilkS, F.Paste, B.Paste, Edge.Cuts
Gerbers use standard Protel file extension format (.gbr, .gbl, etc.)
Compatible with JLCPCB, PCBWay, OSH Park, and most PCB manufacturers
- generate_json_netlist(filename: str) None[source]ο
Generate a JSON representation of this circuit and its hierarchy, then write it out to βfilenameβ.
- generate_kicad_netlist(filename: str) None[source]ο
Generate a KiCad netlist (.net) file for this circuit and its hierarchy.
- generate_kicad_project(project_name: str, generate_pcb: bool = True, force_regenerate: bool = False, placement_algorithm: str = 'hierarchical', draw_bounding_boxes: bool = False, generate_ratsnest: bool = True, update_source_refs: bool | None = None, preserve_user_components: bool = False) Dict[str, Any][source]ο
Generate a complete KiCad project (schematic + PCB) from this circuit.
This method provides a simplified API that handles all the boilerplate setup required for KiCad project generation, creating the project directory and generating KiCad files with an automatic JSON netlist in the project directory.
- Parameters:
project_name β Name of the KiCad project and directory to create
generate_pcb β Whether to generate PCB in addition to schematic (default: True)
force_regenerate β Force regeneration of existing files, losing manual edits (default: False)
placement_algorithm β Component placement algorithm to use (default: βhierarchicalβ)
draw_bounding_boxes β Whether to draw visual bounding boxes around components (default: False)
generate_ratsnest β Whether to generate ratsnest connections in PCB (default: True)
update_source_refs β Whether to update source file with finalized refs. None (default): Auto-update unless force_regenerate=True True: Always update source file False: Never update source file
preserve_user_components β Keep components in KiCad that donβt exist in Python (default: False) False: Python is source of truth - delete components not in Python True: Preserve all components in KiCad, even if not in Python
- Returns:
- Result dictionary containing:
success (bool): Whether generation succeeded
json_path (Path): Path to the canonical JSON netlist
project_path (Path): Path to the KiCad project directory
error (str, optional): Error message if generation failed
- Return type:
Example
>>> circuit = esp32s3_simple() >>> result = circuit.generate_kicad_project("esp32s3_simple") >>> print(f"JSON netlist: {result['json_path']}") >>> print(f"KiCad project: {result['project_path']}")
- generate_pdf_schematic(output_file: str | None = None, project_name: str | None = None, black_and_white: bool = False, theme: str | None = None, exclude_drawing_sheet: bool = False, pages: str | None = None) Dict[str, Any][source]ο
Generate a PDF schematic from this circuit.
This method creates a KiCad project if one doesnβt already exist, then exports the schematic to a PDF file using kicad-cli.
- Parameters:
output_file β Path where PDF should be written. If not provided, defaults to {project_name}/{project_name}.pdf
project_name β Name of the KiCad project directory. If not provided, defaults to the circuit name.
black_and_white β Export in black and white instead of color (default: False)
theme β Color theme to use for export (optional). Theme name depends on KiCad installation.
exclude_drawing_sheet β Exclude the drawing sheet/border from PDF (default: False)
pages β Page range to export (e.g., β1,3-5β for pages 1, 3, 4, 5). If not specified, all pages are exported.
- Returns:
- Result dictionary containing:
success (bool): True if PDF was successfully generated
file (Path): Path to the generated PDF file
project_path (Path): Path to the KiCad project directory
error (str, optional): Error message if generation failed
- Return type:
Example
>>> circuit = led_blinker() >>> result = circuit.generate_pdf_schematic(project_name="led_blinker") >>> print(f"PDF exported to: {result['file']}")
- Raises:
FileNotFoundError β If kicad-cli is not available
RuntimeError β If PDF export fails
- property netsο
Return a dictionary of all nets in this circuit.
- simulate()[source]ο
Create a simulator instance for this circuit.
This method provides access to circuit simulation capabilities using PySpice as the backend. The returned simulator object can be used to run various analyses such as DC operating point, transient, and AC.
- Returns:
Simulator object for running analyses
- Return type:
CircuitSimulator
Example
>>> circuit = voltage_divider() >>> sim = circuit.simulate() >>> result = sim.operating_point()
- Raises:
ImportError β If simulation dependencies are not installed
CircuitSynthError β If circuit cannot be converted for simulation
- simulator()[source]ο
Alias for simulate() method for backward compatibility.
- Returns:
Simulator object for running analyses
- Return type:
CircuitSimulator
- property subcircuitsο
Get subcircuits list.
- to_dict() Dict[str, Any][source]ο
Return a hierarchical dictionary representation of this circuit, including subcircuits, components (as a dictionary keyed by reference), and net connections.
- class circuit_synth.core.Component(symbol: str, ref: str | None = None, value: str | None = None, footprint: str | None = None, datasheet: str | None = None, description: str | None = None, **kwargs)[source]ο
Bases:
SimplifiedPinAccessRepresents an electronic component that references a KiCad symbol.
If multiple pins share the same name (e.g. βGNDβ), __getitem__ returns a PinGroup, so something like:
comp[βGNDβ] += net
will connect all GND pins to that net.
Additional fields can be passed as keyword arguments and will be stored in _extra_fields for later access (e.g., mfg_part_num, tolerance, etc.).
- ALLOWED_REASSIGN = {'value'}ο
- __call__(*args, **kwargs)[source]ο
Cloning a prefix-based ref is allowed, but final references are not.
- __init__(symbol: str, ref: str | None = None, value: str | None = None, footprint: str | None = None, datasheet: str | None = None, description: str | None = None, **kwargs)[source]ο
Initialize Component with support for arbitrary additional fields.
- Parameters:
symbol β KiCad symbol reference (e.g., βDevice:Rβ)
ref β Component reference (e.g., βR1β)
value β Component value (e.g., β10kβ)
footprint β KiCad footprint reference
datasheet β URL to component datasheet
description β Component description
**kwargs β Additional fields (e.g., mfg_part_num, tolerance, etc.)
- class circuit_synth.core.Net(name: str | None = None, is_power: bool | None = None, power_symbol: str | None = None, trace_current: float | None = None, impedance: float | None = None, **properties: Any)[source]ο
Bases:
objectA Net represents an electrical node (set of pins).
Supports: - Automatic power net detection (GND, VCC, etc.) - Explicit power net declaration - Physical constraints (trace current, impedance) - Custom properties - Differential pairs (via KiCad naming conventions)
Examples
# Auto-detected power net (recommended) >>> gnd = Net(name=βGNDβ) # Automatically becomes power net
# Explicit power net >>> vcc = Net(name=βVCCβ, is_power=True, power_symbol=βpower:VCCβ)
# Prevent auto-detection >>> not_power = Net(name=βGND_SENSEβ, is_power=False)
# Differential pair (KiCad detects automatically by name) >>> usb_dp = Net(name=βUSB_DPβ, impedance=90) # KiCad pairs USB_DP/USB_DN >>> usb_dn = Net(name=βUSB_DNβ, impedance=90)
# High current trace >>> power_5v = Net(name=β+5Vβ, trace_current=2000) # 2A, auto-detected as power
# Custom properties >>> rf = Net(name=βRF_OUTβ, impedance=50, substrate_height=1.6)
Note
Differential pairs use KiCad naming conventions (_P/_N, +/-, etc.). KiCad automatically detects and routes them as differential pairs.
- __iadd__(other)[source]ο
net += pin => pin connects to this net net += net => unify (if different) by bringing other netβs pins over
- __init__(name: str | None = None, is_power: bool | None = None, power_symbol: str | None = None, trace_current: float | None = None, impedance: float | None = None, **properties: Any)[source]ο
Create an electrical net.
- Parameters:
name β Net name (e.g., βGNDβ, βUSB_DPβ). Auto-generated if None. For differential pairs, use KiCad naming conventions: - NAME_P / NAME_N (e.g., USB_DP / USB_DN) - NAME+ / NAME- (e.g., ETH_TX+ / ETH_TX-)
is_power β Power net flag. None (default) = auto-detect from name, True = explicitly mark as power net, False = explicitly NOT a power net.
power_symbol β KiCad power symbol (e.g., βpower:GNDβ). Auto-filled if is_power is auto-detected.
trace_current β Maximum current in milliamps (mA).
impedance β Target impedance in ohms for controlled impedance routing. For differential pairs, this is the differential impedance.
**properties β Custom properties for specialized applications.
Note
Differential pairs are detected automatically by KiCad based on net naming. Use matching prefixes with _P/_N, +/-, or similar suffixes.
- static from_dict(data: Dict[str, Any]) Net[source]ο
Deserialize Net from dictionary.
Note: This creates a Net outside of circuit context, so it wonβt auto-register. Caller must manually add to circuit._nets.
- property pinsο
- class circuit_synth.core.Pin(name: str, num: str, func: str | PinType, unit: int = 1, **kwargs)[source]ο
Bases:
objectMinimal Pin class for net connectivity.
No dedicated geometry fields in the constructor (x, y, length, orientation).
We do accept **kwargs so geometry can be passed (and ignored by core), but stored for schematic export.
- __iadd__(other)[source]ο
Support pin += net, or pin += pin.
- Parameters:
other β Either a Net or another Pin to connect to
- Returns:
Self, for chaining
- Return type:
- Raises:
TypeError β If other is not a Net or Pin
ValueError β If pin types are incompatible
- connect_to_net(net: Net)[source]ο
If already on another net, remove from old net. Then join the new net.
- Parameters:
net β The Net to connect this pin to
- Raises:
ValueError β If connecting would create an invalid pin type combination
- circuit_synth.core.circuit(_func=None, *, name=None, comments=True)[source]ο
- Decorator that can be used in three ways:
@circuit def my_circuit(β¦):
β¦
@circuit(name=βsomeCircuitNameβ) def my_circuit(β¦):
β¦
@circuit(name=βsomeCircuitNameβ, comments=False) def my_circuit(β¦):
β¦
Creates a new Circuit object, optionally using name as the circuit name. If comments=True (default), the functionβs docstring will be added as a text annotation on the generated schematic. If thereβs an existing current circuit (the βparentβ), the new circuit is attached to the parent as a subcircuit. Then references are finalized before returning the child circuit.
- exception circuit_synth.core.ComponentError[source]ο
Bases:
CircuitSynthErrorRaised when there is an error with a component or its pins.
- exception circuit_synth.core.ValidationError[source]ο
Bases:
CircuitSynthErrorRaised when a property validation fails.
- exception circuit_synth.core.CircuitSynthError[source]ο
Bases:
ExceptionBase exception for all Circuit Synth errors.
- class circuit_synth.core.DependencyContainer[source]ο
Bases:
IDependencyContainerConcrete implementation of dependency injection container.
Provides registration and resolution of dependencies with support for different lifetime scopes and automatic dependency injection.
- get_registrations() Dict[Type, DependencyRegistration][source]ο
Get all registrations (for debugging)
- register_factory(interface: Type[T], factory: Callable[[], T]) None[source]ο
Register a factory function
- register_singleton(interface: Type[T], implementation: Type[T]) None[source]ο
Register a singleton dependency
- class circuit_synth.core.ServiceLocator[source]ο
Bases:
objectService locator pattern implementation for global access to the container.
Provides a global point of access to the dependency container while maintaining testability through container replacement.
- classmethod get_container() IDependencyContainer[source]ο
Get the global container
- classmethod is_registered(interface: Type[T]) bool[source]ο
Check if an interface is registered in the global container
- classmethod set_container(container: IDependencyContainer) None[source]ο
Set the global container
- class circuit_synth.core.IDependencyContainer[source]ο
Bases:
ABCAbstract interface for dependency container
- abstractmethod is_registered(interface: Type[T]) bool[source]ο
Check if an interface is registered
- abstractmethod register_factory(interface: Type[T], factory: Callable[[], T]) None[source]ο
Register a factory function
- abstractmethod register_instance(interface: Type[T], instance: T) None[source]ο
Register a specific instance
- abstractmethod register_singleton(interface: Type[T], implementation: Type[T]) None[source]ο
Register a singleton dependency
- circuit_synth.core.replace_components(circuit: Circuit, match: Dict[str, str], update: Dict[str, str], dry_run: bool = False) ReplacementResult[source]ο
Replace property values for components matching criteria.
Finds all components with properties matching the match criteria and updates their properties with values from update.
- Parameters:
circuit β Circuit to modify
match β Property criteria to match (e.g., {βMPNβ: βASD123β})
update β Properties to update (e.g., {βMPNβ: βFGS032β, βManufacturerβ: βNewCoβ})
dry_run β If True, donβt actually modify, just return what would change
- Returns:
ReplacementResult with count and list of affected components
Example
>>> circuit = cs.Circuit("Test") >>> r1 = cs.Component("Device:R", ref="R", value="10k") >>> r1.MPN = "ASD123" >>> circuit.add_component(r1) >>> circuit.finalize_references() >>> >>> # Replace MPN >>> result = cs.replace_components( ... circuit, ... match={"MPN": "ASD123"}, ... update={"MPN": "FGS032"} ... ) >>> print(result.count) # 1 >>> print(r1.MPN) # "FGS032"
- circuit_synth.core.replace_multiple(circuit: Circuit, replacements: List[Dict[str, any]], dry_run: bool = False) ReplacementResult[source]ο
Apply multiple replacement operations in sequence.
Each replacement in the list should have βmatchβ and βupdateβ dicts.
- Parameters:
circuit β Circuit to modify
replacements β List of replacement specs, each with βmatchβ and βupdateβ
dry_run β If True, donβt actually modify
- Returns:
Combined ReplacementResult from all operations
Example
>>> replacements = [ ... { ... "match": {"MPN": "ASD123"}, ... "update": {"MPN": "FGS032", "Manufacturer": "NewCo"} ... }, ... { ... "match": {"MPN": "OLD456"}, ... "update": {"MPN": "NEW789"} ... } ... ] >>> result = cs.replace_multiple(circuit, replacements) >>> print(f"Total replaced: {result.count}")
- circuit_synth.core.find_replaceable_components(circuit: Circuit, match: Dict[str, str]) List[str][source]ο
Find components that match criteria without modifying them.
Useful for previewing what would be affected by a replacement operation.
- Parameters:
circuit β Circuit to search
match β Property criteria to match
- Returns:
List of component references that match criteria
Example
>>> # Find all components with specific MPN >>> matches = cs.find_replaceable_components( ... circuit, ... match={"MPN": "ASD123"} ... ) >>> print(f"Would affect: {matches}")
- class circuit_synth.core.ReplacementResult(count: int, affected_components: List[str], warnings: List[str], errors: List[str])[source]ο
Bases:
objectResults from bulk component replacement operation.
Circuitο
- class circuit_synth.core.circuit.Circuit(name=None, description=None, auto_comments=True)[source]ο
Bases:
object- class Component(symbol: str, ref: str | None = None, value: str | None = None, footprint: str | None = None, datasheet: str | None = None, description: str | None = None, **kwargs)ο
Bases:
SimplifiedPinAccessRepresents an electronic component that references a KiCad symbol.
If multiple pins share the same name (e.g. βGNDβ), __getitem__ returns a PinGroup, so something like:
comp[βGNDβ] += net
will connect all GND pins to that net.
Additional fields can be passed as keyword arguments and will be stored in _extra_fields for later access (e.g., mfg_part_num, tolerance, etc.).
- ALLOWED_REASSIGN = {'value'}ο
- __call__(*args, **kwargs)ο
Cloning a prefix-based ref is allowed, but final references are not.
- __init__(symbol: str, ref: str | None = None, value: str | None = None, footprint: str | None = None, datasheet: str | None = None, description: str | None = None, **kwargs)ο
Initialize Component with support for arbitrary additional fields.
- Parameters:
symbol β KiCad symbol reference (e.g., βDevice:Rβ)
ref β Component reference (e.g., βR1β)
value β Component value (e.g., β10kβ)
footprint β KiCad footprint reference
datasheet β URL to component datasheet
description β Component description
**kwargs β Additional fields (e.g., mfg_part_num, tolerance, etc.)
- validate_reference(ref: str) bool[source]ο
Check if reference is available in this circuitβs scope
- add_subcircuit(subcirc: Circuit)[source]ο
Add a subcircuit and establish parent-child relationship
- property componentsο
Get components dictionary for compatibility.
- property subcircuitsο
Get subcircuits list.
- generate_full_netlist() str[source]ο
- Print a hierarchical netlist showing:
Each circuit + subcircuit (name, components, and optional description)
A single combined net listing from all circuits
- add_annotation(annotation)[source]ο
Add a text annotation (TextProperty, TextBox, etc.) to this circuit.
- add_image(image_path: str, position: tuple, scale: float = 1.0)[source]ο
Add an embedded image to the schematic.
Images are embedded as base64-encoded data in the KiCad schematic file. The image file is read when the schematic is generated, so it only needs to exist at generation time.
- Parameters:
image_path β Path to image file (PNG, JPG, etc.)
position β Tuple of (x, y) position in mm
scale β Scale factor (1.0 = original size, 2.0 = 2x larger, etc.)
- Returns:
The created Image annotation object
- Return type:
Image
Example
>>> circuit.add_image("logo.png", position=(100, 50), scale=2.0)
- to_dict() Dict[str, Any][source]ο
Return a hierarchical dictionary representation of this circuit, including subcircuits, components (as a dictionary keyed by reference), and net connections.
- generate_json_netlist(filename: str) None[source]ο
Generate a JSON representation of this circuit and its hierarchy, then write it out to βfilenameβ.
- to_flattened_list(parent_name: str = None, flattened: List[Dict[str, Any]] = None) List[Dict[str, Any]][source]ο
Build or update a shared flattened list of circuit data dicts.
- generate_flattened_json_netlist(filename: str) None[source]ο
Produce a flattened JSON representation for this circuit + subcircuits.
- generate_kicad_netlist(filename: str) None[source]ο
Generate a KiCad netlist (.net) file for this circuit and its hierarchy.
- generate_kicad_project(project_name: str, generate_pcb: bool = True, force_regenerate: bool = False, placement_algorithm: str = 'hierarchical', draw_bounding_boxes: bool = False, generate_ratsnest: bool = True, update_source_refs: bool | None = None, preserve_user_components: bool = False) Dict[str, Any][source]ο
Generate a complete KiCad project (schematic + PCB) from this circuit.
This method provides a simplified API that handles all the boilerplate setup required for KiCad project generation, creating the project directory and generating KiCad files with an automatic JSON netlist in the project directory.
- Parameters:
project_name β Name of the KiCad project and directory to create
generate_pcb β Whether to generate PCB in addition to schematic (default: True)
force_regenerate β Force regeneration of existing files, losing manual edits (default: False)
placement_algorithm β Component placement algorithm to use (default: βhierarchicalβ)
draw_bounding_boxes β Whether to draw visual bounding boxes around components (default: False)
generate_ratsnest β Whether to generate ratsnest connections in PCB (default: True)
update_source_refs β Whether to update source file with finalized refs. None (default): Auto-update unless force_regenerate=True True: Always update source file False: Never update source file
preserve_user_components β Keep components in KiCad that donβt exist in Python (default: False) False: Python is source of truth - delete components not in Python True: Preserve all components in KiCad, even if not in Python
- Returns:
- Result dictionary containing:
success (bool): Whether generation succeeded
json_path (Path): Path to the canonical JSON netlist
project_path (Path): Path to the KiCad project directory
error (str, optional): Error message if generation failed
- Return type:
Example
>>> circuit = esp32s3_simple() >>> result = circuit.generate_kicad_project("esp32s3_simple") >>> print(f"JSON netlist: {result['json_path']}") >>> print(f"KiCad project: {result['project_path']}")
- generate_bom(output_file: str | None = None, project_name: str | None = None, fields: str | None = None, labels: str | None = None, group_by: str | None = None, exclude_dnp: bool = False) Dict[str, Any][source]ο
Generate a Bill of Materials (BOM) from this circuit as a CSV file.
This method creates a KiCad project if one doesnβt already exist, then exports the schematic to a CSV BOM file using kicad-cli.
- Parameters:
output_file β Path where CSV BOM should be written. If not provided, defaults to {project_name}/{project_name}.csv
project_name β Name of the KiCad project directory. If not provided, defaults to the circuit name. Required if output_file is provided but needs a project.
fields β Comma-separated fields to export from schematic. If not specified, KiCad will export default fields (Refs, Value, Footprint, etc.)
labels β Comma-separated column headers for the BOM. Must match the number of fields if fields are specified.
group_by β Field to group references by when exporting. Common values: βValueβ (group by component value), βFootprintβ, etc.
exclude_dnp β If True, exclude βDo not populateβ components from BOM
- Returns:
- Result dictionary containing:
success (bool): True if BOM was successfully generated
file (Path): Path to the generated CSV file
component_count (int): Number of components in the BOM
project_path (Path): Path to the KiCad project directory
error (str, optional): Error message if generation failed
- Return type:
Example
>>> circuit = led_blinker() >>> result = circuit.generate_bom(project_name="led_blinker") >>> print(f"BOM exported to: {result['file']}") >>> print(f"Component count: {result['component_count']}")
- Raises:
FileNotFoundError β If kicad-cli is not available
RuntimeError β If BOM export fails
- generate_pdf_schematic(output_file: str | None = None, project_name: str | None = None, black_and_white: bool = False, theme: str | None = None, exclude_drawing_sheet: bool = False, pages: str | None = None) Dict[str, Any][source]ο
Generate a PDF schematic from this circuit.
This method creates a KiCad project if one doesnβt already exist, then exports the schematic to a PDF file using kicad-cli.
- Parameters:
output_file β Path where PDF should be written. If not provided, defaults to {project_name}/{project_name}.pdf
project_name β Name of the KiCad project directory. If not provided, defaults to the circuit name.
black_and_white β Export in black and white instead of color (default: False)
theme β Color theme to use for export (optional). Theme name depends on KiCad installation.
exclude_drawing_sheet β Exclude the drawing sheet/border from PDF (default: False)
pages β Page range to export (e.g., β1,3-5β for pages 1, 3, 4, 5). If not specified, all pages are exported.
- Returns:
- Result dictionary containing:
success (bool): True if PDF was successfully generated
file (Path): Path to the generated PDF file
project_path (Path): Path to the KiCad project directory
error (str, optional): Error message if generation failed
- Return type:
Example
>>> circuit = led_blinker() >>> result = circuit.generate_pdf_schematic(project_name="led_blinker") >>> print(f"PDF exported to: {result['file']}")
- Raises:
FileNotFoundError β If kicad-cli is not available
RuntimeError β If PDF export fails
- generate_gerbers(output_dir: str | None = None, project_name: str | None = None, include_drill: bool = True, drill_format: str = 'excellon') Dict[str, Any][source]ο
Generate Gerber files for PCB manufacturing from this circuit.
This method creates a complete KiCad project (including PCB) if one doesnβt already exist, then exports Gerber files for manufacturing using kicad-cli. Gerbers can be submitted directly to manufacturers like JLCPCB, PCBWay, etc.
- Parameters:
output_dir β Directory where Gerber files should be written. If not provided, defaults to {project_name}/gerbers
project_name β Name of the KiCad project directory. If not provided, defaults to the circuit name.
include_drill β Also export drill files along with Gerbers (default: True)
drill_format β Format for drill files: βexcellonβ (default) or βgerberβ
- Returns:
- Result dictionary containing:
success (bool): True if Gerbers were successfully generated
gerber_files (list): List of Path objects to generated .gbr files
drill_files (tuple): Tuple of (plated_holes_file, non_plated_holes_file) or None
project_path (Path): Path to the KiCad project directory
output_dir (Path): Directory where Gerbers were exported
error (str, optional): Error message if generation failed
- Return type:
Example
>>> circuit = esp32_board() >>> result = circuit.generate_gerbers(project_name="esp32_board") >>> print(f"Gerbers exported to: {result['output_dir']}") >>> print(f"Files: {len(result['gerber_files'])} Gerber files")
- Requirements:
KiCad 8.0 or later
kicad-cli must be available in PATH
Circuit must be complete with all components and connections
Notes
First run generates full KiCad project including PCB (slower)
Subsequent runs reuse existing project (faster)
Default layers: F.Cu, B.Cu, F.Mask, B.Mask, F.SilkS, B.SilkS, F.Paste, B.Paste, Edge.Cuts
Gerbers use standard Protel file extension format (.gbr, .gbl, etc.)
Compatible with JLCPCB, PCBWay, OSH Park, and most PCB manufacturers
- simulate()[source]ο
Create a simulator instance for this circuit.
This method provides access to circuit simulation capabilities using PySpice as the backend. The returned simulator object can be used to run various analyses such as DC operating point, transient, and AC.
- Returns:
Simulator object for running analyses
- Return type:
CircuitSimulator
Example
>>> circuit = voltage_divider() >>> sim = circuit.simulate() >>> result = sim.operating_point()
- Raises:
ImportError β If simulation dependencies are not installed
CircuitSynthError β If circuit cannot be converted for simulation
Componentο
- class circuit_synth.core.component.Component(symbol: str, ref: str | None = None, value: str | None = None, footprint: str | None = None, datasheet: str | None = None, description: str | None = None, **kwargs)[source]ο
Bases:
SimplifiedPinAccessRepresents an electronic component that references a KiCad symbol.
If multiple pins share the same name (e.g. βGNDβ), __getitem__ returns a PinGroup, so something like:
comp[βGNDβ] += net
will connect all GND pins to that net.
Additional fields can be passed as keyword arguments and will be stored in _extra_fields for later access (e.g., mfg_part_num, tolerance, etc.).
- ALLOWED_REASSIGN = {'value'}ο
- __init__(symbol: str, ref: str | None = None, value: str | None = None, footprint: str | None = None, datasheet: str | None = None, description: str | None = None, **kwargs)[source]ο
Initialize Component with support for arbitrary additional fields.
- Parameters:
symbol β KiCad symbol reference (e.g., βDevice:Rβ)
ref β Component reference (e.g., βR1β)
value β Component value (e.g., β10kβ)
footprint β KiCad footprint reference
datasheet β URL to component datasheet
description β Component description
**kwargs β Additional fields (e.g., mfg_part_num, tolerance, etc.)
Netο
- class circuit_synth.core.net.Net(name: str | None = None, is_power: bool | None = None, power_symbol: str | None = None, trace_current: float | None = None, impedance: float | None = None, **properties: Any)[source]ο
Bases:
objectA Net represents an electrical node (set of pins).
Supports: - Automatic power net detection (GND, VCC, etc.) - Explicit power net declaration - Physical constraints (trace current, impedance) - Custom properties - Differential pairs (via KiCad naming conventions)
Examples
# Auto-detected power net (recommended) >>> gnd = Net(name=βGNDβ) # Automatically becomes power net
# Explicit power net >>> vcc = Net(name=βVCCβ, is_power=True, power_symbol=βpower:VCCβ)
# Prevent auto-detection >>> not_power = Net(name=βGND_SENSEβ, is_power=False)
# Differential pair (KiCad detects automatically by name) >>> usb_dp = Net(name=βUSB_DPβ, impedance=90) # KiCad pairs USB_DP/USB_DN >>> usb_dn = Net(name=βUSB_DNβ, impedance=90)
# High current trace >>> power_5v = Net(name=β+5Vβ, trace_current=2000) # 2A, auto-detected as power
# Custom properties >>> rf = Net(name=βRF_OUTβ, impedance=50, substrate_height=1.6)
Note
Differential pairs use KiCad naming conventions (_P/_N, +/-, etc.). KiCad automatically detects and routes them as differential pairs.
- __init__(name: str | None = None, is_power: bool | None = None, power_symbol: str | None = None, trace_current: float | None = None, impedance: float | None = None, **properties: Any)[source]ο
Create an electrical net.
- Parameters:
name β Net name (e.g., βGNDβ, βUSB_DPβ). Auto-generated if None. For differential pairs, use KiCad naming conventions: - NAME_P / NAME_N (e.g., USB_DP / USB_DN) - NAME+ / NAME- (e.g., ETH_TX+ / ETH_TX-)
is_power β Power net flag. None (default) = auto-detect from name, True = explicitly mark as power net, False = explicitly NOT a power net.
power_symbol β KiCad power symbol (e.g., βpower:GNDβ). Auto-filled if is_power is auto-detected.
trace_current β Maximum current in milliamps (mA).
impedance β Target impedance in ohms for controlled impedance routing. For differential pairs, this is the differential impedance.
**properties β Custom properties for specialized applications.
Note
Differential pairs are detected automatically by KiCad based on net naming. Use matching prefixes with _P/_N, +/-, or similar suffixes.
- property pinsο
Pinο
- class circuit_synth.core.pin.PinType(*values)[source]ο
Bases:
EnumEnumeration of valid pin types.
- INPUT = 'input'ο
- OUTPUT = 'output'ο
- BIDIRECTIONAL = 'bidirectional'ο
- POWER_IN = 'power_in'ο
- POWER_OUT = 'power_out'ο
- PASSIVE = 'passive'ο
- TRI_STATE = 'tri_state'ο
- NO_CONNECT = 'no_connect'ο
- UNSPECIFIED = 'unspecified'ο
- OPEN_COLLECTOR = 'open_collector'ο
- OPEN_EMITTER = 'open_emitter'ο
- classmethod from_string(value: str) PinType[source]ο
Create a PinType from a string value.
- Parameters:
value β String representation of the pin type
- Returns:
The corresponding PinType enum value
- Return type:
- Raises:
ValueError β If the string doesnβt match a valid pin type
- can_connect_to(other: PinType) bool[source]ο
Check if this pin type can connect to another pin type.
- Parameters:
other β The PinType to check compatibility with
- Returns:
True if the pins can be connected, False otherwise
- Return type:
Note
All pin types can connect to each other except NO_CONNECT pins. Design Rule Checks (DRC) should be used to flag potentially incorrect connections.
- class circuit_synth.core.pin.Pin(name: str, num: str, func: str | PinType, unit: int = 1, **kwargs)[source]ο
Bases:
objectMinimal Pin class for net connectivity.
No dedicated geometry fields in the constructor (x, y, length, orientation).
We do accept **kwargs so geometry can be passed (and ignored by core), but stored for schematic export.
- connect_to_net(net: Net)[source]ο
If already on another net, remove from old net. Then join the new net.
- Parameters:
net β The Net to connect this pin to
- Raises:
ValueError β If connecting would create an invalid pin type combination
- __iadd__(other)[source]ο
Support pin += net, or pin += pin.
- Parameters:
other β Either a Net or another Pin to connect to
- Returns:
Self, for chaining
- Return type:
- Raises:
TypeError β If other is not a Net or Pin
ValueError β If pin types are incompatible
KiCad Integrationο
KiCad integration package.
- class circuit_synth.kicad.BOMExporter[source]ο
Bases:
objectExport Bill of Materials from KiCad schematic files using kicad-cli.
- static export_csv(schematic_file: Path, output_file: Path, fields: str | None = None, labels: str | None = None, group_by: str | None = None, exclude_dnp: bool = False) Dict[str, Any][source]ο
Export BOM from a KiCad schematic to CSV format using kicad-cli.
- Parameters:
schematic_file β Path to .kicad_sch schematic file
output_file β Path where CSV BOM should be written
fields β Comma-separated fields to export. Default: all fields from schematic
labels β Comma-separated column headers. Must match number of fields.
group_by β Field to group references by (e.g., βValueβ to group by component value)
exclude_dnp β Whether to exclude βDo not populateβ components
- Returns:
- Result dictionary with keys:
success: bool - True if BOM was successfully exported
file: Path - Path to generated BOM file
component_count: int - Number of components in BOM
error: str (optional) - Error message if export failed
- Return type:
- Raises:
FileNotFoundError β If kicad-cli is not available or schematic file not found
subprocess.CalledProcessError β If kicad-cli returns non-zero exit code
- class circuit_synth.kicad.BOMPropertyManager[source]ο
Bases:
objectManage BOM properties for KiCad schematics.
High-level interface for auditing, updating, and transforming component properties across schematics. Useful for BOM cleanup and standardization.
Example
>>> manager = BOMPropertyManager() >>> >>> # Audit for missing properties >>> issues = manager.audit_directory( ... Path("~/my_designs"), ... required_properties=["PartNumber", "Manufacturer"] ... ) >>> >>> # Generate report >>> manager.generate_report(issues, Path("audit.csv")) >>> >>> # Bulk update properties >>> manager.update_properties( ... Path("~/my_designs"), ... match={"value": "10k", "lib_id": "Device:R"}, ... set_properties={"PartNumber": "RC0805FR-0710KL"} ... )
- audit_directory(directory: Path, required_properties: List[str], recursive: bool = True, exclude_dnp: bool = False) List[ComponentIssue][source]ο
Audit directory for components missing required properties.
- Parameters:
directory β Path to directory containing .kicad_sch files
required_properties β List of property names that must be present
recursive β Scan subdirectories (default: True)
exclude_dnp β Skip Do-Not-Populate components (default: False)
- Returns:
List of ComponentIssue objects describing missing properties
Example
>>> manager = BOMPropertyManager() >>> issues = manager.audit_directory( ... Path("~/designs"), ... required_properties=["PartNumber", "Manufacturer"], ... exclude_dnp=True ... ) >>> print(f"Found {len(issues)} components with missing properties")
- audit_schematic(schematic_path: Path, required_properties: List[str], exclude_dnp: bool = False) List[ComponentIssue][source]ο
Audit single schematic for missing properties.
- Parameters:
schematic_path β Path to .kicad_sch file
required_properties β List of property names that must be present
exclude_dnp β Skip Do-Not-Populate components (default: False)
- Returns:
List of ComponentIssue objects
Example
>>> manager = BOMPropertyManager() >>> issues = manager.audit_schematic( ... Path("circuit.kicad_sch"), ... required_properties=["PartNumber"] ... )
- generate_report(issues: List[ComponentIssue], output_path: Path) None[source]ο
Generate CSV report from audit results.
- Parameters:
issues β List of ComponentIssue objects from audit
output_path β Path where CSV report should be saved
Example
>>> manager = BOMPropertyManager() >>> issues = manager.audit_directory(Path("~/designs"), ["PartNumber"]) >>> manager.generate_report(issues, Path("audit_report.csv"))
- static parse_match_criteria(criteria_str: str) Dict[str, str][source]ο
Parse criteria string into dict for matching.
- Parameters:
criteria_str β Comma-separated criteria (e.g., βvalue=10k,lib_id=Device:Rβ)
- Returns:
Dict of field=pattern criteria
Example
>>> criteria = BOMPropertyManager.parse_match_criteria("value=10k,footprint=*0805*") >>> # Returns: {"value": "10k", "footprint": "*0805*"}
- static parse_properties(props_str: str) Dict[str, str][source]ο
Parse property string into dict for setting.
- Parameters:
props_str β Comma-separated properties (e.g., βPartNumber=XXX,Manufacturer=YYYβ)
- Returns:
Dict of property=value pairs
Example
>>> props = BOMPropertyManager.parse_properties("PartNumber=XXX,Manufacturer=YYY") >>> # Returns: {"PartNumber": "XXX", "Manufacturer": "YYY"}
- transform_properties(directory: Path, transformations: List[Tuple[str, str]], only_if_empty: bool = False, dry_run: bool = False, recursive: bool = True, exclude_dnp: bool = False) int[source]ο
Copy or rename properties across components.
- Parameters:
directory β Path to directory containing .kicad_sch files
transformations β List of (source_property, dest_property) tuples
only_if_empty β Only copy to empty destination properties (default: False)
dry_run β Preview only, donβt modify files (default: False)
recursive β Scan subdirectories (default: True)
exclude_dnp β Skip Do-Not-Populate components (default: False)
- Returns:
Number of components transformed
Example
>>> manager = BOMPropertyManager() >>> >>> # Copy MPN to PartNumber (only where PartNumber is empty) >>> count = manager.transform_properties( ... Path("~/designs"), ... transformations=[("MPN", "PartNumber")], ... only_if_empty=True ... ) >>> >>> # Rename property (overwrite existing) >>> count = manager.transform_properties( ... Path("~/designs"), ... transformations=[("OldField", "NewField")] ... )
- update_properties(directory: Path, match: Dict[str, str], set_properties: Dict[str, str], dry_run: bool = False, recursive: bool = True, exclude_dnp: bool = False) int[source]ο
Bulk update properties on matching components.
- Parameters:
directory β Path to directory containing .kicad_sch files
match β Dict of field=pattern criteria (all must match)
set_properties β Dict of property=value updates to apply
dry_run β Preview only, donβt modify files (default: False)
recursive β Scan subdirectories (default: True)
exclude_dnp β Skip Do-Not-Populate components (default: False)
- Returns:
Number of components updated
Example
>>> manager = BOMPropertyManager() >>> >>> # Preview update >>> count = manager.update_properties( ... Path("~/designs"), ... match={"value": "10k", "lib_id": "Device:R"}, ... set_properties={"PartNumber": "RC0805FR-0710KL"}, ... dry_run=True ... ) >>> print(f"Would update {count} components") >>> >>> # Apply update >>> count = manager.update_properties( ... Path("~/designs"), ... match={"value": "10k", "lib_id": "Device:R"}, ... set_properties={ ... "PartNumber": "RC0805FR-0710KL", ... "Manufacturer": "Yageo", ... "Tolerance": "1%" ... } ... )
- class circuit_synth.kicad.SymbolLibCache[source]ο
Bases:
objectPython fallback implementation of SymbolLibCache. Restored from the original working implementation.
- classmethod find_symbol_library(symbol_name: str) str | None[source]ο
Find which library contains the given symbol name.
- classmethod get_all_libraries() Dict[str, str][source]ο
Get a dictionary of all available libraries.
Unified Integrationο
PCB Generationο
KiCad PCB API - PCB generation features have been removed.
PCB generation functionality is no longer included in the open source version. Contact Circuit Synth for licensing information if you need PCB features.
- exception circuit_synth.pcb.PCBNotAvailableError[source]ο
Bases:
ImportErrorRaised when PCB features are accessed but not available.
- class circuit_synth.pcb.KiCadCLI(kicad_cli_path: str | None = None)[source]ο
Bases:
objectGeneric interface to run KiCad CLI commands.
Provides both low-level command execution and high-level convenience methods for common operations like DRC, export, etc.
- __init__(kicad_cli_path: str | None = None)[source]ο
Initialize KiCad CLI interface.
- Parameters:
kicad_cli_path β Optional explicit path to kicad-cli executable. If not provided, will attempt auto-detection.
- export_drill(pcb_file: str | Path, output_dir: str | Path, format: str = 'excellon', units: str = 'mm', mirror_y: bool = False, minimal_header: bool = False) Tuple[Path | None, Path | None][source]ο
Export drill files from a PCB.
- Parameters:
pcb_file β Path to the PCB file
output_dir β Directory to save drill files
format β Drill file format (excellon, gerber)
units β Units for coordinates (mm, in)
mirror_y β Mirror Y coordinates
minimal_header β Use minimal header
- Returns:
Tuple of (plated_holes_file, non_plated_holes_file)
- export_gerbers(pcb_file: str | Path, output_dir: str | Path, layers: List[str] | None = None, protel_extensions: bool = False) List[Path][source]ο
Export Gerber files from a PCB.
- Parameters:
pcb_file β Path to the PCB file
output_dir β Directory to save Gerber files
layers β Optional list of layer names to export. If None, exports all copper and technical layers
protel_extensions β Use Protel filename extensions
- Returns:
List of generated Gerber file paths
- export_pos(pcb_file: str | Path, output_file: str | Path, side: str = 'both', format: str = 'csv', units: str = 'mm', use_drill_origin: bool = False, smd_only: bool = False) Path[source]ο
Export pick and place (position) file from a PCB.
- Parameters:
pcb_file β Path to the PCB file
output_file β Output file path
side β Which side to export (front, back, both)
format β Output format (csv, ascii, gerber)
units β Units for coordinates (mm, in)
use_drill_origin β Use drill/place origin instead of page origin
smd_only β Only include SMD components
- Returns:
Path to generated position file
- export_svg(pcb_file: str | Path, output_file: str | Path, layers: List[str] | None = None, theme: str | None = None, black_and_white: bool = False, page_size: str | None = None) Path[source]ο
Export PCB as SVG image.
- Parameters:
pcb_file β Path to the PCB file
output_file β Output SVG file path
layers β List of layers to include
theme β Color theme to use
black_and_white β Export in black and white
page_size β Page size (A4, A3, etc.)
- Returns:
Path to generated SVG file
- run_command(args: List[str], cwd: str | Path | None = None, capture_output: bool = True, check: bool = True) CompletedProcess[source]ο
Run a kicad-cli command with the given arguments.
This is the low-level interface that all high-level methods use.
- Parameters:
args β Command arguments (without βkicad-cliβ prefix)
cwd β Working directory for the command
capture_output β Whether to capture stdout/stderr
check β Whether to raise exception on non-zero return code
- Returns:
CompletedProcess instance with command results
- Raises:
KiCadCLICommandError β If command fails and check=True
- run_drc(pcb_file: str | Path, output_file: str | Path | None = None, units: str = 'mm', severity: str = 'error', format: str = 'json', custom_rules_file: str | Path | None = None) DRCResult[source]ο
Run Design Rule Check on a PCB file.
- Parameters:
pcb_file β Path to the PCB file
output_file β Optional output file for the report. If not provided, will use pcb_file with .drc extension
units β Units for the report (mm, in, mils)
severity β Minimum severity to report (error, warning, info)
format β Output format (json, report)
custom_rules_file β Optional path to custom DRC rules file
- Returns:
DRCResult object with violations, warnings, and unconnected items
Note
Custom DRC rules via command line are not directly supported in current KiCad versions. Rules are typically embedded in the PCB file or project. The custom_rules_file parameter is included for future compatibility.
- circuit_synth.pcb.get_kicad_cli(kicad_cli_path: str | None = None) KiCadCLI[source]ο
Get a KiCad CLI instance with auto-detection.
- Parameters:
kicad_cli_path β Optional explicit path to kicad-cli
- Returns:
KiCadCLI instance
- class circuit_synth.pcb.DRCResult(success: bool, violations: List[Dict[str, Any]], warnings: List[Dict[str, Any]], unconnected_items: List[Dict[str, Any]], output_file: Path | None = None)[source]ο
Bases:
objectResult of a DRC (Design Rule Check) operation.
- exception circuit_synth.pcb.KiCadCLIError[source]ο
Bases:
ExceptionBase exception for KiCad CLI errors.
Placement Algorithmsο
Schematic Generationο
Component Placementο
Component placement package for handling geometry, placement and wire routing.
Provides geometry utilities, automated placement algorithms, and wire routing functionality for KiCad schematics.
- class circuit_synth.component_placement.PinLocation(x: float, y: float, side: str)[source]ο
Bases:
objectRepresents a pinβs location relative to component center.
- class circuit_synth.component_placement.ComponentDimensions(width: float, height: float, pin_grid: float = 2.54)[source]ο
Bases:
objectRepresents a componentβs dimensions.
- class circuit_synth.component_placement.ComponentGeometryHandler(component_type: str)[source]ο
Bases:
objectBase class for handling component geometry and pin locations.
- class circuit_synth.component_placement.ResistorGeometryHandler(component_type: str)[source]ο
Bases:
ComponentGeometryHandlerGeometry handler for resistor components.
- class circuit_synth.component_placement.PowerSymbolGeometryHandler(component_type: str)[source]ο
Bases:
ComponentGeometryHandlerGeometry handler for power symbols.
- circuit_synth.component_placement.create_geometry_handler(component_type: str, library: str) ComponentGeometryHandler[source]ο
Factory function to create appropriate geometry handler for component.
- class circuit_synth.component_placement.PlacementNode(component: Component, x: float = 0, y: float = 0, rotation: float = 0, placed: bool = False, connected_components: Set[Component] = None, geometry_handler: ComponentGeometryHandler | None = None)[source]ο
Bases:
objectRepresents a componentβs placement information.
- __init__(component: Component, x: float = 0, y: float = 0, rotation: float = 0, placed: bool = False, connected_components: Set[Component] = None, geometry_handler: ComponentGeometryHandler | None = None) Noneο
- geometry_handler: ComponentGeometryHandler | None = Noneο
- class circuit_synth.component_placement.ComponentPlacer(base_x: float = 77.47, base_y: float = 44.45)[source]ο
Bases:
objectHandles intelligent placement of components in a schematic.
- class circuit_synth.component_placement.WireSegment(start: Tuple[float, float], end: Tuple[float, float], net_name: str, connected_pins: List[Tuple[str, str]])[source]ο
Bases:
objectRepresents a wire segment in the schematic.
- class circuit_synth.component_placement.WireRouter[source]ο
Bases:
objectHandles routing of wires between components.
- route_net(net: Net, placement_nodes: Dict[str, PlacementNode]) List[WireSegment][source]ο
Route wires for a single net.
- class circuit_synth.component_placement.ForceVector(x: float, y: float)[source]ο
Bases:
objectRepresents a 2D force vector.
- scale(factor: float) ForceVector[source]ο
- class circuit_synth.component_placement.ForceDirectedLayout(attractive_force: float = 0.3, repulsive_force: float = 100.0, damping: float = 0.85, min_distance: float = 15.0, max_iterations: int = 100, convergence_threshold: float = 0.1)[source]ο
Bases:
objectForce-directed layout algorithm for component placement.
- __init__(attractive_force: float = 0.3, repulsive_force: float = 100.0, damping: float = 0.85, min_distance: float = 15.0, max_iterations: int = 100, convergence_threshold: float = 0.1)[source]ο
Initialize the force-directed layout algorithm.
- Parameters:
attractive_force β Strength of attractive forces between connected components
repulsive_force β Strength of repulsive forces between all components
damping β Damping factor to prevent oscillation (0-1)
min_distance β Minimum distance between components
max_iterations β Maximum number of iterations
convergence_threshold β Stop when max force is below this threshold
- layout(circuit: Circuit, initial_positions: Dict[str, Tuple[float, float, float]] | None = None) Dict[str, Tuple[float, float, float]][source]ο
Apply force-directed layout to position components.
- Parameters:
circuit β The circuit to layout
initial_positions β Optional dict of initial component positions (x, y, rotation)
- Returns:
Dict mapping component references to (x, y, rotation) tuples
Interfacesο
Exceptionsο
Exceptions for Circuit Synth.
- exception circuit_synth.core.exception.CircuitSynthError[source]ο
Bases:
ExceptionBase exception for all Circuit Synth errors.
- exception circuit_synth.core.exception.LibraryNotFound[source]ο
Bases:
CircuitSynthErrorRaised when a library file cannot be found.
- exception circuit_synth.core.exception.SymbolNotFoundError[source]ο
Bases:
CircuitSynthErrorRaised when a symbol is not found in a library.
- exception circuit_synth.core.exception.ParseError[source]ο
Bases:
CircuitSynthErrorRaised when there is an error parsing a file.
- exception circuit_synth.core.exception.ValidationError[source]ο
Bases:
CircuitSynthErrorRaised when a property validation fails.
- exception circuit_synth.core.exception.ComponentError[source]ο
Bases:
CircuitSynthErrorRaised when there is an error with a component or its pins.
- exception circuit_synth.core.exception.ConnectionError[source]ο
Bases:
CircuitSynthErrorRaised when there is an error with connections.