jitx package#

JITX Python API#

The JITX Python API is a set of classes that can be used to build a design in Python. The core principle of the API is that, when run, your code constructs an object tree that is then inspected. This means that creating an object and attaching them to other objects is what drives the construction of the design, and not function calls. The root of the tree is an instance of a Design subclass. The JITX runtime will inspect your project looking for Design subclasses which are then instantiated on request.

The inspection mechanism will traverse lists, tuples, and dictionaries, as well, thus objects can be added to arrays and dictionaries as needed when building the object tree.

The API is designed to be as simple as possible, and to be as close to Python as possible. The API is designed to be used with a Python language server, such as PyLance/pyright, to provide autocompletion and type checking.

Note

There are a few mechanisms designed to make API usage cleaner by allowing instantiated objects as class attributes, but there are caveats to be aware of when doing more involved logic, and when in doubt, all logic can also be placed in the initializer of the class. Runtime errors involving an unexpected “Instantiable” object is indicative of this type of error.

current = Current#

Singleton, the “current” context registry.

class Anchor(*values)[source]#

Bases: Enum

Enumeration representing anchor positions for shapes and schematic elements.

Anchors define reference points for positioning elements relative to their bounding boxes. The naming follows compass directions: N (North/Top), S (South/Bottom), E (East/Right), W (West/Left), C (Center).

>>> # Create a rectangle anchored at its top-left corner
>>> rect = rectangle(10, 5, anchor=Anchor.NW)
>>> # Create a rectangle centered at the origin
>>> rect = rectangle(10, 5, anchor=Anchor.C)
NW = 'NW'#
N = 'N'#
NE = 'NE'#
W = 'W'#
C = 'C'#
E = 'E'#
SW = 'SW'#
S = 'S'#
SE = 'SE'#
horizontal()[source]#

Extract the horizontal component of an Anchor.

Returns:

The horizontal component (W, C, or E).

Return type:

Anchor

>>> Anchor.NW.horizontal()
<Anchor.W: 'W'>
vertical()[source]#

Extract the vertical component of an Anchor.

Returns:

The vertical component (N, C, or S).

Return type:

Anchor

>>> Anchor.NW.vertical()
<Anchor.N: 'N'>
flip()[source]#

Flip the anchor about both X and Y axes.

Returns:

The diagonally opposite anchor position.

Return type:

Anchor

>>> Anchor.NW.flip()
<Anchor.SE: 'SE'>
to_point(bounds)[source]#

Convert an anchor to a point within the given bounding box.

Parameters:

bounds (tuple[float, float, float, float]) – Bounding box as (min_x, min_y, max_x, max_y).

Return type:

tuple[float, float]

Returns:

The (x, y) coordinates of the anchor position within the bounds.

>>> bounds = (0, 0, 10, 5)
>>> Anchor.NW.to_point(bounds)
(0, 5)
>>> Anchor.C.to_point(bounds)
(0.0, 0.0)
class Board[source]#

Bases: Structural

Board shape and geometric constraints. Can be subclassed to create a template with appropriate shape(s) that may include added mounting holes and other geometric elements.

>>> class MyBoard(Board):
...     # 50mm x 30mm board outline
...     shape = rectangle(50.0, 30.0)
...     signal_area = rectangle(46.0, 26.0)
shape: Shape#

The board outline shape.

signal_area: Shape | None = None#

Shape constraining component and routing placement area. If not provided, the board shape is used.

class Circuit[source]#

Bases: Open, Positionable

The Circuit is JITX’s primary modularization object. The main function of a Circuit is instantiate ports that can be seen as an external interface, instantiate subcircuits or components, as well as net ports of these elements together.

Ports, components, and other circuits can be created directly in the class for convenience, and will be instantiated separately as instance attributes for each created circuit instance. It’s perfectly valid to add elements to self in the __init__ method, and in fact, any type of coding logic, such as a parameterized circuit, would need to go into an __init__ method, as it’s not possible to execute that properly in the class context.

All elements of the circuit needs to be reachable from the circuit in some way, it is not sufficient to merely create a component, it must be assigned to member field in the circuit in some way. It can be added to a container (such as a list, or a dictionary) that is assigned to the circuit object, not every component needs have its own attribute. The same is true for nets.

A general purpose += operator is provided to add elements to the circuit that do not need an assigned name. They’ll all be gathered into a private list that is not accessible from the outside. Note that if elements that have their name displayed somewhere (such as nets in the schematic) are added to this list, they will still be displayed, but their name may look confusing. For most objects it’s advisable to either assign them to a field or add them to a list or mapping which are rendered in a sensible way.

>>> class MyCircuit(Circuit):
...     # assume FancyComponent has an `n` and a `p` port. JITX's instantiation
...     # mechanism will create a new instance of FancyComponent for each
...     # instance of MyCircuit
...     comp = FancyComponent()
...     diffp = DiffPair()
...
...     def __init__(self):
...         self.nets = [
...             diffp.n + comp.n,
...             diffp.p + comp.p,
...         ]
in_bom: bool | None = None#

Whether the components within this circuit are in the bill of materials. If unset, defers to the parent Circuit’s in_bom attribute. If there is no parent circuit, defaults to True.

soldered: bool | None = None#

Whether the components within this circuit are soldered on the board. If unset, defers to the parent Circuit’s soldered attribute. If there is no parent circuit, defaults to True.

schematic_x_out: bool | None = None#

Whether the components within this circuit are marked with a red X in the schematic. If unset, defers to the parent Circuit’s schematic_x_out attribute. If there is no parent circuit, defaults to False.

transform: Placement | None = Placement(Transform((0, 0), 0, (1, 1)), 0)#

The placement of this circuit relative to the parent circuit.

require[T: Port](Bundle, /, *, count=None, restrictions=None)[source]#

Require a port bundle to be provided a subcircuit, or, alternatively, by this circuit as a self-provide.

Overloads:
Parameters:
Return type:

T | Sequence

Note that the returned port instance is a placeholder port for the provided port that can be netted with other ports, but should not be added to this circuit as a member field, as it’s not a port that this circuit itself exposes.

Parameters:
  • Bundle (Union[T, type[T]]) – The port type or instance to require.

  • restrictions (Callable[[T], Mapping[Port, Callable[[Port], Any]]] | None) – Optional function to specify restrictions on the required ports.

  • count (int | None) – Optional number of instances to require. If specified, a sequence of required ports are returned.

Returns:

The required port bundle instance.

Return type:

T | Sequence

>>> class MyCircuit(Circuit):
...     subcircuit = MySubCircuit()
...     my_signal_port = DiffPair()
...     def __init__(self):
...         diffpair = self.subcircuit.require(DiffPair)
...         self.signal_net = self.my_signal_port + diffpair
place[T: Component | Circuit](instance, placement, /, *, on=Side.Top, relative_to=None)[source]#

Place a descendant component or circuit on the board relative to this circuit’s frame of reference. It is different from at() in that it does not modify the instance’s actual placement in its parents frame of reference, but instead adds a placement request for a child circuit or component. If the instance is introspected before placement occurs, the placement will not be reflected in the instance’s Trace transform.

Overloads:
Parameters:
Return type:

T

Note that circuits have a default placement of (0, 0) on top, which is to allow for elements inside the circuit to be placed relative to the design origin. If the circuit should have a free-floating frame of reference that components are placed relative to, the circuit should either be given a placement using at() or explicitly set to be free floating using circuit.at(floating=True). Note that if the circuit is free floating and components inside the circuit are not placed, it is ambiguous which frame of reference is modified when the components are placed.

>>> class MyCircuit(Circuit):
...     def __init__(self):
...         self.component = MyComponent()
...         self.place(self.component, Transform.rotate(90))
annotate(text, *, normalize=True)[source]#

Add a schematic annotation.

Parameters:
  • text (str) – Markdown formatted text to add as an annotation.

  • normalize – Whether to normalize the indentation, this is on by default, and is useful to allow natural indentation of multiline strings.

Return type:

None

>>> class MyCircuit(Circuit):
...     def __init__(self):
...         self.annotate("Hello, world!")
at(x=None, y=None, /, *, on=Side.Top, rotate=0, floating=False)[source]#

Place the circuit on the board relative to its parent’s frame of reference.

Overloads:
Parameters:
  • x (Placement | Transform | Point | float | None) – x-value, transform, or placement to adopt.

  • y (float | None) – y-value if x is an x-value. This argument is only valid in that context.

  • on (Side) – If set to bottom, this object will be placed on the “opposite” side from its frame of reference. This means if the frame of reference is on the bottom of the board, setting this to “bottom” will actually put the object back on top.

  • rotate (float) – Rotation in degrees to apply to the object. Only applicable if not supplying a transform or placement.

  • floating (bool) – If set to True, no other arguments are valid, and will allow this circuit to be free floating, subject to interactive placement.

Returns:

The circuit itself, for method chaining.

Overrides:

Positionable.at

Return type:

Self

class Route(source, destination, layer, sketch=None, *, config=None)[source]#

Bases: Structural, Ref

A code based route between two ports/pads

Parameters:
class Sketch(start, turns_or_end, end=None, /)[source]#

Bases: object

Specify the sketch of a code based Route.

Overloads:
Parameters:

A sketch is a hint for the routing engine: a start and end terminal with an ordered list of turns in between.

class Terminal(point)[source]#

Bases: object

One end of a Route.Sketch.

Parameters:

point (Point)

point: Point#

The point at which this end of the sketch attaches.

start: Terminal#

The terminal where the sketch begins.

turns: Sequence[Point]#

Intermediate waypoints the route should follow.

end: Terminal#

The terminal where the sketch ends.

class Target(kind, radius=None, width=None, height=None, at=<factory>)[source]#

Bases: object

The shape a code based Route ends in at one of its endpoints, for Route.Config.source_target and Route.Config.destination_target.

Use FIT, AUTOMATIC, circle() or rectangle() rather than constructing one directly. Circles and rectangles are placed relative to the endpoint’s center and orientation (for a pad, the pad’s own frame), so at moves or rotates the shape within the pad. The shape is not checked against the pad; keep it inside the pad.

>>> Route.Config(source_target=Route.Target.rectangle(0.4, 0.2, at=Transform((0.1, 0))))
Parameters:
class Kind(*values)[source]#

Bases: StrEnum

The kind of a Route.Target.

Fit = 'fit'#

Fit the route end to the endpoint’s shape.

Automatic = 'automatic'#

The default route end, sized from the trace width.

Circle = 'circle'#

A circle, see Route.Target.circle().

Rectangle = 'rectangle'#

A rectangle, see Route.Target.rectangle().

FIT: ClassVar[Target] = Route.Target(kind=<Kind.Fit: 'fit'>, radius=None, width=None, height=None, at=Transform((0, 0), 0, (1, 1)))#

Fit the route end to the endpoint’s shape.

AUTOMATIC: ClassVar[Target] = Route.Target(kind=<Kind.Automatic: 'automatic'>, radius=None, width=None, height=None, at=Transform((0, 0), 0, (1, 1)))#

The default route end, sized from the trace width.

kind: Kind#

The kind of route end.

radius: float | None = None#

Radius of a circle() target.

width: float | None = None#

Width of a rectangle() target.

height: float | None = None#

Height of a rectangle() target.

at: Transform#

Placement of a circle or rectangle relative to the endpoint.

classmethod circle(*, radius=None, diameter=None, at=Transform((0, 0), 0, (1, 1)))[source]#

A circular route end, given by its radius or diameter.

Overloads:
Parameters:
Return type:

Target

>>> Route.Target.circle(radius=0.2)
>>> Route.Target.circle(diameter=0.4, at=Transform((0.1, 0)))
classmethod rectangle(width, height, *, at=Transform((0, 0), 0, (1, 1)))[source]#

A rectangular route end, centered on the endpoint unless moved with at.

Return type:

Target

Parameters:
class Config(*, pour=None, trace_width=None, trace_space=None, pair_space=None, envelope_overhead=None, source_target=None, destination_target=None)[source]#

Bases: object

Per-route overrides of the routing constraints of a code based Route.

Fields left as None keep the value the route would otherwise get from its routing structure, net class or design rules. Lengths are in mm. Fields set here can’t be changed in the physical design view; change the code instead. The other fields stay editable there.

>>> Route(a, b, layer=0, config=Route.Config(trace_width=0.2))
Parameters:
  • pour (bool | None)

  • trace_width (float | None)

  • trace_space (float | None)

  • pair_space (float | None)

  • envelope_overhead (float | None)

  • source_target (Target | None)

  • destination_target (Target | None)

pour: bool | None = None#

Generate an automatic pour around the route, filling the free space around it.

trace_width: float | None = None#

Width of the trace.

trace_space: float | None = None#

Clearance between the trace and other copper.

pair_space: float | None = None#

Gap between the two traces of a differential pair route, measured copper edge to copper edge.

envelope_overhead: float | None = None#

Extra width, beyond the route’s copper, of the region the trace can meander within for length matching. 0 disables length matching for the route. Can’t be combined with a custom source_target or destination_target.

source_target: Target | None = None#

Shape of the route end at Route.source.

destination_target: Target | None = None#

Shape of the route end at Route.destination.

class Trace(shapes)[source]#

Bases: object

Computed output shape(s) of a route. In the most common case, this a single ArcPolyline shape, but could be a sequence of multiple shapes.

Parameters:

shapes (Sequence[Shape])

shapes: Sequence[Shape]#
traces: Sequence[Trace] | None = None#

Traces generated from this route. Traces are the actual copper pieces generated by the router, and will only be available once the design has been evaluated and captured by the runtime. For normal routes this is a single element, but for diff pairs there will be two entries in this list.

Note that it’s generally advisable to use the query api to look for relevant elements if, for example, only interested in the copper shapes of things, instead of inspecting these fields directly, unless explicitly the shapes of a particular route is needed.

derived: Sequence[Feature | Pour] | None = None#

Derived objects generated from this route. For most routes this will be unset, but for routing structure driven routes this could contain elements such as Soldermask openings or KeepOuts.

class Status(routed)[source]#

Bases: object

The runtime’s routing outcome for a route.

Parameters:

routed (bool) – True if the router produced copper for the route, False if it is blocked: no path was found. A blocked route stays in the design and may route later, for example once components are moved to make room.

routed: bool#
property blocked: bool#

True if no path was found for the route.

status: Status | None = None#

The runtime’s routing outcome, once the design has been captured or a design session has received it; None before that. A blocked route has no traces.

source: Port | Pad | Via | RouteConnectionEndpoint#

One of the end points of the route. In general, routes are not directional.

destination: Port | Pad | Via | RouteConnectionEndpoint#

The other end point of the route. In general, routes are not directional.

layer: int#

The layer to route on

sketch: Sketch | None#

An optional hint for the routing engine to follow

config: Config | None#

Optional overrides of the routing constraints for this route

class Component[source]#

Bases: Open, Positionable

Components are a structural element in JITX representing a physical component. Components are instantiated in a Circuit and contain a landpattern and a symbol, as well as Port objects that are mapped to landpattern pads and symbol pins.

Valid elements in a component are:

Note that if multiple landpatterns are specified, they will be combined into a single composite landpattern. Multiple symbols are permissible, and will end up in the schematic as independent symbols units.

If there are no pad mappings, a default mapping will be created that maps ports to pads in order. Similarly if there are no symbol mappings, a default mapping will be created that will attempt to map all ports to symbol pins in order. If a port should have no pad mapping, or multiple pads need to mapped to a single port, a pad mapping must be explicitly created.

These elements can be declared at class scope or assigned to self in __init__. JITX structural elements declared at class scope are instantiated for each instance of the component, with references between them resolved to that instance’s objects; other class attributes are ordinary class attributes.

>>> class MyComponent(Component):
...     VIN = Power()
...     aux = Port()
...
...     landpattern = MyLandpattern()
...     symbol = BoxSymbol()
...     def __init__(self):
...         self.mappings = [
...             PadMapping({
...                 self.VIN.Vp: self.landpattern.p[1],
...                 self.VIN.Vn: self.landpattern.p[2],
...                 self.aux: self.landpattern.p[3],
...             }),
...             SymbolMapping({
...                 self.VIN.Vp: self.symbol.power,
...                 self.VIN.Vn: self.symbol.ground,
...                 self.aux: self.symbol.data,
...             }),
...         ]

It is perfectly valid to have a component definition that constructs the component dynamically given parameters. For example you could have a component class that reads a CSV file to generate the component’s properties.

value: str | PlainQuantity | None = None#

Value label string for this component.

mpn: str | None = None#

Manufacturer part number for this component.

manufacturer: str | None = None#

Manufacturer for this component.

reference_designator: str | None = None#

Reference designator for this component. Note that this field should probably be left blank until after the component has been instantiated, or it will be the same (and thus trigger an error) for every component of the same type.

reference_designator_prefix: str | None = None#

Reference designator prefix for this component. This will be used to generate a unique reference designator for each component of the same type.

Note

This field is a required data point for matching components between builds. If this value changes (including changing from unset to set), it will be treated as a new component, even if nothing else changes.

in_bom: bool | None = None#

Whether this component is in the bill of materials. If unset, defers to the parent Circuit’s in_bom attribute. If a component is not in the bill of materials, then it can be considered to be non-populated.

soldered: bool | None = None#

Whether this component is soldered on the board. If unset, defers to the parent Circuit’s soldered attribute. If a component is not soldered on the board but in the bill of materials, then it can be considered to a component that is orderable such as a jumper, screw or other mechanical components but not attached via a standard soldering process.

schematic_x_out: bool | None = None#

Whether this component is marked with a red X in the schematic. If unset, defers to the parent Circuit’s schematic_x_out attribute. Enabling the red X on the component in the schematic can indicate that component should be treated differently (e.g. not in the bill of materials or not soldered depending on the state of the other flags). ::note

class SquareViaStitchGrid(pitch, inset)[source]#

Bases: ViaStitchPattern

A square grid pattern for via stitching.

Places vias in a regular square grid pattern within the target area. Used in the StitchVia constraint effect.

>>> pattern = SquareViaStitchGrid(pitch=2.0, inset=0.5)
Parameters:
class Tag[source]#

Bases: object

Tags are the fundamental building blocks for design constraints.

Tags are applied to design objects, and are then used by the rule system to determine which rules apply to which objects.

Tags form a hierarchy through class inheritance, and thus a rule applied to a tag will apply to all tags that are a subclass of that tag. The name of a tag is derived from its class name.

Tags can be combined using logical operators to create complex conditions:

  • & (AND): Both conditions must be true

  • (OR): Either condition can be true
  • ~ (NOT): Inverts the condition

>>> class PowerTag(Tag):
...     "This is a power net, or some appropriate docstring for this tag"
>>> class SignalTag(Tag):
...     "This is a signal net"
>>> class HighSpeedTag(SignalTag):
...     "This is a high speed signal"
>>> # This rule applies to ALL Signal tags (including HighSpeed)
>>> signal_rule = design_constraint(SignalTag()).trace_width(0.2)
>>> # This rule applies only to HighSpeed signals
>>> high_speed_rule = design_constraint(HighSpeedTag()).trace_width(0.1)

Tags can be assigned to objects and used in rule conditions:

>>> # Assign tags to nets
>>> PowerTag().assign(power_net)
>>> GroundTag().assign(ground_net)
>>>
>>> # Create rules using tag combinations
>>> rule1 = design_constraint(PowerTag()).trace_width(0.5)
>>> rule2 = design_constraint(PowerTag() & HighSpeedTag(), AnyObject).clearance(0.3)
>>> rule3 = design_constraint(PowerTag() | SignalTag()).stitch_via(MyVia, pattern)
>>> rule4 = design_constraint(~HighSpeedTag()).trace_width(0.2)
assign(*other)[source]#

Assign this tag to an object.

Parameters:

other – The object to assign this tag to

Returns:

The tag instance for method chaining

>>> class MyCircuit(Circuit):
...     ports = [Port(), Port()]
...     net = Net(ports)
...     def __init__(self):
...         PowerTag().assign(net)
static any(*tgs)[source]#

Construct a new expression that is the logical OR of all the passed tags or expressions.

Return type:

BoolExpr

Parameters:

tgs (Tag | BoolExpr)

static all(*tgs)[source]#

Construct a new expression that is the logical AND of all the passed tags or expressions.

Return type:

BoolExpr

Parameters:

tgs (Tag | BoolExpr)

class Tags(tags, *more)[source]#

Bases: Property

A collection of tags assigned to an object, as a property.

Tags are markers on design objects that are then used by the rule system to determine which rules apply to which objects.

Tags can be assigned to: - Nets - Copper objects (copper, routes, pours) - Structural elements that contain copper objects (pads, vias, control points, landpatterns, components, circuits)

If a tag is assigned to a structural elements that contains copper objects, then all copper objects inside inherit that tag. For example, tagging a landpattern implicitly tags all pads in that landpattern.

While classes cannot be directly tagged, all instances of a class can be tagged by tagging self (often in __init__) without a condition.

Parameters:
  • tags (Tag | Iterable[Tag]) – A single Tag or sequence of Tags to assign

  • *more (Tag) – Additional tags to assign

>>> # Assign a single tag
>>> Tags(PowerTag()).assign(power_net)
>>>
>>> # Assign multiple tags
>>> Tags([PowerTag(), HighSpeedTag()]).assign(signal_net)
>>>
>>> # Assign using multiple arguments
>>> Tags(PowerTag(), HighSpeedTag(), CriticalTag()).assign(clock_net)
>>>
>>> # Tagging a nested pad from a circuit context
>>> class MyCircuit(Circuit):
...     component = MyComponent()
...
...     def __init__(self):
...         GroundTag().assign(self.component.lp.p[0])
>>>
>>> # Tagging self
>>> class MyLandpattern(Landpattern):
...     pad1 = MyPad().at(-0.5, 0)
...     pad2 = MyPad().at(0.5, 0)
...
...     def __init__(self):
...         HighSpeedTag().assign(self)
tags: list[Tag]#
assign[T](obj, /, *objs)[source]#
Return type:

T

Parameters:
  • obj (T)

  • objs (Any)

class TriangularViaStitchGrid(pitch, inset)[source]#

Bases: ViaStitchPattern

A triangular grid pattern for via stitching.

Places vias in a triangular (hexagonal close-packed) pattern within the target area. Used in the StitchVia constraint effect.

>>> pattern = TriangularViaStitchGrid(pitch=1.5, inset=1.0)
Parameters:
class ViaFencePattern(pitch, offset, num_rows=None, min_pitch=None, max_pitch=None, initial_offset=None, input_shape_only=None)[source]#

Bases: object

A pattern configuration for via fencing around routes or copper features.

Via fencing places vias around the perimeter of routes or copper areas. The pattern controls how these vias are arranged. Used in the FenceVia design rule constraint.

See fence_via() for usage.

>>> fence_pattern = ViaFencePattern(
...     pitch=1.0,
...     offset=0.5,
...     num_rows=2,
...     min_pitch=0.5,
...     max_pitch=2.0
... )
Parameters:
  • pitch (float)

  • offset (float)

  • num_rows (int | None)

  • min_pitch (float | None)

  • max_pitch (float | None)

  • initial_offset (float | None)

  • input_shape_only (bool | None)

pitch: float#

The preferred center-to-center spacing between vias in millimeters

offset: float#

The center-to-center distance between fence via rows, and the default initial offset in millimeters

Positive values indicate an outwards offset, negative values an inwards offset. The offset for routes must be positive. If initial_offset is not specified, this value serves as the default initial offset.

num_rows: int | None = None#

The number of rows of fence vias to generate, default is 1

min_pitch: float | None = None#

The minimum allowed center-to-center pitch between vias in millimeters

max_pitch: float | None = None#

The maximum allowed center-to-center pitch between vias in millimeters

initial_offset: float | None = None#

The initial offset of the first row of fence vias

The initial offset is the perpendicular distance from the boundary of the route or copper feature to the centers of the first row of fence vias. Positive values indicate an outwards offset, while negative values indicate an inwards offset (inset). The offset must be positive for routes. Defaults to the same value as offset if unspecified.

input_shape_only: bool | None = None#

For pours only, whether to fence the original pour outline

If true, the pre-isolation outline shape of the pour is used to generate the fence vias. If false, the post-isolation shape is used. Defaults to true if not specified.

design_constraint(condition1, condition2=None, /, *, priority=0, name=None)[source]#

Syntactic helper function for creating the correct type of class. The overloads will generate UnaryDesignConstraint or BinaryDesignConstraint depending on the number of conditions, and should provide correct method completion in the editor.

Overloads:
Parameters:
class Composite(transform=Transform((0, 0), 0, (1, 1)))[source]#

Bases: Container, Kinematic[Transform]

Create a geometric composition of objects. This allows the construction of, for example, a landpattern with a part being constructed in its own frame of reference, or a complex symbol to be constructed by composing multiple elements into one.

>>> class MyLandpattern(Landpattern):
...     pad1 = MyPad().at(-0.5, 0)
...     pad2 = MyPad().at(0.5, 0)
...     courtyard = Courtyard(rectangle(2, 1))
...
...     def __init__(self):
...         plus = plus_symbol(0.5, 0.1)
...         self.plus = Silkscreen(plus.at(0, 1))
...         self.composite = Composite(Transform.rotate(45))
...         self.composite.plus = Silkscreen(plus.at(math.sqrt(2)/2, math.sqrt(2)/2))
Parameters:

transform (T | None)

at(x, y=None, /, *, rotate=0)[source]#

Place this object relative to its frame of reference. Note that this modifies the object, and does not create a copy.

Overloads:
Parameters:
  • x (Transform | Point | float) – x-value, transform, or placement to adopt.

  • y (float | None) – y-value if x is an x-value. This argument is only valid in that context.

  • rotate (float)

Returns:

the object itself.

class Container[source]#

Bases: Container

Namespace-like container object, will be traversed in all introspection. Objects in a container must be valid in the context where the container is instantiated, and will be considered to be children of the conatiner’s parent in the scene graph. Can have any attribute set.

class RoutePoint[T: Port](*, layer, shape=None, bundle=<class 'jitx.net.Port'>)[source]#

Bases: ControlPoint, Generic[T]

Overloads:
Parameters:
shape: Shape | None#

a Circle with a positive radius.

Type:

The geometric shape of the control point

pad: RouteConnectionEndpoint[T]#

The route connection end point associated to this control point, used for routing.

class PairInsertion[T: DiffPair](*, layer, bundle=<class 'jitx.net.DiffPair'>, invert=False)[source]#

Bases: ControlPoint[T], Generic[T]

Differential pair insertion point. Transitions two individual, uncoupled traces into a differential pair.

Overloads:
  • *, layer (int), bundle (type[T]), invert (bool) = False

  • *, layer (int), invert (bool) = False

Parameters:

Pair insertion points can also be netted directly with other objects using Net or TopologyNet.

The coupled end of pair insertion can connect to the back side of a pair point, and an inverted insertion can connect to the front side of an pair point. The relationships are reversed if the pair point is inverted. Similarly an insertion point can only connect to an inverted insertion point. The diagram below shows why inverting one of the insertions is necessary.

Note that specifying invert does _not_ imply that insertion point is rotated, to have insertion points face each other, one must be rotated 180 degrees.

The default p and n sides are as shown below: .. code-block:: text

uncoupled.p – – uncoupled.p
/

== coupled == (inverted, rotated 180 degrees)

/

uncoupled.n – – uncoupled.n

This can be mirrored, (which, for example, would be needed to make a geometric connection possible on the other end, where the diff-pair route terminates in a second insertion point) by setting invert=True.

When used with PortAttachment, it needs an ordered pair of ports. The first port is connected to the p side and the second to the n side of the control point. Using PortAttachments for this should not be necessary for the vast majority of cases.

>>> class MyCircuit(Circuit):
...     c1 = MyComponent1()
...     c2 = MyComponent2()
...     def __init__(self):
...         self.insertion1 = PairInsertion(layer=0).at(-2, 0)
...         self.insertion2 = PairInsertion(layer=0, invert=True).at(2, 0, rotate=180)
...         self.nets = [
...             Net([self.c1.p1, self.c2.p1]),
...             Net([self.c1.p2, self.c2.p2]),
...         ]
...         self.attachments = [
...             PortAttachment([self.c1.p1, self.c1.p2], self.insertion1),
...             PortAttachment([self.c2.p1, self.c2.p2], self.insertion2),
...         ]
...         self.routes = [
...             Route(self.insertion1.coupled, self.insertion2.coupled, 0)
...         ]
port: T#

The differential pair port associated to this control point, used for connections.

coupled: CoupledRouteConnectionEndpoint[T]#

Coupled-side pads of the differential insertion point, used for connections and routing.

uncoupled: UncoupledConnectionEndpoint[T]#

Uncoupled-side pads of the differential insertion point, used for connections and routing.

invert: bool#

Mirror the chirality of the insertion point.

class PairPoint[T: DiffPair](*, layer, bundle=<class 'jitx.net.DiffPair'>, invert=False)[source]#

Bases: ControlPoint[T], Generic[T]

A differential pair control point connects two segments of a differential pair, while still paired, allowing for each segment to be configured independently.

Overloads:
  • *, layer (int), bundle (type[T]), invert (bool) = False

  • *, layer (int), invert (bool) = False

Parameters:

A pair point can connect to another to other pairs, or insertion points. A chain of pair points would connect front -> back, as long as neither or both are inverted. To connect an inverted to non-inverted point you’d connect front to front or back to back. See the diagram in PairInsertion for details.

port: T#

The differential pair port associated to this control point, used for connections.

front: CoupledRouteConnectionEndpoint[T]#

Front-side pads of the differential insertion point, used for routing.

back: CoupledRouteConnectionEndpoint[T]#

Back-side pads of the differential insertion point, used for routing.

invert: bool#

Mirror the chirality of the pair point.

class Copper(shape, layer)[source]#

Bases: Structural

Copper element on a layer index.

Represents a copper element with a defined shape on a particular layer index. Can be combined with other copper elements to form nets.

>>> self.gnd = Net()
>>> self.ground_copper = Copper(Circle(diameter=2.0), layer=0)
>>> self.gnd += self.ground_copper
Parameters:
shape: Shape#

The geometric shape of the copper element.

layer: int#

The layer index for this copper element.

class Pour(shape, layer, *, isolate=0, rank=0, orphans=True)[source]#

Bases: Copper

Copper pour is a filled copper element with isolation and priority settings.

>>> self.gnd = Net()
>>> self.ground_pour = Pour(Circle(diameter=10.0), layer=0, rank=1)
>>> self.gnd += self.ground_pour
Parameters:
isolate: float = 0#

Isolation distance from other features in millimeters.

Deprecated since version 4.4: Isolation is deprecated and will be removed in future versions. Use a design_constriant() instead.

rank: int = 0#

Pour priority rank with higher ranks being prioritized.

orphans: bool = True#

Whether to include orphaned copper areas.

Deprecated since version 4.0.

Note

This field is currently not respected.

class Design[source]#

Bases: Structural

To create a JITX design, create a subclass of this class. It will need a Board, a Substrate, and a Circuit assigned to the fields board, substrate, and circuit respectively.

Schematic settings can optionally be provided by adding fields of type Paper, SchematicTemplate, SchematicMarking, and SchematicTitlePage. By default, the design uses the ANSI A paper size.

>>> class MyDesign(Design):
...     board = MyBoard()
...     substrate = MySubstrate()
...     circuit = MyCircuit()
...     paper = Paper.ANSI_B
board: Board#
substrate: Substrate#
circuit: Circuit#
class Initialized(design)[source]#

Bases: Event

Event that is fired once the entire design has been gone through the initial construction and initialization. The design has not yet been dispatched for processing, and can still be modified if needed.

>>> class MyComponent(Component):
        @Design.Initialized.on
        def on_initialized(self, init: Design.Initialized):
            ... # do something after initialization
Parameters:

design (Design)

design: Design#

The initialized design.

class Submitted(design)[source]#

Bases: Event

Parameters:

design (Design)

design: Design#
capture(f)[source]#
Parameters:

f (Callable[[RuntimeDesign], None])

resubmit()[source]#
setup = <function Design.setup>#
finalize = <function Design.finalize>#
exception UserCodeException(message, hint=None)[source]#

Bases: Exception

Exception raised when user code appears to have constructed an invalid design structure.

Parameters:
  • message (str)

  • hint (str | None)

hint: str | None#
class Courtyard(shape, side=Side.Top)[source]#

Bases: SurfaceFeature

Courtyards are used to indicate land pattern bounds.

>>> courtyard = Courtyard(rectangle(3, 3))
Parameters:
class Custom(shape, side=Side.Top, *, name=None)[source]#

Bases: SurfaceFeature

Custom surface feature with user-defined name.

>>> custom = Custom(rectangle(2, 2), name="Fab")

It’s recommended that a custom layer is subclassed if it’s used to represent actually relevant geometry for the fabrication of the board.

>>> class Stiffening(Custom):
...     pass

The name of the custom layer as presented in the UI defaults to the name of the class.

Parameters:
name: str#

Name of the custom feature layer.

class Cutout(shape)[source]#

Bases: Feature

Cutout element for holes and slots. Through-hole pads will include their hole definition using a Cutout.

>>> cutout = Cutout(Circle(radius=1.0))
Parameters:

shape (Shape)

class Finish(shape, side=Side.Top)[source]#

Bases: SurfaceFeature

Add a shape to the glue application layer

>>> finish = Finish(rectangle(1, 1))
Parameters:
class Glue(shape, side=Side.Top)[source]#

Bases: SurfaceFeature

Add a shape to the glue application layer

>>> glue = Glue(circle(diameter=1), side=Side.Bottom)
Parameters:
class KeepOut(shape, layers, *, pour=False, via=False, route=False)[source]#

Bases: MultiLayerFeature

Construct keepout regions on a range of layers.

>>> # Keep out pours and vias on the top layer
>>> keepout = KeepOut(layers=LayerSet(0), pour=True, via=True, route=False)
Parameters:
pour: bool = False#

Keep pours from covering this area.

via: bool = False#

Avoid auto-placing vias in this area.

route: bool = False#

Disallow auto-router traces in this area.

class Paste(shape, side=Side.Top)[source]#

Bases: SurfaceFeature

Add a shape to the paste application layer

>>> paste = Paste(circle(diameter=1))
Parameters:
class Silkscreen(shape, side=Side.Top)[source]#

Bases: SurfaceFeature

Add a shape to the silkscreen layer

>>> silkscreen = Silkscreen(rectangle(2, 3), side=Side.Bottom)
Parameters:
class Soldermask(shape, side=Side.Top)[source]#

Bases: SurfaceFeature

Add a shape to the solder mask layer

>>> soldermask = Soldermask(rectangle(2, 1), side=Side.Top)
Parameters:
class OverlappableCopper(shape, layer)[source]#

Bases: SingleLayerFeature

Copper element on a layer index that is not associated with a net.

Represents a copper element with a defined shape on a particular layer index. It will be ignored by router and overlap checks. This can be used to define a net-tie that overlaps pads from two different nets, or an antenna, or more generally where an overlap is needed, but it does not cleanly fit the model and gets flagged as an error.

>>> self.copper = PhantomCopper(Circle(diameter=2.0), layer=0)
Parameters:
decompose(ob, types, /, *, refs=False, filter=None)[source]#

Collect fields of a type or types into a sequence that can be used for deconstruction assignment. The elements are all semi-shallow children, traversing lists and dicts, but not other structural elements. Note that objects of subtypes can be returned as well.

Overloads:
Parameters:
>>> class A(Circuit):
...     other = "field"
...     ports = [Port(), DiffPair()]
...     another = Port()
>>> p1, p2, p3 = decompose(A(), Port)
>>> isinstance(p2, DiffPair) and not isinstance(p3, DiffPair)
True
extract(ob, types, /, through=None, *, opaque=None, refs=False, filter=None)[source]#

Recursively traverse all objects in the tree and yield all objects of a particular type or types. This is similar to visit(), but does not generate the meta information associated with each returned element.

Overloads:
Parameters:
>>> def component_ports(comp:Component) -> list[Port]:
...     return list(extract(comp, Port))
visit(root, types, /, through=None, *, path=RefPath(()), transform=Transform((0, 0), 0, (1, 1)), opaque=None, refs=False, filter=None)[source]#

Find elements in an object structure. Objects of the specified types will be returned, traversing down through the object tree structure. If through is specified the traversal will only pass through those when looking for matching elements, otherwise all JITX structural elements will be traversed.

Overloads:
Parameters:
  • root – The root object to start traversing

  • types (type | tuple[type, ...] | Union) – A type, tuple of types, or union of types to find

  • through (tuple[type, ...] | Union | None) – Optional argument to limit which objects to recurse through. If undefined, only Structural elements will be visited.

  • path (RefPath) – Optional starting path

  • transform (Transform | None) – Optional starting transform, if unset will default to the identity transform. Set to None to suppress computing transforms.

  • opaque (tuple[type, ...] | Union | None) – Optional argument to limit which objects to recurse through. If unspecified, or None, contents of Ref elements will be skipped. To recurse through all structural elements, including Ref elements, set this to an empty tuple.

  • filter (Callable[[Any], bool] | None) – Optional filter function to apply to the elements. Only elements that pass the filter will be returned.

  • refs (bool)

Yields:

Pairs of Trace to the element, and the element itself.

The traversal reaches elements held in lists, dicts and nested structural objects. A trace’s transform is the transform of the element’s frame of reference, relative to the root. A placed element’s own transform is its placement in that frame, so its placement relative to the root is trace.transform * elem.transform.

>>> # Every pad a landpattern holds, thermal pads included
>>> pad_count = sum(1 for _ in visit(lp, Pad))
class Landpattern[source]#

Bases: Open, Positionable

Component landpattern definition, also known as a footprint, package, or land-pattern.

Defines the pads and associated geometry for the interface between an electrical component and the circuit board.

>>> # MyPad is a user-defined Pad subclass (see Pad class below)
>>> # Silkscreen, Courtyard are from jitx.feature
>>> # Polyline, rectangle are from jitx.shapes
>>> class ZigZagLandpattern(Landpattern):
    ...     pad1 = MyPad().at(-0.5, 0)
    ...     pad2 = MyPad().at(0.5, 0)
    ...
    ...     silkscreen = Silkscreen(
    ...         Polyline(
    ...             0.1,
    ...             [
    ...                 (-0.4, 1), (-0.3, 1.2), (-0.2, 0.8),
    ...                 (-0.1, 1.2), (0, 0.8), (0.1, 1.2),
    ...                 (0.2, 0.8), (0.3, 1.2), (0.4, 1),
    ...             ]
    ...         )
    ...     )
    ...
    ...     courtyard = Courtyard(rectangle(2, 1))
class Pad[source]#

Bases: Open, Positionable

Class representing a pad, user code should overload this class in order to create new pad definitions. If the pad contains a Cutout it will be interpreted as a through-hole pad, otherwise it will be interpreted as a surface mount pad.

>>> # Circle, rectangle are from jitx.shapes
>>> # Cutout, Soldermask are from jitx.feature
>>> class MyPad(Pad):
    ...     shape = Circle(diameter=0.8)
    ...     shapes = {
    ...         (0, 2): Circle(diameter=0.7),
    ...         1: PadShape(Circle(diameter=0.8), nfp=Circle(diameter=0.4)),
    ...         -1: rectangle(2., 2.),
    ...     }
    ...
    ...     def __init__(self):
    ...         self.cutout = Cutout(Circle(diameter=0.4))
    ...         self.soldermask = Soldermask(self.shape)
shape: Shape | PadShape#

The geometric shape of the pad or a PadShape to specify the regular shape and the shape when non-functional pads are removed. Can be overridden on a per-layer basis by shapes. When using a PadShape with nfp, the nfp removal does not apply to surface layers, to have surface nfp removal, use the shapes mapping to declare top and bottom explicitly.

shapes: Mapping[int | tuple[int, ...], Shape | PadShape] = {}#

The geometric shapes of the pad for specific layers. Overrides shape for the given layers.

entry: Sequence[Point] = ()#

Points in the pad’s frame where routes should enter the pad, inside or on the boundary of the pad shape. A route attaches to the point closest to where it approaches the pad. If empty, the router picks the point.

class PadMapping(entries)[source]#

Bases: Structural, Ref

Mapping between component ports and landpattern pads.

If a component declares no pad mapping, a default mapping is created when the design is translated: the component’s single-pin ports, in declaration order, are paired one to one with its pads in declaration order. Pads left over stay unconnected, and a port left without a pad is an error. Declare a PadMapping when:

  • a port connects to more than one pad, such as a ground pin and an exposed thermal pad;

  • the ports are declared in a different order from the pads, for example when pin 1 is not the first declared port.

Once a component declares any PadMapping, no default mapping is made, so every single-pin port must appear in one. A pad belongs to at most one port: mapping a second port to a pad already mapped raises an error at translation.

>>> class MyComponent(Component):
...     GND = Power()
...     VIN = Power()
...     VOUT = Power()
...
...     lp = MyLandpattern()
...     mappings = PadMapping({
...         GND: [lp.p[1], lp.p[4]],
...         VIN: lp.p[3],
...         VOUT: lp.p[2],
...     })
>>> class MyComponent(Component):
...     GND = Power()
...     VIN = Power()
...     VOUT = Power()
...
...     lp = MyLandpattern()
...     mappings = PadMapping({
...         GND: lp.p[1],
...         VIN: lp.p[2],
...         VOUT: lp.p[3],
...     })
Parameters:

entries (Mapping[Port, Pad | Sequence[Pad]] | Iterable[tuple[Port, Pad | Sequence[Pad]]])

get[T](port, default=None, /)[source]#

Return the pad or port associated with the given port or pad.

Overloads:
Parameters:
Return type:

Pad | Sequence[Pad] | Port | T

items()[source]#
values()[source]#
inverse()[source]#

Return the inverse mapping from pads to ports.

Return type:

Mapping[Pad, Port]

class LayerSet(*layers, ranges=())[source]#

Bases: object

Set of board layers specified by ranges.

Overloads:
Parameters:

Defines which layers a feature or element applies to using layer index ranges.

Basic construction with individual layers:

>>> # Single layer
>>> top_layer = LayerSet(0)
>>> top_layer.ranges
[(0, 0)]
>>> # Multiple individual layers
>>> signal_layers = LayerSet(0, 2, 4)
>>> signal_layers.ranges
[(0, 0), (2, 2), (4, 4)]
>>> # From a sequence of layers
>>> power_layers = LayerSet([1, 3, 5])
>>> power_layers.ranges
[(1, 1), (3, 3), (5, 5)]

Range construction using class methods:

>>> # Range from start to end (exclusive)
>>> inner_layers = LayerSet.range(1, to=4)
>>> inner_layers.ranges
((1, 3),)
>>> # Range from start through end (inclusive)
>>> outer_layers = LayerSet.range(0, through=2)
>>> outer_layers.ranges
((0, 2),)
>>> # All layers
>>> all_layers = LayerSet.all()
>>> all_layers.ranges
((0, -1),)

Combining multiple LayerSet objects:

>>> # Combine different layer sets
>>> top_and_bottom = LayerSet(0, -1)
>>> inner_range = LayerSet.range(1, to=3)
>>> combined = LayerSet(top_and_bottom, inner_range)
>>> combined.ranges
[(0, 0), (-1, -1), (1, 2)]

Using with explicit ranges:

>>> # Direct range specification
>>> custom_ranges = LayerSet(ranges=[(0, 2), (4, 6)])
>>> custom_ranges.ranges
[(0, 2), (4, 6)]

Common use cases:

>>> # Keepout layers
>>> keepout = KeepOut(layers=LayerSet(1), pour=False, via=True, route=True)
ranges: Sequence[tuple[int, int]]#

Sequence of (start, end) layer index ranges.

invert()[source]#

Return a layer set with all layers inverted.

Return type:

LayerSet

classmethod range(start, *, to=None, through=None)[source]#

Create a layer set from a start and end layer.

Overloads:
Parameters:
  • start (int) – Starting layer index.

  • to (int | None) – Ending layer index (exclusive).

  • through (int | None) – Ending layer index (inclusive).

Returns:

LayerSet covering the specified range.

Return type:

LayerSet

classmethod all()[source]#

Create a layer set covering all layers.

Return type:

LayerSet

Returns:

LayerSet covering all layers from 0 to -1 (bottom).

class Side(*values)[source]#

Bases: IntEnum

Board side enumeration.

Represents the top and bottom sides of a circuit board. Note that this is often a relative representation, and as such “Top” simply means “the same side”, and “Bottom” means “the opposite side”.

Supports arithmetic operations to flip sides or adjust layer indices:

  • ~side : Returns the opposite side (flip()).

  • side * other : Flips other if side is Bottom.

  • side + int : Adds an integer offset to the side’s value.

  • side - int : Subtracts an integer offset from the side’s value.

Top = 0#
Bottom = -1#
flip()[source]#

Return the opposite side. Top becomes Bottom, Bottom becomes Top.

apply(other)[source]#
Parameters:

other (int)

class DiffPair[source]#

Bases: Port

Bundles two pins p and n. The DiffPair base class bears special meaning and standardizes naming, any diff-pair type signal should inherit this base class.

>>> class Transmission(DiffPair):
...     pass
>>> class MDI:
...     tx = Transmission()
...     rx = Transmission()
p = Port()#
n = Port()#
class Net[T: Port](ports=(), *, name=None, labeled=None, symbol=None)[source]#

Bases: Ref, Structural, Generic[T]

Construct a net by connecting ports or other nets. Note that nets are constructed implicitly by adding ports and other nets together, and constructing a net explicitly only has the main benefit of declaring the net up front, and giving it a name, label, and/or symbol.

Parameters:
  • ports (Iterable[T | Net[T] | Copper | Via | ControlPoint]) – Optional list of ports to initially add to the net.

  • name (str | None) – Optional name of this net. A net without one is named after the field it is assigned to. When named nets are connected, the connected net takes one of their names: names from higher circuits in the design come first, and among those, the shortest name.

  • labeled (bool | None) – Whether this net gets a label on its wires in the schematic. If unset, the net gets a label if its name is provided here. A net with a symbol shows the symbol instead of the label. If any connected net is labeled, the label is shown. Otherwise, if any is explicitly unlabeled, it is not.

  • symbol (Symbol | None) – Optional net symbol for this net. Only applicable to simple, non-bundle, nets.

>>> Net(name="P5V5")
Net(name="P5V5")
>>> a, b = Port(), Port()
>>> isinstance(a + b, Net)
True
name: str | None = None#
labeled: bool | None = None#
connected: list[Union[T, Net[T], Copper, Via, ControlPoint]]#
property port: T#
property symbol: Symbol | None#
typecheck()[source]#

Check that the net’s connected types are compatible, and return a representative port object from this net.

This function raises an error if there are incompatible elements in the net’s connected set.

Return type:

Optional[T]

classmethod zip(first, second, *more)[source]#

Zip multiple sequences of ports into a sequence of nets, where each net contains the corresponding ports from each sequence. For example, the first net in the returned sequence will contain the first port from each input sequence, the second net will contain the second port, and so on. This is particularly useful when dealing with arrays of ports that need to be connected in parallel.

Parameters:
Return type:

Sequence[Net[T]]

Returns:

A sequence of Nets, where each Net contains corresponding elements from all input sequences.

>>> a, b, c = Port(), Port(), Port()
>>> x, y, z = Port(), Port(), Port()
>>> u, v, w = Port(), Port(), Port()
>>> n1, n2, n3 = Net.zip([a, b, c], [x, y, z], [u, v, w])
>>> n1.connected == [a, x, u]
True
class Port[source]#

Bases: Structural

A Port is the fundamental connectivity element of JITX. It is used to represent everything from “pins” of a component, to the “virtual” pins of a circuit, to the abstract ports that make up a pin-assignment problem.

Ports can only be netted to other ports of the same concrete type, thus a subclass of Port can only be netted to the same subclass of port. For parameterized ports, they also need to match the same parameters. To create a multi-signal port, create a subclass of Port with a member field for each signal. These are sometimes also referred to as “bundle” ports.

Instantiating Port directly represents a single electrical signal, and is the only type that is allowed as a leaf in a complex Port structure.

Ports can be netted together using the + operator. This will create a Net object that represents the netted ports. If the ports should be part of a signal topology where the order of the ports matters, use the >> operator. This will create a TopologyNet object that represents the netted ports that will only allow the ports to be connected in this particular order while routing. Note that you must use a topology net even if there is only two ports in the net if you wish to apply a signal integrity constraint.

>>> class MyDualSignal(Port):
...     a = Port()
...     b = Port()
>>> class MyDualAndClockSignal(Port):
...     dual = MyDualSignal()
...     clock = Port()
is_single_pin()[source]#
no_connect()[source]#

Mark this port as no-connect.

>>> class MyComponent(Component):
...     port = Port()
...     # ...
...
>>> class MyCircuit(Circuit):
...     component = MyComponent()
...     def __init__(self):
...         self.component.port.no_connect()
is_no_connect()[source]#

Check if this port is marked as no-connect.

Return type:

bool

to(other)[source]#

Refer to a topology between these two ports. This does not construct the signal topology itself, but is used to create a topology object which is used as an argument to other functions operating on topologies. To construct a signal topology, use the >> operator to construct TopologyNet and bridge components using the BridgingPinModel, and terminate the topology using the TerminatingPinModel. The pin-models can be added after the fact in a circuit if needed, but ideally they’re already present in the component definition. After that, a signal constraint can applied to the end-to-end topology.

Parameters:

other (Self) – The destination port of the same type as this port.

Return type:

Topology[Self]

Returns:

A Topology object representing the path from this port to the other port. Use this with constraint functions like Constrain(...).timing(...).

>>> class MyCircuit(Circuit):
...     a = TransmitterComponent()
...     b = ReceiverComponent()
...     def __init__(self):
...         self.passive = Resistor(...)
...         p1, p2 = decompose(self.passive, Port)
...         self.signal = [
...             # Note: pin models are best added in the component
...             # definition, but can be added in the circuit after the
...             # fact if needed, as done here.
...             TerminatingPinModel(self.a.transmit, delay=2e-12, loss=0.1),
...             self.a.transmit >> p1,
...             BridgingPinModel(p1, p2, delay=10e-12, loss=0.1),
...             p2 >> self.b.receive,
...             TerminatingPinModel(self.b.receive, delay=2e-12, loss=0.1),
...         ]
...         self.constraint = Constrain(self.a.transmit.to(self.b.receive)).timing(50e-12)
class provide[T: Port](Bundle)[source]#

Bases: Generic[T]

Decorator to help set up the pin-assignment problem. In the base form, the decorator is applied to a method of a circuit that will be given a bundle to map, and should return a list of possibilities how to map that bundle. Each returned options will be offered to requirements, so if 3 options are returned, three different instances of this bundle can be required, served by each option. This is commonly known as the “pin swapping” case, where all options can be used, but it’s not settled which is used where.

For other provisioning schemes, see the @provide.one_of and @provide.subset_of decorators.

Parameters:

Bundle (Union[T, type[T]]) – The type of the bundle to provide

>>> class MyBundle(Port):
...     a = Port()
...     b = Port()
>>> class MyCircuit(Circuit):
...     # these are created here for demonstration purposes, we could just
...     # as easily refer to a component's ports.
...     internal_1 = Port(), Port()
...     internal_2 = Port(), Port()
...     @provide(MyBundle)
...     def provide_my_internals(self, bundle: MyBundle):
...         return [{
...             # first option
...             bundle.a: self.internal_1[0],
...             bundle.b: self.internal_1[1],
...         }, {
...             # second option
...             bundle.a: self.internal_2[0],
...             bundle.b: self.internal_2[1],
...         }]
>>> class MyOtherCircuit(Circuit):
...     subcircuit = MyCircuit()
...     interfaces = MyBundle(), MyBundle()
...     def __init__(self):
...         self.nets = [
...             interfaces[0] + subcircuit.require(MyBundle),
...             interfaces[1] + subcircuit.require(MyBundle),
...         ]
Provider = Provider#
classmethod all_of(Bundle)[source]#

This is the default behavior and indeed an alias of using @provide directly without specifying a provisioning scheme. Each returned option will be offered to requirements, so if 3 options are returned, three different instances of this bundle can be required, served by each option. This is commonly known as the “pin swapping” case, where all options can be used, but it’s not settled which is used where.

Parameters:

Bundle (Union[T, type[T]]) – The type of the bundle to provide

classmethod one_of(Bundle)[source]#

Provide a single instance of the given bundle type, chosen from a list of possible options. The options may overlap with other provided functions. This is the dynamic function use case, where a function can served by multiple different ports, but there’s only one instance of the function provided, e.g. a microcontroller has only one clock, but which pin it’s on is not settled.

Parameters:

Bundle (Union[T, type[T]]) – The type of the bundle to provide

classmethod subset_of(Bundle, n)[source]#

Similar to @provide.one_of, but allows for n instances out of a list of options to be provided. This is equivalent to manually copying a @provide.one_of decorated method n times.

Parameters:
  • Bundle (Union[T, type[T]]) – The type of the bundle to provide

  • n (int) – The number of instances to provide

class Provide[T: Port](Bundle, mapping=None)[source]#

Bases: Structural, Ref, Generic[T]

This is the general structure for setting up a pin-assignment problem. It is recommended to use one of the convenience decorators in provide instead, but if the full power of the pin-assignment system is needed in a way that is not covered by the decorators, or if you need programmatic control over the pin-assignment problem, then directly instantiating this class the appropriate number of times and populating the options in each may be a way to achieve that.

The equivalent of the conenvience decorators are also available as methods on this class for use inside functions, such as __init__.

>>> class MyCircuit(Circuit):
...     def __init__(self, ports: int):
...         self.ports = [Port() for _ in range(ports)]
...         self.gpios = Provide(GPIO).all_of(lambda b: [{b.port: port} for port in self.ports])

Note

Be aware of pythons binding of loop-variables, if you create Provides in a loop, you should bind the loop variable if it’s used in the mapping function. Consider the functional equivalent of all_of() but using one_of() in the example below:

>>> class MyCircuit(Circuit):
...     def __init__(self, ports: int):
...         self.ports = [Port() for _ in range(ports)]
...         self.gpios = [Provide(GPIO).one_of(lambda b, port=port: [{b.port: port}]) for port in ports]

Note that the port argument is bound to the lambda function’s body using a parameter with a default argument, instead of using the loop variable directly, which could potentially be bound to a different value by the time the lambda is called. In the current implementation, the lambda is called immediately, so the result would still be correct here, but it’s a good practice to avoid this pitfall.

Parameters:
  • Bundle (T | type[T]) – The type of the bundle to provide

  • mapping (Provider | None) – The mapping function to use to populate the options for this Provide port. Note that this is the equivalent argument of calling one_of(), and it’s recommended to use that method instead for clarity.

Provider = Provider#
options: Sequence[Sequence[tuple[Port, Port]]]#
bundle: T#
all_of(mapping)[source]#

Equivalent of the @provide.all_of decorator, but can be constructed inside a function, such as __init__. Useful when needing more parametric control over the pin-assignment problem. Note that this function will return a collection of Provide objects.

Return type:

Sequence[Provide]

Parameters:

mapping (Provider)

one_of(mapping)[source]#

Equivalent of the @provide.one_of decorator, but can be constructed inside a function, such as __init__. Useful when needing more parametric control over the pin-assignment problem.

Return type:

Provide

Parameters:

mapping (Provider)

subset_of(count, mapping)[source]#

Equivalent of the @provide.subset_of decorator, but can be constructed inside a function, such as __init__. Useful when needing more parametric control over the pin-assignment problem. Note that this function will return a collection of Provide objects.

Return type:

Sequence[Provide]

Parameters:
classmethod require(Bundle, provider, restrictions=None)[source]#

This is the underlying framework function for requiring a bundle provided by a different circuit. Please use Circuit’s convenience require() method instead.

Parameters:
Return type:

T

classmethod provided_by(port)[source]#
Return type:

None | Circuit | Component

Parameters:

port (Port)

classmethod required_through(port)[source]#
Return type:

None | Port

Parameters:

port (Port)

classmethod restrictions_for(port)[source]#

Get restrictions associated with a required bundle port.

Return type:

Mapping[Port, Callable[[Port], Any]] | None

Parameters:

port (Port)

class Placement(translate, rotate=0, scale=(1, 1), *, on=None)[source]#

Bases: Transform

Component placement with side information.

Overloads:
Parameters:

Extends Transform to include which side of the board the component is placed on.

Multiplying a layer index, Side, or LayerSet by a placement expresses it in the placement’s parent frame: unchanged on the top side, flipped to the opposite side of the board on the bottom side.

>>> placement = Placement((0, 0), on=Side.Bottom)
>>> placement * 0
-1
>>> placement * Side.Top
<Side.Bottom: -1>
side: Side = 0#

Which side of the board this placement is on.

clone()[source]#

Create a copy of this placement.

inverse()[source]#

Compute the inverse of this placement.

Return type:

Placement

class Positionable[source]#

Bases: Structural, Kinematic[Placement]

Base class for objects that can be positioned on the board.

at(x, y=None, /, *, on=Side.Top, rotate=0)[source]#

Place this object relative to its frame of reference. Note that this modifies the object, and does not create a copy.

Overloads:
Parameters:
  • x (Placement | Transform | Point | float) – x-value, transform, or placement to adopt.

  • y (float | None) – y-value if x is an x-value. This argument is only valid in that context.

  • rotate (float) – Rotation in degrees to apply to the object. Only applicable if not supplying a transform or placement.

  • on (Side) – If set to bottom, this object will be placed on the “opposite” side from its frame of reference. This means if the frame of reference is on the bottom of the board, setting this to “bottom” will actually put the object back on top.

Returns:

the object itself.

capsule(width, height, *, anchor=Anchor.C)[source]#

Create a capsule shape represented by a line with a thickness. Fillets the end of the shorter side (min(width,height)) with a radius of half that sides dimension. So if width < height - then the length of the capsule is in the Y dimension. If width > height - then the length of the capsule is in the X dimension. If width == height - then a circle is returned.

Parameters:
  • width (float) – X dimension of the constructed capsule shape.

  • height (float) – Y dimension of the constructed capsule shape.

  • anchor (Anchor) – Localizes the capsule shape around the origin. The default value is C which means that the capsule is centered about the origin for both the X and Y axes. If provided the value NW, then the capsule is created such that its top edge abuts X axis and its left edge abuts the Y axis.

Return type:

Union[Shape[Circle], Shape[Polyline]]

rectangle(width, height, *, radius=None, chamfer=None, anchor=Anchor.C)[source]#

Create an axis aligned rectangle at the origin.

Overloads:
Parameters:
  • width (float) – X-dimension size of the rectangle in mm.

  • height (float) – Y-dimension size of the rectangle in mm.

  • radius (float | tuple[float, float, float, float] | Corners | None) –

    Optional parameter to round the corners of the rectangle. Value in mm
    • If this is a singular float - then that radius is applied to all 4 corners.

    • If this is a tuple of 4 floats - then each float is applied to the corners of the rectangle individually, starting with the top-right quadrant (+X, +Y) and then moving counter-clockwise.

    • If None - then no rounding occurs.

  • chamfer (float | tuple[float, float, float, float] | Corners | None) –

    Optional parameter to chamfer the corners of the rectangle. Value in mm.
    • If this is a singular float - then that chamfer is applied to all 4 corners.

    • If this is a tuple of 4 floats - then each float is applied to the corners of the rectangle individually, starting with the top-right corner (+X, +Y) and then moving counter-clockwise.

    • If None - then no chamfering occurs.

  • anchor (Anchor) – Localizes the rectangle feature around the origin. The default value is C which means that the rectangle is centered about the origin for both the X and Y axes. If provided the value NW, then the rectangle is created such that its top-left corner is located at the origin and the rest of the rectangle projects to the right and down.

Returns:

A Shape containing a Polygon or ArcPolygon with the characteristics described above.

Return type:

Shape[Polygon | ArcPolygon]

To create a normal 1x2 rectangle centered around the middle of the rectangle, you can do the following: >>> shape = rectangle(1.0, 2.0)

Simliarly to create a 1x2 rectangle with rounded corners: >>> shape = rectangle(1.0, 2.0, radius=0.25)

To create a 1x2 rectangle with chamfered corners: >>> shape = rectangle(1.0, 2.0, chamfer=0.25)

Rounded and chamfered corners can be applied simultaneously to the rectangle, causing the corners from the chamfer to be rounded: >>> shape = rectangle(1.0, 2.0, radius=0.25, chamfer=0.25)

Rounded or chamfered corners can be applied individually to each corner of the rectangle. >>> shape = rectangle(1.0, 2.0, radius=(0.1, 0.2, 0.3, 0.4))

To create a 1x2 rectangle anchored in the north-west corner, such that the rectangle projects to the right and down: >>> rectangle(1.0, 2.0, anchor=Anchor.NW)

class Arc(center, radius, start, arc=None, *, clockwise=None, large=None)[source]#

Bases: object

An Arc is represented using a 2D center point, a radius, a start angle between 0 and 360 degrees, and and arc sweep between -360 and 360 where positive values indicate counter-clockwise sweep and negative values indicate a clockwise sweep.

Overloads:
Parameters:

Note that arc angles are in degrees, and not in radians, to avoid numerical issues with precise 90-degree angles.

There are two overloaded constructors in addition to the native center, radius, start, and sweep. The first takes three points, start, mid, and end, and computes the arc from the three points. The second takes a start and end point and a radius, and computes the arc from these values.

>>> # Arc from center, radius, start angle, and sweep
>>> arc1 = Arc((0, 0), 5, 0, 90)
>>> # Arc through three points
>>> arc2 = Arc((0, 0), (1, 1), (2, 0))
>>> # Arc from start/end points, radius, cw orientation, and whether to draw the larger of two possible arcs.
>>> arc3 = Arc((0, 0), (10, 0), 5, clockwise=True, large=False)
center: Point#

The center coordinates of the arc.

start: float#

The start angle in degrees. Must be between 0 and 360.

radius: float#

The radius of the arc.

arc: float#

The arc sweep angle in degrees. Positive values are counter clockwise. Must be between -360 and 360.

class ArcPolygon(elements)[source]#

Bases: Primitive

A polygon consisting of arcs instead of points in the corners.

The ends of arcs will be connected with line segments to form a closed shape. Points are allowed as a “degenerate” arc where a sharp corner is desired, but are not required. For example, a rounded rectangle would consist of four arcs, but no points.

Note that self-intersecting arc polygons are not supported.

>>> # Rounded rectangle using four arcs
>>> corner_radius = 2.0
>>> arcs = [
...     Arc((8, 2), corner_radius, 270, 90),
...     Arc((8, 8), corner_radius, 0, 90),
...     Arc((2, 8), corner_radius, 90, 90),
...     Arc((2, 2), corner_radius, 180, 90),
... ]
>>> rounded_rect = ArcPolygon(arcs)
>>> # Mixed arcs and sharp corners
>>> mixed = ArcPolygon([
...     Arc((0, 0), 5, 0, 90),
...     (10, 5),
...     Arc((5, 10), 3, 90, 180),
... ])
Parameters:

elements (Sequence[Arc | Point])

elements: Sequence[Arc | Point]#

Each “corner” of the rounded polygon represented by an Arc, the last element will be connected to the first automatically, there’s no need to close the polygon. ArcPolygons do currently not support holes.

class ArcPolyline(width, elements)[source]#

Bases: Primitive

A polyline consisting of arcs instead of points in the corners.

Points are allowed as a “degenerate” arc where a sharp corner is desired, but are not required.

The width specifies the thickness of the polyline.

>>> trace = ArcPolyline(0.2, [
...     (0, 0),
...     Arc((5, 0), 2, 0, 90),
...     (5, 10),
...     Arc((10, 10), 3, 90, -180),
... ])
Parameters:
width: float#
elements: Sequence[Arc | Point]#
class Circle(*, radius=None, diameter=None)[source]#

Bases: Primitive

Create a circle primitive. Context will dictate whether the circle is a filled disk or a circle outline.

Overloads:
Parameters:
  • radius (float | None) – Specify the radius of the disk, or, alternatively

  • diameter (float | None) – Specify the diameter of the disk.

>>> # Circle by radius
>>> small_circle = Circle(radius=5.0)
>>> # Circle by diameter
>>> large_circle = Circle(diameter=5.0)
property diameter#
radius: float#

Radius of the circle

class Polygon(elements, holes=())[source]#

Bases: Primitive

A polygon consisting of 2d points.

Line segments will connect the points to form a closed shape. Note that self-intersecting polygons are not supported.

Polygons may be given holes, making it a polygon with holes.

>>> # Triangle polygon
>>> triangle = Polygon([(0, 0), (5, 0), (2.5, 4.33)])
>>> # Rectangle polygon
>>> rect = Polygon([(0, 0), (10, 0), (10, 5), (0, 5)])
>>> # Polygon with a hole
>>> outer = [(0, 0), (10, 0), (10, 10), (0, 10)]
>>> hole = [(3, 3), (7, 3), (7, 7), (3, 7)]
>>> donut = Polygon(outer, holes=[hole])
Parameters:
  • elements (Sequence[Point])

  • holes (Sequence[Sequence[Point]])

elements: Sequence[Point]#

Each corner of the polygon, the last element will be connected to the first automatically, there’s no need to close the polygon. If there are holes in the polygon, this represents the outside boundary.

holes: Sequence[Sequence[Point]] = ()#

Optional set of holes. Each hole is a sequence of point representing an inner boundary. The holes must be disjoint, that is they may not intersect each other or the outside boundary.

class Polyline(width, elements)[source]#

Bases: Primitive

A polyline consisting of 2d points.

The width specifies the thickness of the polyline.

>>> trace = Polyline(0.15, [
...     (0, 0), (5, 0), (5, 5), (10, 5)
... ])
Parameters:
width: float#
elements: Sequence[Point]#
class Substrate[source]#

Bases: Structural

Substrate definition with routing structures and fabrication constraints.

Substrates can be equipped with routing and differential routing structures which will be introspected when an attempt to lookup a particular impedance is made.

A substrate should also contain the permissible Via types as well as the FabricationConstraints.

>>> from jitx.sample import SampleFabConstraints, SampleTwoLayerStackup
>>> class MySubstrate(Substrate):
...     stackup = SampleTwoLayerStackup()
...     constraints = SampleFabConstraints()
...
...     class THVia(Via):
...         start_layer = 0
...         stop_layer = -1
...         diameter = 0.45
...         hole_diameter = 0.3
...         type = ViaType.MechanicalDrill
...
...     RS_50 = RoutingStructure(
...         name="RS_50",
...         impedance=50 * ohm,
...         layers=symmetric_routing_layers({
...             0: RoutingStructure.Layer(
...                 trace_width=0.1176,
...                 clearance=0.2,
...                 velocity=191335235228,
...                 insertion_loss=0.0178,
...             )
...         }),
...     )
>>> MySubstrate().routing_structure(50 * ohm)
RoutingStructure(name=RS_50, impedance=50 Ω)
stackup: Stackup#
constraints: FabricationConstraints#
routing_structure(impedance)[source]#

Look up a routing structure for a given impedance. The default implementation introspects the substrate for RoutingStructure objects. Override this method if you need to implement a custom lookup mechanism.

Return type:

RoutingStructure

Parameters:

impedance (Toleranced | PlainQuantity | float)

differential_routing_structure(impedance)[source]#

Look up a differential routing structure for a given impedance. The default implementation introspects the substrate for RoutingStructure objects. Override this method if you need to implement a custom lookup mechanism.

Return type:

DifferentialRoutingStructure

Parameters:

impedance (Toleranced | float)

class Pin(at, length=0, direction=Direction.Left, pin_name_size=None, pad_name_size=None)[source]#

Bases: Structural

Schematic symbol pin definition.

Parameters:
at: GridPoint#

The position of the pin in grid units.

length: int = 0#

The length of the pin in grid units.

direction: Direction = 'left'#

The direction of the pin.

pin_name_size: float | None = None#

Font size of the pin’s pin name text in grid units, overriding the parent Symbol’s pin_name_size attribute.

pad_name_size: float | None = None#

Font size of the pin’s pad name text in grid units, overriding the parent Symbol’s pad_name_size attribute.

classmethod left(at, length=0, pin_name_size=None, pad_name_size=None)[source]#

Create a left-facing pin (wire extends to the left).

Parameters:
  • at (GridPoint) – Grid position (row, column) for the pin.

  • length (int) – Length of the pin wire in grid units.

  • pin_name_size (float | None) – Optional font size for pin name label.

  • pad_name_size (float | None) – Optional font size for pad name label.

Returns:

A Pin instance configured to face left.

>>> Pin.left((0, 0), length=2)  # Pin at row 0, col 0
classmethod right(at, length=0, pin_name_size=None, pad_name_size=None)[source]#

Create a right-facing pin (wire extends to the right).

Parameters:
  • at (GridPoint) – Grid position (row, column) for the pin.

  • length (int) – Length of the pin wire in grid units.

  • pin_name_size (float | None) – Optional font size for pin name label.

  • pad_name_size (float | None) – Optional font size for pad name label.

Returns:

A Pin instance configured to face right.

>>> Pin.right((0, 5), length=2)  # Pin at row 0, col 5
classmethod up(at, length=0, pin_name_size=None, pad_name_size=None)[source]#

Create an up-facing pin (wire extends upward).

Parameters:
  • at (GridPoint) – Grid position (row, column) for the pin.

  • length (int) – Length of the pin wire in grid units.

  • pin_name_size (float | None) – Optional font size for pin name label.

  • pad_name_size (float | None) – Optional font size for pad name label.

Returns:

A Pin instance configured to face up.

>>> Pin.up((5, 2), length=1)  # Pin at row 5, col 2
classmethod down(at, length=0, pin_name_size=None, pad_name_size=None)[source]#

Create a down-facing pin (wire extends downward).

Parameters:
  • at (GridPoint) – Grid position (row, column) for the pin.

  • length (int) – Length of the pin wire in grid units.

  • pin_name_size (float | None) – Optional font size for pin name label.

  • pad_name_size (float | None) – Optional font size for pad name label.

Returns:

A Pin instance configured to face down.

>>> Pin.down((0, 2), length=1)  # Pin at row 0, col 2
class Symbol[source]#

Bases: Open, Structural

Symbols are a structural element in JITX encoding the schematic representation of a part. Symbols often contain electrical connection points represented by Pin, geometric artwork, and Text annotations. Symbols are linked to a design through a Component where a symbol’s Pin objects are mapped to Port objects.

Valid elements in a symbol are:

If a symbol is defined inside another symbol, they will be treated together as one symbol in the design.

For a rectangular symbol with automatic or configurable pin layout, use BoxSymbol.

>>> class MySymbol(Symbol):
...     a = Pin(at=(1, 0), length=1, direction=Direction.Right)
...     b = Pin(at=(-1, 0), length=1, direction=Direction.Left)
...     pin_name_size = 0.3
...     pad_name_size = 0.3
...     orientation = SymbolOrientation(0)
...     rect = rectangle(2, 2)
>>> class MyComponent(Component):
...     ports = [Port() for _ in range(2)]
...     symbol = BoxSymbol()

Note

Grid units are abstract schematic units where 1 grid unit equals the standard pin spacing in the schematic editor.

pin_name_size: float | None = None#

Font size of pin name text of Pin objects in this symbol, in grid units. If unset, defers to a parent Symbol, if a parent exists. This can be overriden at the Pin level by setting its pin_name_size attribute.

pad_name_size: float | None = None#

Font size of pad name text of Pin objects in this symbol, in grid units. If unset, defers to a parent Symbol, if a parent exists. This can be overriden at the Pin level by setting its pad_name_size attribute.

class SymbolMapping(entries)[source]#

Bases: Structural, Ref

Mapping between component ports and schematic symbol pins.

If no symbol mapping is provided, a default mapping will be created that maps ports to symbol pins in declaration order.

>>> class MyComponent(Component):
...     GND = Power()
...     VIN = Power()
...     VOUT = Power()
...
...     symbol = MySymbol()
...     mappings = SymbolMapping({
...         GND: symbol.gnd,
...         VIN: symbol.vin,
...         VOUT: symbol.vout,
...     })
Parameters:

entries (Mapping[Port, Pin] | Iterable[tuple[Port, Pin]])

items()[source]#
values()[source]#
class Toleranced(typ, plus, minus=Unspecified)[source]#

Bases: Interval

Interval Arithmetic Type for values with tolerances.

Overloads:
Parameters:

Supports standard arithmetic operations: +, -, *, /. All operations support both Toleranced values and floats. Operations propagate tolerances correctly (e.g., adding tolerances sums them, subtracting adds them for worst-case range).

Parameters:
  • typ (float) – Typical value (average/nominal)

  • plus (float | None) – Relative positive increment (max bound, or None for unbounded)

  • minus (float | None | Unspecified) – Relative negative increment (min bound, or None for unbounded), If this argument is unspecified, the range will be symmetric.

>>> # Create a resistor with ±5% tolerance
>>> r1 = Toleranced.percent(10_000, 5)  # 10kΩ ± 5%
>>> print(r1)
10000 ± 5%
>>> # Create a voltage with asymmetric bounds
>>> v1 = Toleranced.min_typ_max(2.7, 3.3, 3.6)  # 2.7V to 3.6V, typical 3.3V
>>> print(v1)
Toleranced(2.7 <= 3.3 <= 3.6)
>>> # Arithmetic with tolerances
>>> r2 = Toleranced.percent(1_000, 1)  # 1kΩ ± 1%
>>> total = r1 + r2
>>> print(f"Total: {total.min_value:.0f}Ω to {total.max_value:.0f}Ω")
Total: 10490Ω to 11510Ω
>>> # Voltage divider calculation
>>> v_out = v1 * r2 / (r1 + r2)
>>> print(v_out)
Toleranced(0.3, 0.0466158, 0.0677672)
typ: float#

The typical/nominal value.

plus: float | None#

Positive tolerance from typical to maximum value. None indicates unbounded maximum.

minus: float | None#

Negative tolerance from typical to minimum value. None indicates unbounded minimum.

property max_value: float#

The maximum value of the tolerance range (typ + plus).

property min_value: float#

The minimum value of the tolerance range (typ - minus).

center_value()[source]#

Calculate the geometric center of the range (midpoint between min and max).

Return type:

float

plus_percent()[source]#

Calculate the positive tolerance as a percentage of the typical value.

Return type:

float

Returns:

Percentage value (e.g., 5.0 for 5%).

Raises:

ValueError – If plus is None or typ is zero.

minus_percent()[source]#

Calculate the negative tolerance as a percentage of the typical value.

Return type:

float

Returns:

Percentage value (e.g., 5.0 for 5%).

Raises:

ValueError – If minus is None or typ is zero.

in_range(value)[source]#

Check if a value or range is contained within this tolerance range.

Parameters:

value (float | Toleranced) – A float or another Toleranced value to check.

Return type:

bool

Returns:

True if the value/range is completely within this range.

>>> tol = Toleranced(10, 1, 1)  # 9 to 11
>>> tol.in_range(10.5)
True
>>> tol.in_range(Toleranced(10, 0.5, 0.5))  # 9.5 to 10.5
True
range()[source]#

Calculate the total range (max - min).

Return type:

float

apply(f)[source]#

Apply a function to the toleranced value.

Applies the given function to min, typ, and max values and creates a new Toleranced from the results. Useful for non-linear transformations.

Parameters:

f (Callable[[float], float]) – A function that takes a float and returns a float.

Return type:

Self

Returns:

New Toleranced value with the function applied.

>>> import math
>>> v = Toleranced(4.0, 0.5, 0.5)  # 3.5 to 4.5
>>> sqrt_v = v.apply(math.sqrt)  # sqrt applied to range
>>> print(f"{sqrt_v.min_value:.2f} to {sqrt_v.max_value:.2f}")
1.87 to 2.12
classmethod min_typ_max(min_val, typ_val, max_val)[source]#

Create a Toleranced value from min, typ, and max values.

At least two of the three values must be specified. If typ is not provided, it will be calculated as the midpoint of min and max.

Parameters:
  • min_val (float | None) – Minimum value (or None if unbounded below).

  • typ_val (float | None) – Typical/nominal value (or None to use midpoint).

  • max_val (float | None) – Maximum value (or None if unbounded above).

Return type:

Self

Returns:

New Toleranced value.

Raises:

ValueError – If fewer than two values are specified, or if min > typ, typ > max, or min > max.

>>> # Supply voltage specification
>>> vdd = Toleranced.min_typ_max(2.7, 3.3, 3.6)
>>> print(vdd)
Toleranced(2.7 <= 3.3 <= 3.6)
>>> # Temperature range without typical
>>> temp = Toleranced.min_typ_max(-40, None, 85)
>>> print(f"Center temp: {temp.typ}°C")
Center temp: 22.5°C
classmethod min_max(min_val, max_val)[source]#

Create a Toleranced defined by absolute min and max values.

The typical value will be set to the midpoint of min and max.

Parameters:
  • min_val (float) – Minimum value.

  • max_val (float) – Maximum value.

Return type:

Self

Returns:

New Toleranced value.

>>> # Operating frequency range
>>> freq = Toleranced.min_max(10e6, 20e6)  # 10-20 MHz
>>> print(f"Center: {freq.typ/1e6} MHz")
Center: 15.0 MHz
classmethod min_typ(min_val, typ_val)[source]#

Create a Toleranced defined by an absolute minimum and typical value.

The maximum is unbounded (None).

Parameters:
  • min_val (float) – Minimum value.

  • typ_val (float) – Typical/nominal value.

Return type:

Self

Returns:

New Toleranced value with unbounded maximum.

>>> # Minimum load current
>>> i_load = Toleranced.min_typ(0.1, 0.5)  # At least 100mA, typ 500mA
classmethod typ_max(typ_val, max_val)[source]#

Create a Toleranced defined by a typical and absolute maximum value.

The minimum is unbounded (None).

Parameters:
  • typ_val (float) – Typical/nominal value.

  • max_val (float) – Maximum value.

Return type:

Self

Returns:

New Toleranced value with unbounded minimum.

>>> # Maximum current consumption
>>> i_max = Toleranced.typ_max(50e-6, 100e-6)  # Typ 50µA, max 100µA
classmethod percent(typ, plus, minus=Unspecified)[source]#

Create a Toleranced based on symmetric or asymmetric percentages of the typical value.

If the minus argument is unspecified, the range will be symmetric.

Parameters:
  • typ (float) – Typical/nominal value.

  • plus (float) – Positive tolerance as a percentage (0-100).

  • minus (float | Unspecified) – Negative tolerance as a percentage (0-100). If unspecified, uses the same value as plus.

Return type:

Self

Returns:

New Toleranced value.

Raises:

ValueError – If plus or minus is not in the range 0-100.

>>> # 10kΩ resistor with ±5% tolerance
>>> r1 = Toleranced.percent(10_000, 5)
>>> print(r1)
10000 ± 5%
>>> # Voltage with asymmetric tolerance
>>> v = Toleranced.percent(3.3, 10, 5)  # +10%, -5%
>>> print(f"{v.min_value}V to {v.max_value}V")
3.135V to 3.63V
classmethod sym(typ, plusminus)[source]#

Create a Toleranced with symmetric bounds.

Effectively an alias of the two-argument constructor.

Parameters:
  • typ (float) – Typical/nominal value.

  • plusminus (float) – Symmetric tolerance (both plus and minus).

Return type:

Self

Returns:

New Toleranced value with symmetric tolerance.

>>> # Component with ±0.1mm tolerance
>>> dim = Toleranced.sym(5.0, 0.1)  # 4.9 to 5.1 mm
classmethod exact(typ)[source]#

Create a Toleranced with zero tolerance (exact value).

Overloads:
Parameters:

typ (float | Toleranced)

Return type:

Self | Toleranced

If given a Toleranced value, returns it unchanged. If given a float, creates a Toleranced with plus=0 and minus=0.

Parameters:

typ (float | Toleranced) – Value to wrap as exact, or existing Toleranced.

Returns:

Toleranced value with zero tolerance, or the input if already Toleranced.

Return type:

Self | Toleranced

>>> # Ideal reference voltage (no tolerance)
>>> v_ref = Toleranced.exact(2.5)
>>> print(v_ref)
2.5 ± 0
type Point = tuple[float | int, float | int]#
class Transform(translate, rotate=0, scale=(1, 1))[source]#

Bases: object

Transform represents a translate * rotate * scale (TRS) transform in that order, so scale is applied first, then rotate, and finally translate. Note that non-unit scale will typically not carry over into component and circuit placement, and while it can be used to compute a placement before it’s applied, the results may be unexpected, and should be avoided. Also note that because the transforms are internally stored as decomposed values, a non-uniform scale cannot be applied to another transform, as this would result in a shear.

Constructing a transform directly is typically only needed in niche cases, and more often than not it is better to use member methods of various objects (in JITX typically called at()) to transform the object.

Supports the following operators:

  • t1 * t2 : Compose transforms. Matrix order (T1 * T2 applies T2 then T1).

  • t * point : Apply transform to a Point, Vec2D, or Shape.

  • t * layer : Apply transform to a layer index, Side, or LayerSet. A plain transform carries no side, so these are returned unchanged; see Placement.

  • ~t : Compute the inverse transform.

Parameters:
  • translate (Point) – Translation as (x, y).

  • rotate (float) – Optional rotation angle in degrees.

  • scale (float | tuple[float, float]) – Optional scale factors as (x, y). If a single value is provided, then the same value is used for both x and y.

>>> # Place a component at (10, 20) with 90° rotation
>>> xform = Transform((10, 20), rotate=90)
>>> # Use helper methods instead
>>> xform = Transform.translate(10, 20) * Transform.rotate(90)
>>> # Apply transform to a point
>>> point = (5, 0)
>>> new_point = xform * point
>>> print(new_point)
(10, 25)
>>> # Compose transforms
>>> t1 = Transform.translate(10, 0)
>>> t2 = Transform.rotate(90)
>>> combined = t1 * t2  # Rotate first, then translate
>>> # Transform a shape
>>> circle = Circle(radius=5).at(0, 0)
>>> moved_circle = t1 * circle
clone()[source]#

Create a copy of this transform.

Returns:

New Transform with identical translation, rotation, and scale.

property trs#

Get the transform components as a tuple (translation, rotation, scale).

property translation: Point#

The transform’s translation as (x, y).

property rotation: float#

The transform’s rotation angle in degrees.

inverse()[source]#

Compute the inverse transform.

The inverse transform undoes the effect of this transform. Applying a transform followed by its inverse returns the original value.

Returns:

New Transform that is the inverse of this transform.

>>> t = Transform.translate(10, 20) * Transform.rotate(45)
>>> t_inv = t.inverse()
>>> point = (5, 5)
>>> # Applying transform then inverse returns original
>>> result = t_inv * (t * point)
>>> # result ≈ (5, 5)
matrix2x3(*, row_major=False, flat=False)[source]#

Convert transform to a 2x3 affine transformation matrix.

Overloads:

Returns the matrix representation of this transform, which can be used with graphics libraries or other systems that expect matrix form.

Parameters:
  • row_major – If True, return in row-major order; otherwise column-major (default).

  • flat – If True, return as flat tuple; otherwise as nested tuples (default).

Returns:

Matrix in the requested format (nested tuples or flat tuple).

>>> t = Transform.translate(10, 5) * Transform.rotate(90)
>>> # Get column-major nested format (default)
>>> m = t.matrix2x3()
>>> # m = ((0, 1), (-1, 0), (10, 5))
>>> # Get row-major flat format
>>> m = t.matrix2x3(row_major=True, flat=True)
>>> # m = (0, -1, 10, 1, 0, 5)
matrix3x3(*, row_major=False, flat=False)[source]#

Convert transform to a 3x3 homogeneous transformation matrix.

Overloads:

Returns the matrix representation as a 3x3 homogeneous matrix with the bottom row as [0, 0, 1], suitable for use with homogeneous coordinates.

Parameters:
  • row_major – If True, return in row-major order; otherwise column-major (default).

  • flat – If True, return as flat tuple; otherwise as nested tuples (default).

Returns:

3x3 matrix in the requested format (nested tuples or flat tuple).

>>> t = Transform.translate(10, 5)
>>> m = t.matrix3x3()
>>> # Column-major: ((1, 0, 0), (0, 1, 0), (10, 5, 1))
classmethod translate(x, y=None, /)[source]#

Create a translation-only transform.

Overloads:
Parameters:
  • x (float | Point) – X translation or a (x, y) point.

  • y (float | None) – Y translation (not used if x is a point).

Returns:

New Transform with only translation (no rotation or scaling).

>>> # Translate by (10, 20)
>>> t = Transform.translate(10, 20)
>>> # Alternative using tuple
>>> t = Transform.translate((10, 20))
>>> # Use in component placement
>>> component.at(Transform.translate(5, 10))
classmethod rotate(angle)[source]#

Create a rotation-only transform.

Parameters:

angle (float) – Rotation angle in degrees (counter-clockwise).

Returns:

New Transform with only rotation (no translation or scaling).

>>> # Rotate 90 degrees counter-clockwise
>>> t = Transform.rotate(90)
>>> # Combine with translation
>>> t = Transform.translate(10, 0) * Transform.rotate(45)
classmethod scale(x, y=None, /)[source]#

Create a scale-only transform.

Overloads:
Parameters:
  • x (float) – X scale factor, or uniform scale if y is not provided.

  • y (float | None) – Y scale factor (optional, defaults to x for uniform scaling).

Returns:

New Transform with only scaling (no translation or rotation).

Note

Non-uniform scaling should be used with caution as it may not carry over properly to component placement.

>>> # Uniform scale by 2x
>>> t = Transform.scale(2)
>>> # Non-uniform scale
>>> t = Transform.scale(2, 1.5)  # 2x in X, 1.5x in Y
classmethod identity()[source]#

Create an identity transform (no transformation).

Returns:

New Transform that applies no transformation.

>>> t = Transform.identity()
>>> point = (5, 10)
>>> result = t * point
>>> # result == (5, 10)
class Via[source]#

Bases: Positionable, Ref

Via definition that can be instantiated in the board. Layer indexes referenced in this definition are absolute in the board: 0 is always the top layer. They are not relative to any component / circuit. Flipping via instances in the UI will not flip those layers, contrary to landpattern pads.

>>> class StandardVia(Via):
...     start_layer = Side.Top
...     stop_layer = Side.Bottom
...     diameter = 0.6
...     diameters = {0: 0.5, 1: ViaDiameter(0.5, nfp=0.2)}
...     hole_diameter = 0.3
...     type = ViaType.MechanicalDrill
type: ClassVar[ViaType]#

MechanicalDrill or LaserDrill.

Type:

Type of via drilling method

name: str | None = None#

Name of the via. If not specified, the name of the class will be used. This name must be unique.

start_layer: int#

Starting layer for the via. Setting this to a layer index other than the top layer allows for creating buried or blind vias.

stop_layer: int#

Ending layer for the via.

diameter: float | ViaDiameter#

Pad diameter of the via, in mm. Can be overridden on a per-layer basis by diameters.

diameters: Mapping[int | tuple[int, ...], float | ViaDiameter] = {}#

Pad diameters of the via for specific layers. Overrides diameter for the given layers.

Each key is a conductor layer index, or a tuple of indices that share one value. An index counts from 0 at the top layer, or from -1 at the bottom layer when negative, so on a 4-layer board 1 and -3 name the same layer. Every index must exist in the design’s stackup, and each layer may appear in only one key, in either form; translating the design raises an error otherwise. A value may be a ViaDiameter to set a separate pad diameter where non-functional pads are removed (see ViaDiameter.nfp).

>>> diameters = {0: 0.5, (1, 2): ViaDiameter(0.5, nfp=0.2), -1: 0.5}  # 4 layers
hole_diameter: float#

Drilled or laser-cut hole diameter for the via, in mm.

filled: bool = False#

Whether the via is filled.

tented: set[Side] | Side | None | bool = True#

Whether the via is tented on Top, Bottom, or both sides. Untented sides will have a solder mask opening.

via_in_pad: bool = False#

Whether the via is allowed to be placed inside a component’s pads.

backdrill: BackdrillSet | Backdrill | None = None#

Backdrill specifications. If a Backdrill is used, it will be assumed to be drilled from bottom.

A backdrilled via is drilled through to the backdrilled surface, while its pads still run only from start_layer to stop_layer. So stop_layer sets the depth of a bottom backdrill (the via connects down to that layer and the stub below it is drilled out), and for BackdrillSet(top=...) start_layer sets the depth of the top backdrill in the same way.

>>> class BackdrilledVia(Via):
...     type = ViaType.MechanicalDrill
...     start_layer = Side.Top
...     stop_layer = 2
...     diameter = 0.6
...     hole_diameter = 0.3
...     backdrill = BackdrillSet(
...         bottom=Backdrill(
...             diameter=0.5,
...             startpad_diameter=0.7,
...             solder_mask_opening=0.8,
...             copper_clearance=0.6,
...         )
...     )
models: Mapping[tuple[int, int], PinModel] = {}#

Specifies delay and loss models for the via, used by signal integrity constraints.

Each entry defines a model for a pair of layers. Layers are specified as layer indices. Models are assumed to be symmetric, so the order of layer indices is arbitrary. It is an error to specify multiple models for the same pair of layers.

It is recommended to not specify models with the same start and end layer. They will currently be ignored by the constraint solver (since path does not travel through the via) but this behavior may change in a future version of JITX. The models are given in terms of the same jitx.si.PinModel object used by components.

>>> class MyVia(Via):
>>>     # Other via parameters...
>>>     models = {
>>>         # Top to bottom layer (through-hole via)
>>>         (0, -1): PinModel(5e-12, 0.05),
>>>         # Top to inner layer 1 (blind via)
>>>         (0, 1): PinModel(2e-12, 0.02),
>>>         # Inner layer 1 to inner layer 2 (buried via)
>>>         (1, 2): PinModel(2e-12, 0.02),
>>>     }

Not all layer pairs need to be specified. If you know that, for example, all usages of a via will go between the top and bottom of the board, then only that model needs to be provided.

Via models can also be generated programmatically using loops. For example, to define models for all layer pairs in a multi-layer board where delay and loss scale linearly with the number of layers traversed:

>>> class MultiModelVia(Via):
>>>     # Other via parameters...
>>>
>>>     # Generate models for all layer pairs
>>>     total_layers = 4
>>>     models = {}
>>>     for i in range(total_layers):
>>>         for j in range(i + 1, total_layers):
>>>             # Model that scales with number of layers
>>>             n_layers = j - i
>>>             models[(i, j)] = PinModel(
>>>                 2e-12 * n_layers,
>>>                 0.05 * n_layers
>>>             )

When models are not provided for a via, placeholder models are automatically inserted. When using placeholder models (models with ideal delay and loss), any timing or loss constraints involving signals through these vias will be flagged as unsatisfied. This is because the placeholder model assumes some arbitrary transmission delay and loss values, which are not set by the user. For accurate signal integrity analysis, provide calculated, measured, or simulated via models for all layer pairs used in your design.

For maximum accuracy, it is recommended to simulate or measure each specific pair of layers rather than using a simplified linear model. The loop approach is most useful for initial designs or when detailed measurements are not yet available.

port = Port()#

Port for connectivity. It’s mainly used internally.

Subpackages#

Submodules#