Compare commits

..
133 changed files with 5602 additions and 28575 deletions

View file

@ -1,856 +0,0 @@
# Migration Guide
This guide covers changes between the `master` branch and the current tree.
Both `master` and the current tree report `masque.__version__ == '3.4'`; the
version string has not yet been bumped for these changes.
Most downstream changes are in `masque/builder/*`, but there are a few other
API changes that may require code updates.
## Routing API: renamed and consolidated
The routing helpers were consolidated into a single implementation in
`masque/builder/pather.py`.
The biggest migration point is that the old routing verbs were renamed:
| Old API | New API |
| --- | --- |
| `Pather.path(...)` | `Pather.trace(...)` |
| `Pather.path_to(...)` | `Pather.trace_to(...)` |
| `Pather.mpath(...)` | `Pather.trace(...)` / `Pather.trace_to(...)` with multiple ports |
| `Pather.pathS(...)` | `Pather.jog(...)` |
| `Pather.pathU(...)` | `Pather.uturn(...)` |
| `Pather.path_into(...)` | `Pather.trace_into(...)` |
| `Pather.path_from(src, dst)` | `Pather.at(src).trace_into(dst)` |
| `RenderPather.path(...)` | `Pather(..., render='deferred').trace(...)` |
| `RenderPather.path_to(...)` | `Pather(..., render='deferred').trace_to(...)` |
| `RenderPather.mpath(...)` | `Pather(..., render='deferred').trace(...)` / `Pather(..., render='deferred').trace_to(...)` |
| `RenderPather.pathS(...)` | `Pather(..., render='deferred').jog(...)` |
| `RenderPather.pathU(...)` | `Pather(..., render='deferred').uturn(...)` |
| `RenderPather.path_into(...)` | `Pather(..., render='deferred').trace_into(...)` |
| `RenderPather.path_from(src, dst)` | `Pather(..., render='deferred').at(src).trace_into(dst)` |
There are also new convenience wrappers:
- `straight(...)` for `trace_to(..., ccw=None, ...)`
- `ccw(...)` for `trace_to(..., ccw=True, ...)`
- `cw(...)` for `trace_to(..., ccw=False, ...)`
- `jog(...)` for S-bends
- `uturn(...)` for U-bends
Important: `Pather.path()` is no longer the routing API. It now forwards to
`Pattern.path()` and creates a geometric `Path` element. Any old routing code
that still calls `pather.path(...)` must be renamed.
### Common rewrites
```python
# old
pather.path('VCC', False, 6_000)
pather.path_to('VCC', None, x=0)
pather.mpath(['GND', 'VCC'], True, xmax=-10_000, spacing=5_000)
pather.pathS('VCC', offset=-2_000, length=8_000)
pather.pathU('VCC', offset=4_000, length=5_000)
pather.path_into('src', 'dst')
pather.path_from('src', 'dst')
# new
pather.cw('VCC', 6_000)
pather.straight('VCC', x=0)
pather.ccw(['GND', 'VCC'], xmax=-10_000, spacing=5_000)
pather.jog('VCC', offset=-2_000, length=8_000)
pather.uturn('VCC', offset=4_000, length=5_000)
pather.trace_into('src', 'dst')
pather.at('src').trace_into('dst')
```
If you prefer the more explicit spelling, `trace(...)` and `trace_to(...)`
remain the underlying primitives:
```python
pather.trace('VCC', False, 6_000)
pather.trace_to('VCC', None, x=0)
```
## `PortPather` and `.at(...)`
Routing can now be written in a fluent style via `.at(...)`, which returns a
`PortPather`.
```python
(rpather.at('VCC')
.trace(False, length=6_000)
.trace_to(None, x=0)
)
```
This is additive, not required for migration. Existing code can stay with the
non-fluent `Pather` methods after renaming the verbs above.
Old `PortPather` helper names were also cleaned up:
| Old API | New API |
| --- | --- |
| `save_copy(...)` | `mark(...)` |
| `rename_to(...)` | `rename(...)` |
Example:
```python
# old
pp.save_copy('branch')
pp.rename_to('feed')
# new
pp.mark('branch')
pp.rename('feed')
```
## Imports and module layout
`Pather` now provides the remaining builder/routing surface in
`masque/builder/pather.py`. The old module files
`masque/builder/builder.py` and `masque/builder/renderpather.py` were removed.
Update imports like this:
```python
# old
from masque.builder.builder import Builder
from masque.builder.renderpather import RenderPather
# new
from masque.builder import Pather
builder = Pather(...)
deferred = Pather(..., render='deferred')
```
The new `Pather` remains importable from both `masque` and `masque.builder`.
The removed `Builder` and `RenderPather` names are no longer exported from
either location.
`Pather` now defaults to `render='auto'`, so plain construction replaces the
old `Builder` behavior. Use `Pather(..., render='deferred')` where you
previously used `RenderPather`.
## `SimpleTool` was removed and `AutoTool` registration changed
`SimpleTool` is no longer exported. `AutoTool` remains, but its old public
descriptor classes and constructor-oriented configuration were replaced by
registration methods. Use it for generated straights and S-bends and reusable
bends, U-turns, and transitions.
### Old `AutoTool`
```python
from masque.builder import AutoTool
tool = AutoTool(
straights=[
AutoTool.Straight('m1wire', make_straight, 'input', 'output'),
],
bends=[
AutoTool.Bend(lib.abstract('bend'), 'input', 'output'),
],
sbends=[],
transitions={
('m2wire', 'm1wire'): AutoTool.Transition(
lib.abstract('via'), 'top', 'bottom'
),
},
default_out_ptype='m1wire',
)
```
### New `AutoTool`
```python
from masque.builder import AutoTool
tool = (
AutoTool()
.add_straight(make_straight, 'm1wire', 'input')
.add_bend(lib.abstract('bend'), 'input', 'output', clockwise=True)
.add_transition(lib.abstract('via'), 'top', 'bottom')
)
```
The key differences are:
- `SimpleTool` was removed; use `AutoTool` or implement the new `Tool`
primitive-offer interface
- `AutoTool.Straight(...)` -> `add_straight(fn, ptype, in_name)`
- `AutoTool.Bend(...)` -> `add_bend(abstract, in_name, out_name)`
- `AutoTool.SBend(...)` -> `add_sbend(fn, ptype, in_name, out_name)`
- reusable native U-turns can be registered with `add_uturn(...)`
- transitions are registered with `add_transition(abstract, external_port, internal_port)`
- transitions are bidirectional by default; pass `one_way=True` to inhibit the reverse adapter
Primitive costs are now explicit and independent of `AutoTool` registration
order. Every `add_*()` method accepts `cost=`, as do the concrete offer
factories. A numeric value scales the default geometric cost; for example,
`cost=2` makes a primitive twice as expensive. A callable receives the
canonical primitive parameter and local endpoint and returns the complete
cost:
```python
tool.add_straight(make_straight, 'm1wire', 'input', cost=1.5)
tool.add_sbend(
make_sbend,
'm1wire',
'input',
'output',
cost=lambda jog, endpoint: abs(jog) + 2 * abs(endpoint.x),
)
```
`PrimitiveOffer.priority_bias` was removed; custom offers should use `cost`
instead. Exact equal-cost candidates still use deterministic discovery order
as the final tie-break, but registration order no longer changes their
reported cost.
For two-port primitives, `AutoTool` can infer omitted port names and, for
generated straight/S-bend primitives, omitted ptype metadata by sampling an
in-domain example. Supply those values explicitly when generation requires
route-specific keyword arguments, because metadata inference does not receive
`tool_options`.
## Custom `Tool` subclasses
If you maintain your own `Tool` subclass, the interface changed:
- `primitive_offers()` is now the planning boundary
- `render()` consumes committed primitive render tokens
- `Tool.path(...)`, `traceL()`, `traceS()`, `traceU()`, `planL()`,
`planS()`, and `planU()` are no longer part of the public `Tool` API
In practice, a minimal old implementation like:
```python
class MyTool(Tool):
def path(self, ccw, length, **kwargs):
...
```
should now become:
```python
from collections.abc import Sequence
from typing import Any
from masque import Port
from masque.builder import RenderStep, StraightOffer, Tool
class MyTool(Tool):
def primitive_offers(self, kind, *, in_ptype=None, out_ptype=None, **kwargs):
if kind != 'straight':
return ()
def endpoint(length):
ptype = out_ptype or in_ptype
return Port((length, 0), rotation=3.141592653589793, ptype=ptype)
def commit(length):
return {'length': length}
return (StraightOffer(
in_ptype=in_ptype,
out_ptype=out_ptype or in_ptype,
endpoint_planner=endpoint,
commit_planner=commit,
),)
def render(self, batch: Sequence[RenderStep]):
...
```
If a tool does not provide a primitive kind, return `()` for that kind. `Pather`
will compose available primitive offers where the route family allows it.
### Primitive offers
Tools describe legal routing primitives through `Tool.primitive_offers()`.
`Pather` composes those primitive offers to implement `trace()`, `jog()`,
`uturn()`, and `trace_into()`.
For custom tools, construct the concrete offer class that matches the primitive
you are exposing:
- `StraightOffer` for non-turning length-parameterized primitives
- `BendOffer` for single-turn length-parameterized primitives
- `SOffer` for S-like jog-parameterized primitives
- `UOffer` for U-like jog-parameterized primitives
`PrimitiveOffer` is the shared base type used for generic annotations and
common callback behavior. It is not the normal class users should instantiate.
The concrete offer classes carry the semantic fields (`length_domain`,
`jog_domain`, `ccw`) so tools do not need to encode primitive identity in
strings. Each concrete offer now also exposes a class-level canonical `kind`.
Tools must return the matching offer kind for the discovery query; for example,
`primitive_offers('s', ...)` must return only `SOffer` instances. Mismatches are
reported as fatal `ToolContractError`s rather than silently ignored.
`RenderStep` now stores that same canonical kind. Code that constructs render
steps directly must use the kind rather than a legacy opcode:
```python
# old
RenderStep('L', tool, start, end, data)
# new
RenderStep('straight', tool, start, end, data)
```
Use `'bend'`, `'s'`, `'u'`, or `'plug'` for the other step types. The read-only
`RenderStep.opcode` and `PrimitiveOffer.opcode` properties remain available for
code that only consumes steps, but opcodes are now derived rather than stored.
Minimal straight-only example:
```python
from collections.abc import Sequence
from typing import Literal
from masque import Port
from masque.builder import RenderStep, StraightOffer, Tool
class MyTool(Tool):
def primitive_offers(
self,
kind: Literal['straight', 'bend', 's', 'u'],
*,
in_ptype=None,
out_ptype=None,
**kwargs,
):
if kind != 'straight':
return ()
def endpoint(length):
ptype = out_ptype or in_ptype
return Port((length, 0), rotation=3.141592653589793, ptype=ptype)
def commit(length):
return {'length': length}
return (StraightOffer(
in_ptype=in_ptype,
out_ptype=out_ptype or in_ptype,
endpoint_planner=endpoint,
commit_planner=commit,
),)
def render(self, batch: Sequence[RenderStep]):
...
```
Routing entry points now name every supported route argument explicitly.
Custom per-route Tool values must be placed under `tool_options`:
```python
pather.jog('A', 4, length=10, tool_options={'process_corner': 'slow'})
```
The mapping is unpacked only for `Tool.primitive_offers()`. Route arguments do
not leak into that namespace, and tool options are not forwarded to
`Tool.render()`. An offer that needs route-specific render behavior must capture
the selected value in its `commit()` result (`RenderStep.data`). `AutoTool`
does this automatically for generated straight and S-bend primitives: the
mapping is deep-copied per offer discovery and passed to its generator as
keyword arguments during rendering. Consequently every AutoTool option value
must be deep-copyable, and later mutation of nested caller-owned values does
not affect a pending route. AutoTool options must not change generated
ports or endpoint geometry. `PathTool` defines no tool options and rejects
nonempty mappings.
AutoTool does not validate generator keyword signatures during planning. A bad
keyword therefore raises when the generator runs, normally during rendering.
Generators that require route options must provide explicit port metadata at
registration; S-bend generators must also provide an explicit `endpoint`.
Primitive offers are local planning objects:
- `endpoint_at(parameter)` returns the local output `Port`
- `cost_at(parameter)` returns an additive scalar route-selection cost
- `bbox_at(parameter)` returns local primitive bounds when a footprint hook is supplied
- `parameterized_bbox` may carry opaque future-router footprint metadata
- `commit(parameter)` returns opaque render data consumed later by `render()`
- `(min, max)` parameter domains are half-open; `(value, value)` is a fixed singleton
- domains are validated when an offer is constructed, not when it is first evaluated
- selected parameter values must be finite; domains may use infinite open bounds but not `NaN`
- straight/bend domains require a finite nonnegative minimum; fixed singleton domains must be finite
- `None` and `"unk"` ptypes are wildcards; concrete ptype mismatches reject an offer
`AutoTool.add_straight(length_range=...)` and
`AutoTool.add_sbend(jog_range=...)` now validate their ranges before metadata
inference. `jog_range` is an absolute-magnitude range and must have a finite,
nonnegative lower bound; AutoTool creates the corresponding positive and
negative S offers itself. Invalid ranges now raise immediately instead of
registering no offers.
`ToolContractError` is exported from `masque` and `masque.builder`. It marks a
broken Tool contract—such as an endpoint ptype that disagrees with its offer,
an invalid evaluated cost, or rendered output that disagrees with the planned
endpoint—and is fatal to route fallback. Ordinary `BuildError` raised by a
planning callback remains a recoverable candidate rejection. Rendered output
rotations are compared modulo one full turn; a port facing exactly backward is
no longer accepted as equivalent. A `None` rotation remains an explicit
wildcard.
Custom Tool authors can exercise discovery, offer callbacks, committed data,
and one-step rendering without depending on pytest:
```python
from masque.builder import ToolContractCase, validate_tool_contract
validate_tool_contract(my_tool, (
ToolContractCase('straight', in_ptype='wire', probe_parameters=(10,)),
ToolContractCase('bend', in_ptype='wire', ccw=False),
ToolContractCase('bend', in_ptype='wire', ccw=True),
ToolContractCase('s', in_ptype='wire', require_offers=False),
))
```
Cases derive representative parameters from each returned offer domain and
may add explicit probes. Empty discovery is an error unless
`require_offers=False`; bbox support is required only with `check_bbox=True`.
Validation returns normally on success and otherwise raises an
`ExceptionGroup` of contextual `ToolContractError`s.
Run this validation during Tool development, testing, or application startup.
It is the comprehensive semantic preflight for custom Tools; those checks are
intentionally not repeated for every offer evaluation in the routing hot path.
Positional routing bounds (`p`, `pos`, `position`, `x`, and `y`) now require a
nearly Manhattan input-port direction. Arbitrarily angled ports remain valid
for non-positional/extension routing.
Heterogeneous `StraightOffer` and `SOffer` objects may be used as ptype
adapters. Requested `out_ptype` constrains only the final route endpoint; any
intermediate ptypes are chosen by the route solver.
`Tool` subclasses must override `primitive_offers()` and return `()` themselves
for recognized unsupported kinds. There is no route-level `plan*()` fallback.
Omitted-length S/U behavior comes from direct `SOffer` and `UOffer` endpoint
domains or from composed straight/bend primitives.
Offer constructors accept split `endpoint_planner` and `commit_planner`
callbacks. Provide both callbacks or override the offer methods in a subclass;
partial callback configurations are rejected during offer construction.
When writing direct primitive offers, declare the actual endpoint ptype
produced by the offer if it can differ from the requested value; `Pather`
validates evaluated endpoints against the declared offer ptype.
Stable imports for custom tool authors live in `masque.builder`. The
`masque.builder.planner` module is an internal planner implementation; do not
import it from user code.
`trace_into()` uses the same primitive-offer route selection and defaults to
the minimal main-route bend count required by the endpoint relationship: zero
for a straight, one for a quarter-turn, and two for S- and U-like connections.
Ptype adapters do not consume this bend budget. Set
`plan_options={'bend_policy': 'flexible'}` to search bounded route topologies
with up to four bend roles, including dogleg and loop-like fallbacks.
Bend-family requests then search one-bend routes before three-bend routes;
other families search zero-to-two-bend routes before four-bend routes. The
first band with a legal route wins. Within that band, candidates are ordered
by total primitive-offer cost, adapter count, step count, and deterministic
discovery order. The default planner's `strategy` option affects only that
final discovery-order tie-break and is also supplied through `plan_options`.
`plan_options` is reserved for planner-specific per-route policy, while
`tool_options` is forwarded only to `Tool.primitive_offers()`. For example:
```python
pather.jog('A', 4, length=10, plan_options={'strategy': 'turn_first'})
```
Explicit-length `jog()` routes may also be satisfied by composing a straight
primitive before or after an omitted-length native S primitive. `uturn()` routes
may compose a straight primitive before an omitted-length native U primitive.
These compositions are used when they are the lowest-cost legal route for the
explicit request.
`AutoTool` can attach `bbox_at()` hooks to its primitive offers by rendering the
selected primitive into a temporary pattern and measuring it. If the rendered
primitive contains reusable refs, pass the source library as `bbox_library=...`;
normal routing does not require this.
### Omitted-length routing
Single-port omitted-length calls now evaluate legal primitive routes at their
minimum legal length-like parameter, or at their intrinsic endpoint length when
the requested offset fixes the primitive geometry. Cost then selects among
those minimum-length candidates:
```python
pather.trace('A', None) # minimum straight-like route
pather.jog('A', offset=2) # minimum S-like route for that offset
pather.uturn('A', offset=4) # minimum U-like route for that offset
```
For U-turns, use explicit `length=0` to request the old zero-public-length
shape:
```python
pather.uturn('A', offset=4, length=0)
```
## Transform semantics changed
The other major user-visible change is that `mirror()` and `rotate()` are now
treated more consistently as intrinsic transforms on low-level objects.
The practical migration rule is:
- use `mirror()` / `rotate()` when you want to change the object relative to its
own origin
- use `flip_across(...)`, `rotate_around(...)`, or container-level transforms
when you want to move the object in its parent coordinate system
### Example: `Port`
Old behavior:
```python
port.mirror(0) # changed both offset and orientation
```
New behavior:
```python
port.mirror(0) # changes orientation only
port.flip_across(axis=0) # old "mirror in the parent pattern" behavior
```
### What to audit
Check code that calls:
- `Port.mirror(...)`
- `Ref.rotate(...)`
- `Ref.mirror(...)`
- `Label.rotate_around(...)` / `Label.mirror(...)`
- `Abstract.mirror_port_offsets(...)` / `Abstract.mirror_ports(...)`
If that code expected offsets or repetition grids to move automatically, it
needs updating. For whole-pattern transforms, prefer calling `Pattern.mirror()`
or `Pattern.rotate_around(...)` at the container level.
`Abstract.mirror_port_offsets()` and `Abstract.mirror_ports()` were removed.
Use `Abstract.mirror(axis)` to mirror both port locations and orientations. If
you intentionally need only one half of that operation, update the individual
ports explicitly with `Port.flip_across(...)` or `Port.mirror(...)`.
## Library hierarchy and graph behavior
`masque/library.py` was split into the `masque.library` package. Imports from
the public module remain stable:
```python
from masque import Library, LazyLibrary
# or
from masque.library import Library, LazyLibrary
```
Code importing the implementation file itself must move to the public package;
do not depend on the new internal `base`, `mapping`, or `lazy` module paths.
Hierarchy helpers now handle dangling references explicitly. The following
methods accept `dangling='error' | 'ignore' | 'include'` and default to
`'error'`:
- `child_graph()`
- `parent_graph()`
- `child_order()`
- `find_refs_local()`
- `find_refs_global()`
- `prune_empty()`
On `master`, graph construction could expose missing targets implicitly or
fail later with a `KeyError`. If dangling refs are intentional, choose the
behavior explicitly, for example:
```python
graph = library.child_graph(dangling='include')
order = library.child_order(dangling='ignore')
```
Graph cycles and invalid hierarchy states are now reported as `LibraryError`
with context. Audit code that caught `KeyError` or `graphlib.CycleError` from
these helpers.
Invalid `dangling=` strings now raise `ValueError`; they no longer fall through
to the `include` behavior. Empty lists stored in `Pattern.refs` are consistently
treated as absent references by hierarchy and geometry traversal. Code that
uses a `defaultdict` lookup such as `pattern.refs[name]` without appending a
`Ref` will therefore not create an edge or force that target to be loaded.
`Library.add()` now resolves the full name plan and remaps references before it
starts inserting cells. Name-resolution and preparation failures no longer
leave partially-added cells behind. A `rename_theirs` callback now receives an
`INameView` containing both existing names and names reserved earlier in the
same addition. Use membership, iteration, `len()`, or `get_name()`; the callback
argument is not the destination object and does not support pattern lookup or
mapping helpers such as `keys()` and `items()`. Update callback annotations from
`ILibraryView` to `INameView`. Custom `_merge()` implementations remain
responsible for their own rollback if they fail during the final commit.
Reference transforms returned by `find_refs_local()` and
`find_refs_global()` are now Nx5 arrays. The fifth column is the cumulative
scale, so rows have the form `(x, y, rotation, mirrored, scale)` rather than the
old Nx4 form.
`BuildReport` mapping fields are now defensively copied and read-only. Copy a
field to a new `dict` before adding or removing report entries.
`PortLoadView`, `LayerMappedView`, `OverlayLibrary`, and source-backed outputs
returned by `LibraryBuilder.build()` borrow their sources. They do not close
source resources, and the views are not context managers. Keep each lazy
source open and unchanged until every borrowing view or overlay is finished,
then close the owning source explicitly. An eager `build(output='library')`
result is detached and does not need its sources afterward.
Lazy GDS sources no longer provide `with_ports_from_data()` or
`with_port_overrides()` convenience methods. Construct the generic view
directly instead: `PortLoadView(source, layers=...)` imports port data, and
`PortLoadView(source, ports=..., replace=...)` applies explicit overrides.
`LayerMappedView(source, map_layer)` lazily remaps shape and label layers while
leaving the source untouched. Its default `copy_through=False` forces mapped
serialization of every cell. Set `copy_through=True` only when source-aware
writers may copy untouched cells unchanged and intentionally skip their layer
mapping; persistently accessed cells are mapped and no longer copied through.
`preflight_source_aware(...)` preserves that per-cell provenance. It returns a
borrowing `OverlayLibrary`, skips source-backed cells completely, and applies
pattern sorting, named-layer validation, safe empty-cell pruning, and
repeated-shape wrapping only to cells without reusable source provenance.
Library name order is retained because sorting source-backed cells would
require loading them. Always use the returned overlay for writing, and keep the
original lazy source open until the write finishes. The comprehensive
`preflight(...)` operation continues to materialize every cell when sorting is
enabled.
Generic borrowing views no longer expose GDS-specific `raw_struct_bytes()`,
`can_copy_raw_struct()`, or forwarded `library_info` attributes. Keep the
owning GDS source or the metadata returned by `readfile()` when direct access is
needed. `IBorrowing.source_cell()` now provides format-neutral per-cell
provenance; GDS writers use it internally to preserve safe raw copy-through.
Read-only `subtree()` results are now borrowed lazy views rather than eager
`LibraryView` snapshots. Creating one no longer loads its reachable patterns,
and the view preserves source ordering, hierarchy metadata, and lazy GDS
copy-through. Mutable `Library`, `LazyLibrary`, and `OverlayLibrary` subtrees
return the same writable type as their source. Overlay subtrees retain their
source layers and lazy GDS capabilities. Mutable subtree containers are
structurally independent, but already-materialized patterns remain shared.
Keep borrowed sources open and structurally unchanged for the subtree's
lifetime.
`ILibrary` no longer inherits `collections.abc.MutableMapping`. It remains a
readable `Mapping` with explicit insert-only item assignment and deletion, but
generic mutation helpers such as `update()`, `setdefault()`, `pop()`,
`popitem()`, and `clear()` are no longer supplied. Use `add()`, `rename()`,
`delete()`, item insertion, and item deletion so library name and reference
invariants remain explicit.
Library-level `referenced_patterns()` and `dangling_refs()` now report only
named cell targets and return `set[str]`. Populated refs whose target is `None`
are ignored, matching `child_graph()` and recursive geometry behavior;
`Pattern.referenced_patterns()` continues to report `None` locally.
Port-importing views now always process detached patterns, including when the
raw source cell was already cached. Code can safely retain and compare raw and
processed views without port overrides leaking back into the raw pattern.
Once a processed cell is persistently materialized, lazy GDS writers no longer
copy the raw source structure for that cell, so later mutations to the returned
`Pattern` are serialized. Non-persistent materialization does not mark the cell
as changed.
Underscore-prefixed declarations work through the attribute authoring surface:
`builder.cells._helper = pattern` now declares `_helper`. Only the view's exact
internal `_library` attribute is reserved.
Recursive geometry operations now reject cyclic reference hierarchies with a
contextual `PatternError` instead of eventually leaking `RecursionError`. This
applies to bounds calculation, flattened layer polygon extraction, and
visualization as well as the existing flattening checks.
`LibraryBuilder.validate(names=...)` now accepts either one string or a sequence
of strings. Non-string roots raise `TypeError`, and duplicate roots are reduced
to their first occurrence. A recipe may build a different `LibraryBuilder`, but
calling `build()` or `validate()` recursively on its own active builder now
raises `BuildError` before starting another session.
`LibraryBuilder` is an authoring registry, not an `ILibraryView` or mapping.
Use membership, iteration, `keys()`, `get_name()`, assignment, and deletion to
manage declarations, then use the library returned by `build()` for reads and
hierarchy operations. Recipes that need an active library must receive the
builder-owned placeholder as a direct argument:
```python
def make_top(lib: ILibrary) -> Pattern:
return Pather(library=lib, ports='device').pattern
builder.cells.top = cell(make_top)(builder.library)
builder.cells.device = cell(factory)(hole_lib=builder.library)
```
The builder-owned `builder.library` placeholder is read-only. Only direct
positional and keyword values equal to it are substituted; placeholders nested
inside containers are not interpreted. A placeholder from another builder is
rejected when the recipe is assigned.
`IMaterializable` now identifies libraries which support explicit
`materialize()` and `materialize_many()` operations. `LibraryBuilder.add()`
borrows these marked inputs, while ordinary mappings and `ILibraryView`
instances are copied eagerly. Use `add_source()` to force borrowing of an
unmarked view. Wrapping a materializable library in `LibraryView` intentionally
erases the marker.
`IBorrowing` separately identifies composite views which retain direct source
libraries and expose them through `borrowed_sources()`. Keep those sources open
and unchanged for the lifetime of the borrowing view. Owner libraries such as
`LazyLibrary` and the lazy GDS readers are materializable but do not implement
`IBorrowing`. Borrowing views may expose unchanged per-cell layout provenance
through `source_cell()`; format writers decide whether that provenance permits
raw copy-through. Raw GDS structure access remains confined to GDS sources and
writers.
`LibraryBuilder`, `OverlayLibrary`, `PortLoadView`, and `LayerMappedView` are new
additive library implementations. `LibraryBuilder` supports declarative `@cell`
recipes and dependency-aware builds; `OverlayLibrary` composes source libraries
without eagerly copying all patterns; `PortLoadView` loads port metadata from
labels and/or explicit mappings; `LayerMappedView` remaps shape and label layers
on detached materialization.
Flattening with `flatten_ports=True` now rejects repeated refs whose target has
ports, because expanding them would create duplicate port names. Resolve the
repetition and assign unique port names before flattening, or use
`flatten_ports=False`.
## GDSII module and lazy-loading changes
`masque.file.gdsii` changed from a module into a package. The eager klamath
API remains available at the old import path, so ordinary `read`, `readfile`,
`write`, and `writefile` calls do not need to change:
```python
from masque.file import gdsii
library, info = gdsii.readfile('layout.gds')
```
The old `gdsii.load_library()` and `gdsii.load_libraryfile()` entry points were
removed. Use the source-backed lazy reader instead:
```python
# old
library, info = gdsii.load_libraryfile('layout.gds')
# new
from masque.file.gdsii import lazy
library, info = lazy.readfile('layout.gds')
try:
pattern = library['TOP']
finally:
library.close()
```
`lazy.read(stream)` and `lazy.readfile(path, use_mmap=...)` return a read-only
`GdsLibrarySource`. It owns file resources when it opens them and also supports
the context-manager protocol. The old `full_load` and `postprocess` arguments
are gone; materialize/copy the desired cells and post-process them explicitly.
An optional Arrow/native backend is available through
`masque.file.gdsii.arrow` and `masque.file.gdsii.lazy_arrow`; install the new
`arrow` extra to use it. These modules are additive and are not a transparent
replacement unless their additional dependencies and native library are
available.
GDS writing now has one entry point for eager and lazy libraries. Use
`masque.file.gdsii.write()` or `masque.file.gdsii.writefile()` regardless of
which reader produced the library. The `lazy` and `lazy_arrow` modules no
longer re-export writer functions. Source-backed libraries continue to infer
their header metadata and copy untouched structures directly.
## Shape construction and geometry additions
The public `raw=True` constructor shortcut was removed from `Arc`, `Circle`,
`Ellipse`, `Path`, `Polygon`, `PolyCollection`, and `Text`. Call their normal
constructors without `raw`; `_from_raw()` is an internal fast path and is not a
compatibility API.
```python
# old
polygon = Polygon(vertices, raw=True)
# new
polygon = Polygon(vertices)
```
`Arc` radii must now be strictly positive rather than merely non-negative.
`Arc.angle_ref` is additive and defaults to `Arc.AngleRef.Center`, preserving
the previous center-referenced angle interpretation.
`RectCollection` is a new shape for batches of axis-aligned rectangles and is
exported from both `masque` and `masque.shapes`. `Polygon.boolean()` and the
top-level `masque.boolean()` helper are also new; install the `boolean` extra
for their `pyclipper` dependency.
## Other user-facing changes
### File writers
SVG writing no longer polygonizes or flattens caller-owned patterns in place;
it works from detached copies. `svg.writefile(..., annotate_ports=True)` can
add port arrows. DXF writing now expands shape repetitions into individual DXF
entities, so callers no longer need to wrap repeated shapes solely for DXF
output.
### DXF environments
If you install the DXF extra, the supported `ezdxf` baseline moved from
`~=1.0.2` to `~=1.4`. Any pinned environments should be updated accordingly.
### Optional dependency names
The misspelled `manhatanize_slow` extra was corrected to
`manhattanize_slow`. A separate `manhattanize` extra now installs the
scikit-image implementation. The `arrow` and `boolean` extras are also new.
### New exports
These are additive, but available now from `masque` and `masque.builder`:
- from `masque`: `RectCollection`, `boolean`, `OverlayLibrary`,
`PortLoadView`, `LayerMappedView`, `IMaterializable`, `IBorrowing`, `LibraryBuilder`,
`BuildReport`, `CellProvenance`, and `cell`
- from `masque.builder`: `CostCallable`, `RenderStepKind`, the concrete
primitive-offer classes, structured route error/status types,
`ToolContractCase`, and `validate_tool_contract`
## Minimal migration checklist
If your code uses the routing stack, do these first:
1. Replace `path`/`path_to`/`mpath`/`path_into` calls with
`trace`/`trace_to`/multi-port `trace`/`trace_into`.
2. Replace `SimpleTool` and old `AutoTool` descriptor construction with the
new `AutoTool.add_*()` methods.
3. Fix imports that still reference `masque.builder.builder` or
`masque.builder.renderpather`.
4. Audit any low-level `mirror()` usage, especially on `Port` and `Ref`.
5. Move lazy GDS calls from `gdsii.load_library*()` to
`masque.file.gdsii.lazy`.
6. Remove `raw=True` from public shape constructors.
If your code only uses `Pattern`, `Library`, `place()`, and `plug()` without the
routing helpers, audit transforms, dangling-reference graph calls, raw shape
construction, and any stale imports.

View file

@ -145,7 +145,7 @@ References are accomplished by listing the target's name, not its `Pattern` obje
in order to create a reference, but they also need to access the pattern's ports. in order to create a reference, but they also need to access the pattern's ports.
* One way to provide this data is through an `Abstract`, generated via * One way to provide this data is through an `Abstract`, generated via
`Library.abstract()` or through a `Library.abstract_view()`. `Library.abstract()` or through a `Library.abstract_view()`.
* Another way is use `Pather.place()` or `Pather.plug()`, which automatically creates * Another way is use `Builder.place()` or `Builder.plug()`, which automatically creates
an `Abstract` from its internally-referenced `Library`. an `Abstract` from its internally-referenced `Library`.
@ -193,8 +193,8 @@ my_pattern.ref(new_name, ...) # instantiate the cell
# In practice, you may do lots of # In practice, you may do lots of
my_pattern.ref(lib << make_tree(...), ...) my_pattern.ref(lib << make_tree(...), ...)
# With a `Pather` and `place()`/`plug()` the `lib <<` portion can be implicit: # With a `Builder` and `place()`/`plug()` the `lib <<` portion can be implicit:
my_builder = Pather(library=lib, ...) my_builder = Builder(library=lib, ...)
... ...
my_builder.place(make_tree(...)) my_builder.place(make_tree(...))
``` ```
@ -275,6 +275,14 @@ my_pattern.ref(_make_my_subpattern(), offset=..., ...)
``` ```
## Development ## TODO
Project-level planned work is tracked in [TODO.md](TODO.md). * Rework naming/args for path-related (Builder, PortPather, path/pathL/pathS/pathU, path_to, mpath)
* PolyCollection & arrow-based read/write
* pather and renderpather examples, including .at() (PortPather)
* Bus-to-bus connections?
* Tests tests tests
* Better interface for polygon operations (e.g. with `pyclipper`)
- de-embedding
- boolean ops
* tuple / string layer auto-translation

View file

@ -1,131 +0,0 @@
from __future__ import annotations
import argparse
import importlib
import json
import time
from pathlib import Path
from typing import Any
from masque import LibraryError
READERS: dict[str, tuple[str, tuple[str, ...]]] = {
'gdsii': ('masque.file.gdsii', ('readfile',)),
'gdsii_arrow': ('masque.file.gdsii.arrow', ('readfile', 'arrow_import', 'arrow_convert')),
}
def _summarize_library(path: Path, elapsed_s: float, info: dict[str, object], lib: object) -> dict[str, object]:
assert hasattr(lib, '__len__')
assert hasattr(lib, 'tops')
tops = lib.tops() # type: ignore[no-any-return, attr-defined]
try:
unique_top = lib.top() # type: ignore[no-any-return, attr-defined]
except LibraryError:
unique_top = None
return {
'path': str(path),
'elapsed_s': elapsed_s,
'library_name': info['name'],
'cell_count': len(lib), # type: ignore[arg-type]
'topcells': tops,
'topcell': unique_top,
}
def _summarize_arrow_import(path: Path, elapsed_s: float, arrow_arr: Any) -> dict[str, object]:
libarr = arrow_arr[0]
return {
'path': str(path),
'elapsed_s': elapsed_s,
'arrow_rows': len(arrow_arr),
'library_name': libarr['lib_name'].as_py(),
'cell_count': len(libarr['cells']),
'layer_count': len(libarr['layers']),
}
def _profile_stage(module: Any, stage: str, path: Path) -> dict[str, object]:
start = time.perf_counter()
if stage == 'readfile':
lib, info = module.readfile(path)
elapsed_s = time.perf_counter() - start
return _summarize_library(path, elapsed_s, info, lib)
if stage == 'arrow_import':
if hasattr(module, 'readfile_arrow'):
libarr, _info = module.readfile_arrow(path)
elapsed_s = time.perf_counter() - start
return {
'path': str(path),
'elapsed_s': elapsed_s,
'arrow_rows': 1,
'library_name': libarr['lib_name'].as_py(),
'cell_count': len(libarr['cells']),
'layer_count': len(libarr['layers']),
}
arrow_arr = module._read_to_arrow(path)
elapsed_s = time.perf_counter() - start
return _summarize_arrow_import(path, elapsed_s, arrow_arr)
if stage == 'arrow_convert':
arrow_arr = module._read_to_arrow(path)
libarr = arrow_arr[0]
start = time.perf_counter()
lib, info = module.read_arrow(libarr)
elapsed_s = time.perf_counter() - start
return _summarize_library(path, elapsed_s, info, lib)
raise ValueError(f'Unsupported stage {stage!r}')
def build_arg_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description='Profile GDS readers with a stable end-to-end workload.')
parser.add_argument('--reader', choices=sorted(READERS), required=True)
parser.add_argument('--stage', default='readfile')
parser.add_argument('--path', type=Path, required=True)
parser.add_argument('--warmup', type=int, default=1)
parser.add_argument('--repeat', type=int, default=1)
parser.add_argument('--output-json', type=Path)
return parser
def main(argv: list[str] | None = None) -> int:
parser = build_arg_parser()
args = parser.parse_args(argv)
module_name, stages = READERS[args.reader]
if args.stage not in stages:
parser.error(f'reader {args.reader!r} only supports stages: {", ".join(stages)}')
module = importlib.import_module(module_name)
path = args.path.expanduser().resolve()
for _ in range(args.warmup):
_profile_stage(module, args.stage, path)
runs = []
for _ in range(args.repeat):
runs.append(_profile_stage(module, args.stage, path))
payload = {
'reader': args.reader,
'stage': args.stage,
'warmup': args.warmup,
'repeat': args.repeat,
'runs': runs,
}
rendered = json.dumps(payload, indent=2, sort_keys=True)
if args.output_json is not None:
args.output_json.parent.mkdir(parents=True, exist_ok=True)
args.output_json.write_text(rendered + '\n')
print(rendered)
return 0
if __name__ == '__main__':
raise SystemExit(main())

View file

@ -1,12 +1,6 @@
masque Tutorial masque Tutorial
=============== ===============
These examples are meant to be read roughly in order.
- Start with `basic_shapes.py` for the core `Pattern` / GDS concepts.
- Then read `devices.py` and `library.py` for hierarchical composition and libraries.
- Read the `pather*` tutorials separately when you want routing helpers.
Contents Contents
-------- --------
@ -14,30 +8,27 @@ Contents
* Draw basic geometry * Draw basic geometry
* Export to GDS * Export to GDS
- [devices](devices.py) - [devices](devices.py)
* Build hierarchical photonic-crystal example devices
* Reference other patterns * Reference other patterns
* Add ports to a pattern * Add ports to a pattern
* Use `Pather` to snap ports together into a circuit * Snap ports together to build a circuit
* Check for dangling references * Check for dangling references
- [library](library.py) - [library](library.py)
* Continue from `devices.py` by declaring a mixed library with `LibraryBuilder` * Create a `LazyLibrary`, which loads / generates patterns only when they are first used
* Import source-backed GDS cells and register python-generated recipes together
* Call `build()` to produce a normal library and report for downstream `Pather` usage and writing
* Explore alternate ways of specifying a pattern for `.plug()` and `.place()` * Explore alternate ways of specifying a pattern for `.plug()` and `.place()`
* Design a pattern which is meant to plug into an existing pattern (via `.interface()`)
- [pather](pather.py) - [pather](pather.py)
* Use `Pather` to route individual wires and wire bundles * Use `Pather` to route individual wires and wire bundles
* Define a custom `Tool` that exposes primitive routing offers * Use `AutoTool` to generate paths
* Use primitive offers to automatically transition between path types * Use `AutoTool` to automatically transition between path types
- [renderpather](renderpather.py) - [renderpather](renderpather.py)
* Use `Pather(render='deferred')` and `PathTool` to build a layout similar to the one in [pather](pather.py), * Use `RenderPather` and `PathTool` to build a layout similar to the one in [pather](pather.py),
but using `Path` shapes instead of `Polygon`s. but using `Path` shapes instead of `Polygon`s.
- [port_pather](port_pather.py) - [port_pather](port_pather.py)
* Use `PortPather` and the `.at()` syntax for more concise routing * Use `PortPather` and the `.at()` syntax for more concise routing
* Advanced port manipulation and connections * Advanced port manipulation and connections
Additionally, [pcgen](pcgen.py) is a utility module used by `devices.py` for generating Additionaly, [pcgen](pcgen.py) is a utility module for generating photonic crystal lattices.
photonic-crystal lattices; it is support code rather than a step-by-step tutorial.
Running Running
@ -49,6 +40,3 @@ cd examples/tutorial
python3 basic_shapes.py python3 basic_shapes.py
klayout -e basic_shapes.gds klayout -e basic_shapes.gds
``` ```
Some tutorials depend on outputs from earlier ones. In particular, `library.py`
expects `circuit.gds`, which is generated by `devices.py`.

View file

@ -1,18 +1,10 @@
"""
Tutorial: building hierarchical devices with `Pattern`, `Port`, and `Pather`.
This file uses photonic-crystal components as the concrete example, so some of
the geometry-generation code is domain-specific. The tutorial value is in the
Masque patterns around it: creating reusable cells, annotating ports, composing
hierarchy with references, and snapping ports together to build a larger circuit.
"""
from collections.abc import Sequence, Mapping from collections.abc import Sequence, Mapping
import numpy import numpy
from numpy import pi from numpy import pi
from masque import ( from masque import (
layer_t, Pattern, Ref, Pather, Port, Polygon, layer_t, Pattern, Ref, Builder, Port, Polygon,
Library, Library,
) )
from masque.utils import ports2data from masque.utils import ports2data
@ -72,9 +64,9 @@ def perturbed_l3(
Provided sequence should have same length as `shifts_a`. Provided sequence should have same length as `shifts_a`.
xy_size: `(x, y)` number of mirror periods in each direction; total size is xy_size: `(x, y)` number of mirror periods in each direction; total size is
`2 * n + 1` holes in each direction. Default (10, 10). `2 * n + 1` holes in each direction. Default (10, 10).
perturbed_radius: radius of holes perturbed to form an upwards-directed beam perturbed_radius: radius of holes perturbed to form an upwards-driected beam
(multiplicative factor). Default 1.1. (multiplicative factor). Default 1.1.
trench_width: Width of the undercut trenches. Default 1200. trench width: Width of the undercut trenches. Default 1200.
Returns: Returns:
`Pattern` object representing the L3 design. `Pattern` object representing the L3 design.
@ -87,15 +79,14 @@ def perturbed_l3(
shifts_a=shifts_a, shifts_a=shifts_a,
shifts_r=shifts_r) shifts_r=shifts_r)
# Build the cavity by instancing the supplied `hole` pattern many times. # Build L3 cavity, using references to the provided hole pattern
# Using references keeps the pattern compact even though it contains many holes.
pat = Pattern() pat = Pattern()
pat.refs[hole] += [ pat.refs[hole] += [
Ref(scale=r, offset=(lattice_constant * x, Ref(scale=r, offset=(lattice_constant * x,
lattice_constant * y)) lattice_constant * y))
for x, y, r in xyr] for x, y, r in xyr]
# Add rectangular undercut aids based on the referenced hole extents. # Add rectangular undercut aids
min_xy, max_xy = pat.get_bounds_nonempty(hole_lib) min_xy, max_xy = pat.get_bounds_nonempty(hole_lib)
trench_dx = max_xy[0] - min_xy[0] trench_dx = max_xy[0] - min_xy[0]
@ -104,7 +95,7 @@ def perturbed_l3(
Polygon.rect(ymax=min_xy[1], xmin=min_xy[0], lx=trench_dx, ly=trench_width), Polygon.rect(ymax=min_xy[1], xmin=min_xy[0], lx=trench_dx, ly=trench_width),
] ]
# Define the interface in Masque terms: two ports at the left/right extents. # Ports are at outer extents of the device (with y=0)
extent = lattice_constant * xy_size[0] extent = lattice_constant * xy_size[0]
pat.ports = dict( pat.ports = dict(
input=Port((-extent, 0), rotation=0, ptype='pcwg'), input=Port((-extent, 0), rotation=0, ptype='pcwg'),
@ -134,17 +125,17 @@ def waveguide(
Returns: Returns:
`Pattern` object representing the waveguide. `Pattern` object representing the waveguide.
""" """
# Generate the normalized lattice locations for the line defect. # Generate hole locations
xy = pcgen.waveguide(length=length, num_mirror=mirror_periods) xy = pcgen.waveguide(length=length, num_mirror=mirror_periods)
# Build the pattern by placing repeated references to the same hole cell. # Build the pattern
pat = Pattern() pat = Pattern()
pat.refs[hole] += [ pat.refs[hole] += [
Ref(offset=(lattice_constant * x, Ref(offset=(lattice_constant * x,
lattice_constant * y)) lattice_constant * y))
for x, y in xy] for x, y in xy]
# Publish the device interface as two ports at the outer edges. # Ports are at outer edges, with y=0
extent = lattice_constant * length / 2 extent = lattice_constant * length / 2
pat.ports = dict( pat.ports = dict(
left=Port((-extent, 0), rotation=0, ptype='pcwg'), left=Port((-extent, 0), rotation=0, ptype='pcwg'),
@ -173,17 +164,17 @@ def bend(
`Pattern` object representing the waveguide bend. `Pattern` object representing the waveguide bend.
Ports are named 'left' (input) and 'right' (output). Ports are named 'left' (input) and 'right' (output).
""" """
# Generate the normalized lattice locations for the bend. # Generate hole locations
xy = pcgen.wgbend(num_mirror=mirror_periods) xy = pcgen.wgbend(num_mirror=mirror_periods)
# Build the pattern by instancing the shared hole cell. # Build the pattern
pat = Pattern() pat= Pattern()
pat.refs[hole] += [ pat.refs[hole] += [
Ref(offset=(lattice_constant * x, Ref(offset=(lattice_constant * x,
lattice_constant * y)) lattice_constant * y))
for x, y in xy] for x, y in xy]
# Publish the bend interface as two ports. # Figure out port locations.
extent = lattice_constant * mirror_periods extent = lattice_constant * mirror_periods
pat.ports = dict( pat.ports = dict(
left=Port((-extent, 0), rotation=0, ptype='pcwg'), left=Port((-extent, 0), rotation=0, ptype='pcwg'),
@ -212,17 +203,17 @@ def y_splitter(
`Pattern` object representing the y-splitter. `Pattern` object representing the y-splitter.
Ports are named 'in', 'top', and 'bottom'. Ports are named 'in', 'top', and 'bottom'.
""" """
# Generate the normalized lattice locations for the splitter. # Generate hole locations
xy = pcgen.y_splitter(num_mirror=mirror_periods) xy = pcgen.y_splitter(num_mirror=mirror_periods)
# Build the pattern by instancing the shared hole cell. # Build pattern
pat = Pattern() pat = Pattern()
pat.refs[hole] += [ pat.refs[hole] += [
Ref(offset=(lattice_constant * x, Ref(offset=(lattice_constant * x,
lattice_constant * y)) lattice_constant * y))
for x, y in xy] for x, y in xy]
# Publish the splitter interface as one input and two outputs. # Determine port locations
extent = lattice_constant * mirror_periods extent = lattice_constant * mirror_periods
pat.ports = { pat.ports = {
'in': Port((-extent, 0), rotation=0, ptype='pcwg'), 'in': Port((-extent, 0), rotation=0, ptype='pcwg'),
@ -236,13 +227,13 @@ def y_splitter(
def main(interactive: bool = True) -> None: def main(interactive: bool = True) -> None:
# First make a couple of reusable primitive cells. # Generate some basic hole patterns
shape_lib = { shape_lib = {
'smile': basic_shapes.smile(RADIUS), 'smile': basic_shapes.smile(RADIUS),
'hole': basic_shapes.hole(RADIUS), 'hole': basic_shapes.hole(RADIUS),
} }
# Then build a small library of higher-level devices from those primitives. # Build some devices
a = LATTICE_CONSTANT a = LATTICE_CONSTANT
devices = {} devices = {}
@ -254,23 +245,22 @@ def main(interactive: bool = True) -> None:
devices['ysplit'] = y_splitter(lattice_constant=a, hole='hole', mirror_periods=5) devices['ysplit'] = y_splitter(lattice_constant=a, hole='hole', mirror_periods=5)
devices['l3cav'] = perturbed_l3(lattice_constant=a, hole='smile', hole_lib=shape_lib, xy_size=(4, 10)) # uses smile :) devices['l3cav'] = perturbed_l3(lattice_constant=a, hole='smile', hole_lib=shape_lib, xy_size=(4, 10)) # uses smile :)
# Turn the device mapping into a `Library`. # Turn our dict of devices into a Library.
# That gives us convenience helpers for hierarchy inspection and abstract views. # This provides some convenience functions in the future!
lib = Library(devices) lib = Library(devices)
# #
# Build a circuit # Build a circuit
# #
# Create a `Pather`, and register the resulting top cell as "my_circuit". # Create a `Builder`, and add the circuit to our library as "my_circuit".
circ = Pather(library=lib, name='my_circuit') circ = Builder(library=lib, name='my_circuit')
# Start by placing a waveguide and renaming its ports to match the circuit-level # Start by placing a waveguide. Call its ports "in" and "signal".
# names we want to use while assembling the design.
circ.place('wg10', offset=(0, 0), port_map={'left': 'in', 'right': 'signal'}) circ.place('wg10', offset=(0, 0), port_map={'left': 'in', 'right': 'signal'})
# Extend the signal path by attaching another waveguide. # Extend the signal path by attaching the "left" port of a waveguide.
# Because `wg10` only has one unattached port left after the plug, Masque can # Since there is only one other port ("right") on the waveguide we
# infer that it should keep the name `signal`. # are attaching (wg10), it automatically inherits the name "signal".
circ.plug('wg10', {'signal': 'left'}) circ.plug('wg10', {'signal': 'left'})
# We could have done the following instead: # We could have done the following instead:
@ -278,8 +268,8 @@ def main(interactive: bool = True) -> None:
# lib['my_circuit'] = circ_pat # lib['my_circuit'] = circ_pat
# circ_pat.place(lib.abstract('wg10'), ...) # circ_pat.place(lib.abstract('wg10'), ...)
# circ_pat.plug(lib.abstract('wg10'), ...) # circ_pat.plug(lib.abstract('wg10'), ...)
# but `Pather` removes some repeated `lib.abstract(...)` boilerplate and keeps # but `Builder` lets us omit some of the repetition of `lib.abstract(...)`, and uses similar
# the assembly code focused on port-level intent. # syntax to `Pather` and `RenderPather`, which add wire/waveguide routing functionality.
# Attach a y-splitter to the signal path. # Attach a y-splitter to the signal path.
# Since the y-splitter has 3 ports total, we can't auto-inherit the # Since the y-splitter has 3 ports total, we can't auto-inherit the
@ -291,10 +281,13 @@ def main(interactive: bool = True) -> None:
circ.plug('wg05', {'signal1': 'left'}) circ.plug('wg05', {'signal1': 'left'})
circ.plug('wg05', {'signal2': 'left'}) circ.plug('wg05', {'signal2': 'left'})
# Add a bend to both branches. # Add a bend to both ports.
# Our bend primitive is defined with a specific orientation, so choosing which # Our bend's ports "left" and "right" refer to the original counterclockwise
# port to plug determines whether the path turns clockwise or counterclockwise. # orientation. We want the bends to turn in opposite directions, so we attach
# We could also mirror one instance instead of using opposite ports. # the "right" port to "signal1" to bend clockwise, and the "left" port
# to "signal2" to bend counterclockwise.
# We could also use `mirrored=(True, False)` to mirror one of the devices
# and then use same device port on both paths.
circ.plug('bend0', {'signal1': 'right'}) circ.plug('bend0', {'signal1': 'right'})
circ.plug('bend0', {'signal2': 'left'}) circ.plug('bend0', {'signal2': 'left'})
@ -303,26 +296,29 @@ def main(interactive: bool = True) -> None:
circ.plug('l3cav', {'signal1': 'input'}) circ.plug('l3cav', {'signal1': 'input'})
circ.plug('wg10', {'signal1': 'left'}) circ.plug('wg10', {'signal1': 'left'})
# `signal2` gets a single waveguide of equivalent overall length. # "signal2" just gets a single of equivalent length
circ.plug('wg28', {'signal2': 'left'}) circ.plug('wg28', {'signal2': 'left'})
# Now bend both branches back towards each other. # Now we bend both waveguides back towards each other
circ.plug('bend0', {'signal1': 'right'}) circ.plug('bend0', {'signal1': 'right'})
circ.plug('bend0', {'signal2': 'left'}) circ.plug('bend0', {'signal2': 'left'})
circ.plug('wg05', {'signal1': 'left'}) circ.plug('wg05', {'signal1': 'left'})
circ.plug('wg05', {'signal2': 'left'}) circ.plug('wg05', {'signal2': 'left'})
# To join the branches, attach a second y-junction. # To join the waveguides, we attach a second y-junction.
# This succeeds only if both chosen ports agree on the same translation and # We plug "signal1" into the "bot" port, and "signal2" into the "top" port.
# rotation for the inserted device; otherwise Masque raises an exception. # The remaining port gets named "signal_out".
# This operation would raise an exception if the ports did not line up
# correctly (i.e. they required different rotations or translations of the
# y-junction device).
circ.plug('ysplit', {'signal1': 'bot', 'signal2': 'top'}, {'in': 'signal_out'}) circ.plug('ysplit', {'signal1': 'bot', 'signal2': 'top'}, {'in': 'signal_out'})
# Finally, add some more waveguide to "signal_out". # Finally, add some more waveguide to "signal_out".
circ.plug('wg10', {'signal_out': 'left'}) circ.plug('wg10', {'signal_out': 'left'})
# Bake the top-level port metadata into labels so it survives GDS export. # We can also add text labels for our circuit's ports.
# These labels appear on the circuit cell; individual child devices keep their # They will appear at the uppermost hierarchy level, while the individual
# own port labels in their own cells. # device ports will appear further down, in their respective cells.
ports_to_data(circ.pattern) ports_to_data(circ.pattern)
# Check if we forgot to include any patterns... ooops! # Check if we forgot to include any patterns... ooops!
@ -334,12 +330,12 @@ def main(interactive: bool = True) -> None:
lib.add(shape_lib) lib.add(shape_lib)
assert not lib.dangling_refs() assert not lib.dangling_refs()
# We can visualize the design directly, though opening the written GDS is often easier. # We can visualize the design. Usually it's easier to just view the GDS.
if interactive: if interactive:
print('Visualizing... this step may be slow') print('Visualizing... this step may be slow')
circ.pattern.visualize(lib) circ.pattern.visualize(lib)
# Write out only the subtree reachable from our top cell. #Write out to GDS, only keeping patterns referenced by our circuit (including itself)
subtree = lib.subtree('my_circuit') # don't include wg90, which we don't use subtree = lib.subtree('my_circuit') # don't include wg90, which we don't use
check_valid_names(subtree.keys()) check_valid_names(subtree.keys())
writefile(subtree, 'circuit.gds', **GDS_OPTS) writefile(subtree, 'circuit.gds', **GDS_OPTS)

View file

@ -1,133 +1,131 @@
"""
Tutorial: authoring a mixed library with `LibraryBuilder`.
This example assumes you have already read `devices.py` and generated the
`circuit.gds` file it writes. The goal here is not the photonic-crystal geometry
itself, but rather how Masque lets you combine imported GDS cells with
python-generated recipes, then turn that declaration set into a normal library
for downstream assembly and writing.
"""
from typing import Any from typing import Any
from pprint import pformat from pprint import pformat
from masque import ILibrary, LibraryBuilder, Pather, Pattern, PortLoadView, cell from masque import Builder, LazyLibrary
from masque.file.gdsii import writefile from masque.file.gdsii import writefile, load_libraryfile
from masque.file.gdsii.lazy import readfile
import basic_shapes import basic_shapes
import devices import devices
from devices import data_to_ports
from basic_shapes import GDS_OPTS from basic_shapes import GDS_OPTS
def make_mixed_waveguide(lib: ILibrary) -> Pattern:
"""
Recipe which assembles imported and generated cells behind the builder API.
"""
circ = Pather(library=lib, ports='tri_l3cav')
# First way to specify what we are plugging in: request an explicit abstract.
circ.plug(lib.abstract('wg10'), {'input': 'right'})
# Second way: use an AbstractView, which behaves like a mapping of names
# to abstracts.
abstracts = lib.abstract_view()
circ.plug(abstracts['wg10'], {'output': 'left'})
# Third way: let Pather resolve a pattern name through its own library.
circ.plug('tri_wg10', {'input': 'right'})
circ.plug('tri_wg10', {'output': 'left'})
return circ.pattern
def main() -> None: def main() -> None:
builder = LibraryBuilder() # Define a `LazyLibrary`, which provides lazy evaluation for generating
cells = builder.cells # patterns and lazy-loading of GDS contents.
lib = LazyLibrary()
# Naming and export policy can be bound once without changing individual
# declarations. For example, a foundry-specific group could use:
#
# cells = builder.cells.prefixed(
# 'foundry_',
# facade=lambda proxy: devices.ports_to_data(proxy),
# )
#
# Dynamic names use the same view: cells[generated_name] = cell(factory)(...)
# #
# Load some devices from a GDS file # Load some devices from a GDS file
# #
# Scan circuit.gds and prepare to lazy-load its contents. Port labels are # Scan circuit.gds and prepare to lazy-load its contents
# imported on first materialization, but the raw source remains untouched gds_lib, _properties = load_libraryfile('circuit.gds', postprocess=data_to_ports)
# until we build the final library.
gds_lib, _properties = readfile('circuit.gds')
builder.add_source(PortLoadView(gds_lib, layers=[(3, 0)], max_depth=1))
print('Registered imported cells:\n' + pformat(list(gds_lib.keys()))) # Add it into the device library by providing a way to read port info
# This maintains the lazy evaluation from above, so no patterns
# are actually read yet.
lib.add(gds_lib)
print('Patterns loaded from GDS into library:\n' + pformat(list(lib.keys())))
# #
# Register some new devices, this time from python code rather than GDS. # Add some new devices to the library, this time from python code rather than GDS
# #
cells.triangle = basic_shapes.triangle(devices.RADIUS) lib['triangle'] = lambda: basic_shapes.triangle(devices.RADIUS)
opts: dict[str, Any] = dict( opts: dict[str, Any] = dict(
lattice_constant=devices.LATTICE_CONSTANT, lattice_constant = devices.LATTICE_CONSTANT,
hole='triangle', hole = 'triangle',
) )
cells.tri_wg10 = cell(devices.waveguide)(length=10, mirror_periods=5, **opts) # Triangle-based variants. These are defined here, but they won't run until they're
cells.tri_wg05 = cell(devices.waveguide)(length=5, mirror_periods=5, **opts) # retrieved from the library.
cells.tri_wg28 = cell(devices.waveguide)(length=28, mirror_periods=5, **opts) lib['tri_wg10'] = lambda: devices.waveguide(length=10, mirror_periods=5, **opts)
cells.tri_bend0 = cell(devices.bend)(mirror_periods=5, **opts) lib['tri_wg05'] = lambda: devices.waveguide(length=5, mirror_periods=5, **opts)
cells.tri_ysplit = cell(devices.y_splitter)(mirror_periods=5, **opts) lib['tri_wg28'] = lambda: devices.waveguide(length=28, mirror_periods=5, **opts)
cells.tri_l3cav = cell(devices.perturbed_l3)( lib['tri_bend0'] = lambda: devices.bend(mirror_periods=5, **opts)
xy_size=(4, 10), lib['tri_ysplit'] = lambda: devices.y_splitter(mirror_periods=5, **opts)
**opts, lib['tri_l3cav'] = lambda: devices.perturbed_l3(xy_size=(4, 10), **opts, hole_lib=lib)
hole_lib=builder.library,
)
cells.mixed_wg_cav = cell(make_mixed_waveguide)(builder.library)
print('Declared cells waiting to be built:\n' + pformat(list(builder.keys())))
# #
# Build the declaration set into a normal library. # Build a mixed waveguide with an L3 cavity in the middle
# #
built, report = builder.build() # Immediately start building from an instance of the L3 cavity
print('Built library contains:\n' + pformat(list(built.keys()))) circ2 = Builder(library=lib, ports='tri_l3cav')
print('Build dependency graph:\n' + pformat(report.dependency_graph))
# First way to get abstracts is `lib.abstract(name)`
# We can use this syntax directly with `Pattern.plug()` and `Pattern.place()` as well as through `Builder`.
circ2.plug(lib.abstract('wg10'), {'input': 'right'})
# Second way to get abstracts is to use an AbstractView
# This also works directly with `Pattern.plug()` / `Pattern.place()`.
abstracts = lib.abstract_view()
circ2.plug(abstracts['wg10'], {'output': 'left'})
# Third way to specify an abstract works by automatically getting
# it from the library already within the Builder object.
# This wouldn't work if we only had a `Pattern` (not a `Builder`).
# Just pass the pattern name!
circ2.plug('tri_wg10', {'input': 'right'})
circ2.plug('tri_wg10', {'output': 'left'})
# Add the circuit to the device library.
lib['mixed_wg_cav'] = circ2.pattern
# #
# Continue designing against the built library. # Build a device that could plug into our mixed_wg_cav and joins the two ports
# #
# The built result behaves like a normal mutable library, so downstream code # We'll be designing against an existing device's interface...
# can use Pather, abstract views, and writing without going back through the circ3 = Builder.interface(source=circ2)
# builder interface.
circ = Pather.interface(source='mixed_wg_cav', library=built) # ... that lets us continue from where we left off.
circ.plug('tri_bend0', {'input': 'right'}) circ3.plug('tri_bend0', {'input': 'right'})
circ.plug('tri_bend0', {'input': 'left'}, mirrored=True) # mirror since no tri y-symmetry circ3.plug('tri_bend0', {'input': 'left'}, mirrored=True) # mirror since no tri y-symmetry
circ.plug('tri_bend0', {'input': 'right'}) circ3.plug('tri_bend0', {'input': 'right'})
circ.plug('bend0', {'output': 'left'}) circ3.plug('bend0', {'output': 'left'})
circ.plug('bend0', {'output': 'left'}) circ3.plug('bend0', {'output': 'left'})
circ.plug('bend0', {'output': 'left'}) circ3.plug('bend0', {'output': 'left'})
circ.plug('tri_wg10', {'input': 'right'}) circ3.plug('tri_wg10', {'input': 'right'})
circ.plug('tri_wg28', {'input': 'right'}) circ3.plug('tri_wg28', {'input': 'right'})
circ.plug('tri_wg10', {'input': 'right', 'output': 'left'}) circ3.plug('tri_wg10', {'input': 'right', 'output': 'left'})
built['loop_segment'] = circ.pattern
lib['loop_segment'] = circ3.pattern
# #
# Write all devices into a GDS file. # Write all devices into a GDS file
# #
print('Writing library to file...') print('Writing library to file...')
writefile(built, 'library.gds', **GDS_OPTS) writefile(lib, 'library.gds', **GDS_OPTS)
# The default build output is an overlay which borrows its lazy sources.
# Close the owning GDS source only after the overlay is no longer needed.
gds_lib.close()
if __name__ == '__main__': if __name__ == '__main__':
main() main()
#
#class prout:
# def place(
# self,
# other: Pattern,
# label_layer: layer_t = 'WATLAYER',
# *,
# port_map: Dict[str, str | None] | None = None,
# **kwargs,
# ) -> 'prout':
#
# Pattern.place(self, other, port_map=port_map, **kwargs)
# name: str | None
# for name in other.ports:
# if port_map:
# assert(name is not None)
# name = port_map.get(name, name)
# if name is None:
# continue
# self.pattern.label(string=name, offset=self.ports[name].offset, layer=label_layer)
# return self
#

View file

@ -1,20 +1,10 @@
""" """
Manual wire routing tutorial: Pather and primitive offers Manual wire routing tutorial: Pather and AutoTool
""" """
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any, Literal
import numpy
from numpy import pi from numpy import pi
from masque import Pather, Library, Pattern, Port, layer_t from masque import Pather, Library, Pattern, Port, layer_t
from masque.abstract import Abstract from masque.builder.tools import AutoTool, Tool
from masque.builder import (
BendOffer, RenderStep, StraightOffer, Tool, ToolContractCase, validate_tool_contract,
)
from masque.error import BuildError
from masque.file.gdsii import writefile from masque.file.gdsii import writefile
from masque.library import ILibrary, SINGLE_USE_PREFIX
from basic_shapes import GDS_OPTS from basic_shapes import GDS_OPTS
@ -116,259 +106,7 @@ def map_layer(layer: layer_t) -> layer_t:
'M2': (20, 0), 'M2': (20, 0),
'V1': (30, 0), 'V1': (30, 0),
} }
if isinstance(layer, str):
return layer_mapping.get(layer, layer) return layer_mapping.get(layer, layer)
return layer
@dataclass(frozen=True, slots=True)
class WireStraightData:
length: float
out_transition: 'WireTransitionSpec | None' = None
@dataclass(frozen=True, slots=True)
class WireBendData:
straight_length: float
ccw: bool
@dataclass(frozen=True, slots=True)
class WireTransitionSpec:
abstract: Abstract
in_port_name: str
out_port_name: str
@property
def in_port(self) -> Port:
return self.abstract.ports[self.in_port_name]
@property
def out_port(self) -> Port:
return self.abstract.ports[self.out_port_name]
@dataclass(frozen=True, slots=True)
class WireTransitionData:
spec: WireTransitionSpec
@dataclass
class PrimitiveWireTool(Tool):
"""
Minimal routing tool that exposes local routing primitives directly.
The high-level `Pather` methods below still decide how to compose straights,
bends, and ptype transitions. This tool only describes which one-step
primitives it can draw and how selected primitives should be rendered.
"""
layer: layer_t
width: float
ptype: str
bend: Abstract
transitions: Sequence[WireTransitionSpec]
def _straight_pattern(self, length: float) -> Pattern:
return make_straight_wire(layer=self.layer, width=self.width, ptype=self.ptype, length=length)
@staticmethod
def _transition_length(spec: WireTransitionSpec) -> float | None:
dxy, angle = spec.in_port.measure_travel(spec.out_port)
if angle is None or not numpy.isclose(angle, pi) or not numpy.isclose(dxy[1], 0):
return None
return float(dxy[0])
def _transition_offers(self, in_ptype: str | None) -> tuple[StraightOffer, ...]:
offers: list[StraightOffer] = []
for spec in self.transitions:
if spec.out_port.ptype != self.ptype:
continue
if in_ptype not in (None, 'unk', spec.in_port.ptype):
continue
length = self._transition_length(spec)
if length is None:
continue
def endpoint_planner(
parameter: float,
*,
spec: WireTransitionSpec = spec,
length: float = length,
) -> Port:
_ = parameter
return Port((length, 0), rotation=pi, ptype=spec.out_port.ptype)
def commit_planner(
parameter: float,
*,
spec: WireTransitionSpec = spec,
) -> WireTransitionData:
_ = parameter
return WireTransitionData(spec)
offers.append(StraightOffer(
in_ptype = spec.in_port.ptype,
out_ptype = spec.out_port.ptype,
length_domain = (length, length),
endpoint_planner = endpoint_planner,
commit_planner = commit_planner,
))
return tuple(offers)
def _out_transition_offers(self, out_ptype: str | None) -> tuple[StraightOffer, ...]:
if out_ptype in ('unk', self.ptype):
return ()
offers: list[StraightOffer] = []
for spec in self.transitions:
if spec.in_port.ptype != self.ptype:
continue
if out_ptype is not None and spec.out_port.ptype != out_ptype:
continue
transition_length = self._transition_length(spec)
if transition_length is None:
continue
def endpoint_planner(
length: float,
*,
spec: WireTransitionSpec = spec,
transition_length: float = transition_length,
) -> Port:
straight_length = length - transition_length
if straight_length < 0:
raise BuildError(
f'Asked to draw straight path with total length {length:,g}, shorter than required transition: {transition_length:,g}'
)
return Port((length, 0), rotation=pi, ptype=spec.out_port.ptype)
def commit_planner(
length: float,
*,
spec: WireTransitionSpec = spec,
transition_length: float = transition_length,
) -> WireStraightData:
endpoint_planner(length)
return WireStraightData(length - transition_length, spec)
offers.append(StraightOffer(
in_ptype = self.ptype,
out_ptype = spec.out_port.ptype,
length_domain = (transition_length, numpy.inf),
endpoint_planner = endpoint_planner,
commit_planner = commit_planner,
))
return tuple(offers)
def primitive_offers(
self,
kind: Literal['straight', 'bend', 's', 'u'],
*,
in_ptype: str | None = None,
out_ptype: str | None = None, # noqa: ARG002 (Pather validates selected output ptypes)
**kwargs: Any,
) -> tuple[StraightOffer | BendOffer, ...]:
if kind == 'straight':
tool_options = dict(kwargs)
def endpoint_planner(length: float) -> Port:
return Port((length, 0), rotation=pi, ptype=self.ptype)
def commit_planner(length: float) -> WireStraightData:
_ = tool_options
return WireStraightData(length)
native_offer = StraightOffer(
in_ptype = self.ptype,
out_ptype = self.ptype,
endpoint_planner = endpoint_planner,
commit_planner = commit_planner,
)
return (*self._transition_offers(in_ptype), native_offer, *self._out_transition_offers(out_ptype))
if kind == 'bend':
ccw = bool(kwargs.pop('ccw'))
bend_forward = self.width / 2
bend_run = bend_forward if ccw else -bend_forward
bend_rotation = -pi / 2 if ccw else pi / 2
def endpoint_planner(length: float) -> Port:
straight_length = length - bend_forward
if straight_length < 0:
raise BuildError(
f'Asked to draw L-path with total length {length:,g}, shorter than required bend: {bend_forward:,g}'
)
return Port((length, bend_run), rotation=bend_rotation, ptype=self.ptype)
def commit_planner(length: float) -> WireBendData:
endpoint_planner(length)
return WireBendData(straight_length=length - bend_forward, ccw=ccw)
return (BendOffer(
in_ptype = self.ptype,
out_ptype = self.ptype,
ccw = ccw,
length_domain = (bend_forward, numpy.inf),
endpoint_planner = endpoint_planner,
commit_planner = commit_planner,
),)
if kind in ('s', 'u'):
return ()
raise BuildError(f'Unrecognized primitive offer kind {kind!r}')
def _render_straight(self, tree: ILibrary, port_names: tuple[str, str], data: WireStraightData) -> None:
if numpy.isclose(data.length, 0) and data.out_transition is None:
return
if not numpy.isclose(data.length, 0):
tree.top_pattern().plug(
self._straight_pattern(data.length),
{port_names[1]: 'input'},
append=True,
)
if data.out_transition is not None:
self._render_transition(tree, port_names, WireTransitionData(data.out_transition))
def _render_bend(self, tree: ILibrary, port_names: tuple[str, str], data: WireBendData) -> None:
self._render_straight(tree, port_names, WireStraightData(data.straight_length))
tree.top_pattern().plug(
self.bend,
{port_names[1]: 'input'},
mirrored=data.ccw,
)
@staticmethod
def _render_transition(tree: ILibrary, port_names: tuple[str, str], data: WireTransitionData) -> None:
tree.top_pattern().plug(
data.spec.abstract,
{port_names[1]: data.spec.in_port_name},
)
def render(
self,
batch: Sequence[RenderStep],
*,
port_names: tuple[str, str] = ('A', 'B'),
) -> ILibrary:
tree, pat = Library.mktree(SINGLE_USE_PREFIX + 'primitive_wire')
pat.add_port_pair(names=port_names, ptype=batch[0].start_port.ptype if batch else self.ptype)
for step in batch:
assert step.tool == self
if isinstance(step.data, WireTransitionData):
self._render_transition(tree, port_names, step.data)
elif isinstance(step.data, WireStraightData):
self._render_straight(tree, port_names, step.data)
elif isinstance(step.data, WireBendData):
self._render_bend(tree, port_names, step.data)
else:
raise BuildError(f'Unexpected primitive render data {type(step.data)}')
return tree
def prepare_tools() -> tuple[Library, Tool, Tool]: def prepare_tools() -> tuple[Library, Tool, Tool]:
@ -393,55 +131,80 @@ def prepare_tools() -> tuple[Library, Tool, Tool]:
# #
# Now, define two tools. # Now, define two tools.
# M1_tool will route on M1, using wires with M1_WIDTH. # M1_tool will route on M1, using wires with M1_WIDTH
# M2_tool will route on M2, using wires with M2_WIDTH. # M2_tool will route on M2, using wires with M2_WIDTH
# Both tools are able to automatically transition from the other wire type (with a via)
# #
# Unlike the reusable `AutoTool`, this tutorial tool exposes primitive offers # Note that while we use AutoTool for this tutorial, you can define your own `Tool`
# directly: it tells `Pather` about native straight/bend primitives and about # with arbitrary logic inside -- e.g. with single-use bends, complex transition rules,
# via adapters that can transition between M1 and M2 port types. # transmission line geometry, or other features.
# #
via = library.abstract('v1_via') M1_tool = AutoTool(
via_transitions = ( # First, we need a function which takes in a length and spits out an M1 wire
WireTransitionSpec(via, 'top', 'bottom'), straights = [
WireTransitionSpec(via, 'bottom', 'top'), AutoTool.Straight(
)
M1_tool = PrimitiveWireTool(
layer = 'M1',
width = M1_WIDTH,
ptype = 'm1wire', ptype = 'm1wire',
bend = library.abstract('m1_bend'), fn = lambda length: make_straight_wire(layer='M1', ptype='m1wire', width=M1_WIDTH, length=length),
transitions = via_transitions, in_port_name = 'input', # When we get a pattern from make_straight_wire, use the port named 'input' as the input
out_port_name = 'output', # and use the port named 'output' as the output
),
],
bends = [
AutoTool.Bend(
abstract = library.abstract('m1_bend'), # When we need a bend, we'll reference the pattern we generated earlier
in_port_name = 'input',
out_port_name = 'output',
clockwise = True,
),
],
transitions = { # We can automate transitions for different (normally incompatible) port types
('m2wire', 'm1wire'): AutoTool.Transition( # For example, when we're attaching to a port with type 'm2wire'
library.abstract('v1_via'), # we can place a V1 via
'top', # using the port named 'top' as the input (i.e. the M2 side of the via)
'bottom', # and using the port named 'bottom' as the output
),
},
sbends = [],
default_out_ptype = 'm1wire', # Unless otherwise requested, we'll default to trying to stay on M1
) )
M2_tool = PrimitiveWireTool( M2_tool = AutoTool(
layer = 'M2', straights = [
width = M2_WIDTH, # Again, we use make_straight_wire, but this time we set parameters for M2
AutoTool.Straight(
ptype = 'm2wire', ptype = 'm2wire',
bend = library.abstract('m2_bend'), fn = lambda length: make_straight_wire(layer='M2', ptype='m2wire', width=M2_WIDTH, length=length),
transitions = via_transitions, in_port_name = 'input',
out_port_name = 'output',
),
],
bends = [
# and we use an M2 bend
AutoTool.Bend(
abstract = library.abstract('m2_bend'),
in_port_name = 'input',
out_port_name = 'output',
),
],
transitions = {
('m1wire', 'm2wire'): AutoTool.Transition(
library.abstract('v1_via'), # We still use the same via,
'bottom', # but the input port is now 'bottom'
'top', # and the output port is now 'top'
),
},
sbends = [],
default_out_ptype = 'm2wire', # We default to trying to stay on M2
) )
# Custom tools can be checked independently of Pather or pytest. Automatic
# probes cover each offer domain; explicit probes can target useful process
# dimensions. Unsupported primitive families opt out with require_offers=False.
for tool in (M1_tool, M2_tool):
validate_tool_contract(tool, (
ToolContractCase('straight', in_ptype=tool.ptype, probe_parameters=(10_000,)),
ToolContractCase('bend', in_ptype=tool.ptype, ccw=False),
ToolContractCase('bend', in_ptype=tool.ptype, ccw=True),
ToolContractCase('s', in_ptype=tool.ptype, require_offers=False),
ToolContractCase('u', in_ptype=tool.ptype, require_offers=False),
))
return library, M1_tool, M2_tool return library, M1_tool, M2_tool
# #
# Now we can start building up our library (collection of static cells) and pathing tools. # Now we can start building up our library (collection of static cells) and pathing tools.
# #
# If any of the operations below are confusing, you can cross-reference against the deferred # If any of the operations below are confusing, you can cross-reference against the `RenderPather`
# `Pather` tutorial, which handles some things more explicitly (e.g. via placement) and simplifies # tutorial, which handles some things more explicitly (e.g. via placement) and simplifies others
# others (e.g. geometry definition). # (e.g. geometry definition).
# #
def main() -> None: def main() -> None:
library, M1_tool, M2_tool = prepare_tools() library, M1_tool, M2_tool = prepare_tools()
@ -461,25 +224,27 @@ def main() -> None:
# Path VCC forward (in this case south) and turn clockwise 90 degrees (ccw=False) # Path VCC forward (in this case south) and turn clockwise 90 degrees (ccw=False)
# The total distance forward (including the bend's forward component) must be 6um # The total distance forward (including the bend's forward component) must be 6um
pather.cw('VCC', 6_000) pather.path('VCC', ccw=False, length=6_000)
# Now path VCC to x=0. This time, don't include any bend. # Now path VCC to x=0. This time, don't include any bend (ccw=None).
# Note that if we tried y=0 here, we would get an error since the VCC port is facing in the x-direction. # Note that if we tried y=0 here, we would get an error since the VCC port is facing in the x-direction.
pather.straight('VCC', x=0) pather.path_to('VCC', ccw=None, x=0)
# Path GND forward by 5um, turning clockwise 90 degrees. # Path GND forward by 5um, turning clockwise 90 degrees.
pather.cw('GND', 5_000) # This time we use shorthand (bool(0) == False) and omit the parameter labels
# Note that although ccw=0 is equivalent to ccw=False, ccw=None is not!
pather.path('GND', 0, 5_000)
# This time, path GND until it matches the current x-coordinate of VCC. Don't place a bend. # This time, path GND until it matches the current x-coordinate of VCC. Don't place a bend.
pather.straight('GND', x=pather['VCC'].offset[0]) pather.path_to('GND', None, x=pather['VCC'].offset[0])
# Now, start using M1_tool for GND. # Now, start using M1_tool for GND.
# Since we have defined an M2-to-M1 transition for Pather, we don't need to place one ourselves. # Since we have defined an M2-to-M1 transition for Pather, we don't need to place one ourselves.
# If we wanted to place our via manually, we could add `pather.plug('m1_via', {'GND': 'top'})` here # If we wanted to place our via manually, we could add `pather.plug('m1_via', {'GND': 'top'})` here
# and achieve the same result without having to define any transitions in M1_tool. # and achieve the same result without having to define any transitions in M1_tool.
# Note that even though we have changed the tool used for GND, the via doesn't get placed until # Note that even though we have changed the tool used for GND, the via doesn't get placed until
# the next time we route GND (the `pather.ccw()` call below). # the next time we draw a path on GND (the pather.mpath() statement below).
pather.retool(M1_tool, keys='GND') pather.retool(M1_tool, keys=['GND'])
# Bundle together GND and VCC, and path the bundle forward and counterclockwise. # Bundle together GND and VCC, and path the bundle forward and counterclockwise.
# Pick the distance so that the leading/outermost wire (in this case GND) ends up at x=-10_000. # Pick the distance so that the leading/outermost wire (in this case GND) ends up at x=-10_000.
@ -487,7 +252,7 @@ def main() -> None:
# #
# Since we recently retooled GND, its path starts with a via down to M1 (included in the distance # Since we recently retooled GND, its path starts with a via down to M1 (included in the distance
# calculation), and its straight segment and bend will be drawn using M1 while VCC's are drawn with M2. # calculation), and its straight segment and bend will be drawn using M1 while VCC's are drawn with M2.
pather.ccw(['GND', 'VCC'], xmax=-10_000, spacing=5_000) pather.mpath(['GND', 'VCC'], ccw=True, xmax=-10_000, spacing=5_000)
# Now use M1_tool as the default tool for all ports/signals. # Now use M1_tool as the default tool for all ports/signals.
# Since VCC does not have an explicitly assigned tool, it will now transition down to M1. # Since VCC does not have an explicitly assigned tool, it will now transition down to M1.
@ -497,37 +262,38 @@ def main() -> None:
# The total extension (travel distance along the forward direction) for the longest segment (in # The total extension (travel distance along the forward direction) for the longest segment (in
# this case the segment being added to GND) should be exactly 50um. # this case the segment being added to GND) should be exactly 50um.
# After turning, the wire pitch should be reduced only 1.2um. # After turning, the wire pitch should be reduced only 1.2um.
pather.ccw(['GND', 'VCC'], emax=50_000, spacing=1_200) pather.mpath(['GND', 'VCC'], ccw=True, emax=50_000, spacing=1_200)
# Make a U-turn with the bundle and expand back out to 4.5um wire pitch. # Make a U-turn with the bundle and expand back out to 4.5um wire pitch.
# Here, emin specifies the travel distance for the shortest segment. For the first call # Here, emin specifies the travel distance for the shortest segment. For the first mpath() call
# that applies to VCC, and for the second call, that applies to GND; the relative lengths of the # that applies to VCC, and for teh second call, that applies to GND; the relative lengths of the
# segments depend on their starting positions and their ordering within the bundle. # segments depend on their starting positions and their ordering within the bundle.
pather.cw(['GND', 'VCC'], emin=1_000, spacing=1_200) pather.mpath(['GND', 'VCC'], ccw=False, emin=1_000, spacing=1_200)
pather.cw(['GND', 'VCC'], emin=2_000, spacing=4_500) pather.mpath(['GND', 'VCC'], ccw=False, emin=2_000, spacing=4_500)
# Now, set the default tool back to M2_tool. Note that GND remains on M1 since it has been # Now, set the default tool back to M2_tool. Note that GND remains on M1 since it has been
# explicitly assigned a tool. # explicitly assigned a tool. We could `del pather.tools['GND']` to force it to use the default.
pather.retool(M2_tool) pather.retool(M2_tool)
# Now path both ports to x=-28_000. # Now path both ports to x=-28_000.
# With ccw=None, all ports stop at the same coordinate, and so specifying xmin= or xmax= is # When ccw is not None, xmin constrains the trailing/innermost port to stop at the target x coordinate,
# However, with ccw=None, all ports stop at the same coordinate, and so specifying xmin= or xmax= is
# equivalent. # equivalent.
pather.straight(['GND', 'VCC'], xmin=-28_000) pather.mpath(['GND', 'VCC'], None, xmin=-28_000)
# Further extend VCC out to x=-50_000, and specify that we would like to get an output on M1. # Further extend VCC out to x=-50_000, and specify that we would like to get an output on M1.
# This results in a via at the end of the wire (instead of having one at the start like we got # This results in a via at the end of the wire (instead of having one at the start like we got
# when using pather.retool(). # when using pather.retool().
pather.straight('VCC', x=-50_000, out_ptype='m1wire') pather.path_to('VCC', None, -50_000, out_ptype='m1wire')
# Now extend GND out to x=-50_000, using M2 for a portion of the path. # Now extend GND out to x=-50_000, using M2 for a portion of the path.
# We can use `pather.toolctx()` to temporarily retool, instead of calling `retool()` twice. # We can use `pather.toolctx()` to temporarily retool, instead of calling `retool()` twice.
with pather.toolctx(M2_tool, keys='GND'): with pather.toolctx(M2_tool, keys=['GND']):
pather.straight('GND', x=-40_000) pather.path_to('GND', None, -40_000)
pather.straight('GND', x=-50_000) pather.path_to('GND', None, -50_000)
# Save the pather's pattern into our library # Save the pather's pattern into our library
library['Pather_and_PrimitiveOffers'] = pather.pattern library['Pather_and_AutoTool'] = pather.pattern
# Convert from text-based layers to numeric layers for GDS, and output the file # Convert from text-based layers to numeric layers for GDS, and output the file
library.map_layers(map_layer) library.map_layers(map_layer)

View file

@ -1,7 +1,7 @@
""" """
PortPather tutorial: Using .at() syntax PortPather tutorial: Using .at() syntax
""" """
from masque import Pather, Pattern, Port, R90 from masque import RenderPather, Pattern, Port, R90
from masque.file.gdsii import writefile from masque.file.gdsii import writefile
from basic_shapes import GDS_OPTS from basic_shapes import GDS_OPTS
@ -12,8 +12,8 @@ def main() -> None:
# Reuse the same patterns (pads, bends, vias) and tools as in pather.py # Reuse the same patterns (pads, bends, vias) and tools as in pather.py
library, M1_tool, M2_tool = prepare_tools() library, M1_tool, M2_tool = prepare_tools()
# Create a deferred Pather and place some initial pads (same as Pather tutorial) # Create a RenderPather and place some initial pads (same as Pather tutorial)
rpather = Pather(library, tools=M2_tool, render='deferred') rpather = RenderPather(library, tools=M2_tool)
rpather.place('pad', offset=(18_000, 30_000), port_map={'wire_port': 'VCC'}) rpather.place('pad', offset=(18_000, 30_000), port_map={'wire_port': 'VCC'})
rpather.place('pad', offset=(18_000, 60_000), port_map={'wire_port': 'GND'}) rpather.place('pad', offset=(18_000, 60_000), port_map={'wire_port': 'GND'})
@ -27,14 +27,14 @@ def main() -> None:
# and remembers the selected port(s). This allows method chaining. # and remembers the selected port(s). This allows method chaining.
# Route VCC: 6um South, then West to x=0. # Route VCC: 6um South, then West to x=0.
# (Note: since the port points North into the pad, trace() moves South by default) # (Note: since the port points North into the pad, path() moves South by default)
(rpather.at('VCC') (rpather.at('VCC')
.trace(False, length=6_000) # Move South, turn West (Clockwise) .path(ccw=False, length=6_000) # Move South, turn West (Clockwise)
.trace_to(None, x=0) # Continue West to x=0 .path_to(ccw=None, x=0) # Continue West to x=0
) )
# Route GND: 5um South, then West to match VCC's x-coordinate. # Route GND: 5um South, then West to match VCC's x-coordinate.
rpather.at('GND').trace(False, length=5_000).trace_to(None, x=rpather['VCC'].x) rpather.at('GND').path(ccw=False, length=5_000).path_to(ccw=None, x=rpather['VCC'].x)
# #
@ -49,46 +49,45 @@ def main() -> None:
.retool(M1_tool) # this only retools the 'GND' port .retool(M1_tool) # this only retools the 'GND' port
) )
# We can also pass multiple ports to .at(), and then route them together. # We can also pass multiple ports to .at(), and then use .mpath() on them.
# Here we bundle them, turn South, and retool both to M1 (VCC gets an auto-via). # Here we bundle them, turn South, and retool both to M1 (VCC gets an auto-via).
(rpather.at(['GND', 'VCC']) (rpather.at(['GND', 'VCC'])
.trace(True, xmax=-10_000, spacing=5_000) # Move West to -10k, turn South .mpath(ccw=True, xmax=-10_000, spacing=5_000) # Move West to -10k, turn South
.retool(M1_tool) # Retools both GND and VCC .retool(M1_tool) # Retools both GND and VCC
.set_spacing(1_200) # Default bundle spacing for later bends .mpath(ccw=True, emax=50_000, spacing=1_200) # Turn East, moves 50um extension
.trace(True, emax=50_000) # Turn East, moves 50um extension .mpath(ccw=False, emin=1_000, spacing=1_200) # U-turn back South
.trace(False, emin=1_000) # U-turn back South .mpath(ccw=False, emin=2_000, spacing=4_500) # U-turn back West
.trace(False, emin=2_000, spacing=4_500) # U-turn back West, overriding the default spacing
) )
# Retool VCC back to M2 and move both to x=-28k # Retool VCC back to M2 and move both to x=-28k
rpather.at('VCC').retool(M2_tool) rpather.at('VCC').retool(M2_tool)
rpather.at(['GND', 'VCC']).trace(None, xmin=-28_000) rpather.at(['GND', 'VCC']).mpath(ccw=None, xmin=-28_000)
# Final segments to -50k # Final segments to -50k
rpather.at('VCC').trace_to(None, x=-50_000, out_ptype='m1wire') rpather.at('VCC').path_to(ccw=None, x=-50_000, out_ptype='m1wire')
with rpather.at('GND').toolctx(M2_tool): with rpather.at('GND').toolctx(M2_tool):
rpather.at('GND').trace_to(None, x=-40_000) rpather.at('GND').path_to(ccw=None, x=-40_000)
rpather.at('GND').trace_to(None, x=-50_000) rpather.at('GND').path_to(ccw=None, x=-50_000)
# #
# Branching with mark and fork # Branching with save_copy and into_copy
# #
# .mark(new_name) creates a port copy and keeps the original selected. # .save_copy(new_name) creates a port copy and keeps the original selected.
# .fork(new_name) creates a port copy and selects the new one. # .into_copy(new_name) creates a port copy and selects the new one.
# Create a tap on GND # Create a tap on GND
(rpather.at('GND') (rpather.at('GND')
.trace(None, length=5_000) # Move GND further West .path(ccw=None, length=5_000) # Move GND further West
.mark('GND_TAP') # Mark this location for a later branch .save_copy('GND_TAP') # Mark this location for a later branch
.jog(offset=-10_000, length=10_000) # Continue GND with an S-bend .pathS(length=10_000, jog=-10_000) # Continue GND with an S-bend
) )
# Branch VCC and follow the new branch # Branch VCC and follow the new branch
(rpather.at('VCC') (rpather.at('VCC')
.trace(None, length=5_000) .path(ccw=None, length=5_000)
.fork('VCC_BRANCH') # We are now manipulating 'VCC_BRANCH' .into_copy('VCC_BRANCH') # We are now manipulating 'VCC_BRANCH'
.trace(True, length=5_000) # VCC_BRANCH turns South .path(ccw=True, length=5_000) # VCC_BRANCH turns South
) )
# The original 'VCC' port remains at x=-55k, y=VCC.y # The original 'VCC' port remains at x=-55k, y=VCC.y
@ -100,25 +99,27 @@ def main() -> None:
# Route the GND_TAP we saved earlier. # Route the GND_TAP we saved earlier.
(rpather.at('GND_TAP') (rpather.at('GND_TAP')
.retool(M1_tool) .retool(M1_tool)
.trace(True, length=10_000) # Turn South .path(ccw=True, length=10_000) # Turn South
.rename('GND_FEED') # Give it a more descriptive name .rename_to('GND_FEED') # Give it a more descriptive name
.retool(M1_tool) # Re-apply tool to the new name .retool(M1_tool) # Re-apply tool to the new name
) )
# We can manage the active set of ports in a PortPather # We can manage the active set of ports in a PortPather
pp = rpather.at(['VCC_BRANCH', 'GND_FEED']) pp = rpather.at(['VCC_BRANCH', 'GND_FEED'])
pp.select('GND') # Now tracking 3 ports pp.add_port('GND') # Now tracking 3 ports
pp.deselect('VCC_BRANCH') # Now tracking 2 ports: GND_FEED, GND pp.drop_port('VCC_BRANCH') # Now tracking 2 ports: GND_FEED, GND
pp.trace(None, each=5_000) # Move both 5um forward (length > transition size) pp.path_each(ccw=None, length=5_000) # Move both 5um forward (length > transition size)
# We can also delete ports from the pather entirely # We can also delete ports from the pather entirely
rpather.at('VCC').delete() # VCC is gone (we have VCC_BRANCH instead) rpather.at('VCC').delete() # VCC is gone (we have VCC_BRANCH instead)
# #
# Advanced Connections: trace_into # Advanced Connections: path_into and path_from
# #
# trace_into routes FROM the selected port TO a target port.
# path_into routes FROM the selected port TO a target port.
# path_from routes TO the selected port FROM a source port.
# Create a destination component # Create a destination component
dest_ports = { dest_ports = {
@ -132,10 +133,10 @@ def main() -> None:
# Connect GND_FEED to DEST_A # Connect GND_FEED to DEST_A
# Since GND_FEED is moving South and DEST_A faces West, a single bend will suffice. # Since GND_FEED is moving South and DEST_A faces West, a single bend will suffice.
rpather.at('GND_FEED').trace_into('DEST_A') rpather.at('GND_FEED').path_into('DEST_A')
# Connect VCC_BRANCH to DEST_B # Connect VCC_BRANCH to DEST_B using path_from
rpather.at('VCC_BRANCH').trace_into('DEST_B') rpather.at('DEST_B').path_from('VCC_BRANCH')
# #
@ -157,7 +158,7 @@ def main() -> None:
# #
# Rendering and Saving # Rendering and Saving
# #
# Since routing is deferred, we must call .render() to generate the geometry. # Since we used RenderPather, we must call .render() to generate the geometry.
rpather.render() rpather.render()
library['PortPather_Tutorial'] = rpather.pattern library['PortPather_Tutorial'] = rpather.pattern

View file

@ -1,8 +1,8 @@
""" """
Manual wire routing tutorial: deferred Pather and PathTool Manual wire routing tutorial: RenderPather an PathTool
""" """
from masque import Pather, Library from masque import RenderPather, Library
from masque.builder import PathTool from masque.builder.tools import PathTool
from masque.file.gdsii import writefile from masque.file.gdsii import writefile
from basic_shapes import GDS_OPTS from basic_shapes import GDS_OPTS
@ -11,9 +11,9 @@ from pather import M1_WIDTH, V1_WIDTH, M2_WIDTH, map_layer, make_pad, make_via
def main() -> None: def main() -> None:
# #
# To illustrate deferred routing with `Pather`, we use `PathTool` instead # To illustrate the advantages of using `RenderPather`, we use `PathTool` instead
# of `AutoTool`. `PathTool` lacks some sophistication (e.g. no automatic transitions) # of `AutoTool`. `PathTool` lacks some sophistication (e.g. no automatic transitions)
# but when used with `Pather(render='deferred')`, it can consolidate multiple routing steps into # but when used with `RenderPather`, it can consolidate multiple routing steps into
# a single `Path` shape. # a single `Path` shape.
# #
# We'll try to nearly replicate the layout from the `Pather` tutorial; see `pather.py` # We'll try to nearly replicate the layout from the `Pather` tutorial; see `pather.py`
@ -39,7 +39,7 @@ def main() -> None:
# and what port type to present. # and what port type to present.
M1_ptool = PathTool(layer='M1', width=M1_WIDTH, ptype='m1wire') M1_ptool = PathTool(layer='M1', width=M1_WIDTH, ptype='m1wire')
M2_ptool = PathTool(layer='M2', width=M2_WIDTH, ptype='m2wire') M2_ptool = PathTool(layer='M2', width=M2_WIDTH, ptype='m2wire')
rpather = Pather(tools=M2_ptool, library=library, render='deferred') rpather = RenderPather(tools=M2_ptool, library=library)
# As in the pather tutorial, we make some pads and labels... # As in the pather tutorial, we make some pads and labels...
rpather.place('pad', offset=(18_000, 30_000), port_map={'wire_port': 'VCC'}) rpather.place('pad', offset=(18_000, 30_000), port_map={'wire_port': 'VCC'})
@ -48,28 +48,28 @@ def main() -> None:
rpather.pattern.label(layer='M2', string='GND', offset=(18e3, 60e3)) rpather.pattern.label(layer='M2', string='GND', offset=(18e3, 60e3))
# ...and start routing the signals. # ...and start routing the signals.
rpather.cw('VCC', 6_000) rpather.path('VCC', ccw=False, length=6_000)
rpather.straight('VCC', x=0) rpather.path_to('VCC', ccw=None, x=0)
rpather.cw('GND', 5_000) rpather.path('GND', 0, 5_000)
rpather.straight('GND', x=rpather.pattern['VCC'].x) rpather.path_to('GND', None, x=rpather['VCC'].x)
# `PathTool` doesn't know how to transition betwen metal layers, so we have to # `PathTool` doesn't know how to transition betwen metal layers, so we have to
# `plug` the via into the GND wire ourselves. # `plug` the via into the GND wire ourselves.
rpather.plug('v1_via', {'GND': 'top'}) rpather.plug('v1_via', {'GND': 'top'})
rpather.retool(M1_ptool, keys='GND') rpather.retool(M1_ptool, keys=['GND'])
rpather.ccw(['GND', 'VCC'], xmax=-10_000, spacing=5_000) rpather.mpath(['GND', 'VCC'], ccw=True, xmax=-10_000, spacing=5_000)
# Same thing on the VCC wire when it goes down to M1. # Same thing on the VCC wire when it goes down to M1.
rpather.plug('v1_via', {'VCC': 'top'}) rpather.plug('v1_via', {'VCC': 'top'})
rpather.retool(M1_ptool) rpather.retool(M1_ptool)
rpather.ccw(['GND', 'VCC'], emax=50_000, spacing=1_200) rpather.mpath(['GND', 'VCC'], ccw=True, emax=50_000, spacing=1_200)
rpather.cw(['GND', 'VCC'], emin=1_000, spacing=1_200) rpather.mpath(['GND', 'VCC'], ccw=False, emin=1_000, spacing=1_200)
rpather.cw(['GND', 'VCC'], emin=2_000, spacing=4_500) rpather.mpath(['GND', 'VCC'], ccw=False, emin=2_000, spacing=4_500)
# And again when VCC goes back up to M2. # And again when VCC goes back up to M2.
rpather.plug('v1_via', {'VCC': 'bottom'}) rpather.plug('v1_via', {'VCC': 'bottom'})
rpather.retool(M2_ptool) rpather.retool(M2_ptool)
rpather.straight(['GND', 'VCC'], xmin=-28_000) rpather.mpath(['GND', 'VCC'], None, xmin=-28_000)
# Finally, since PathTool has no conception of transitions, we can't # Finally, since PathTool has no conception of transitions, we can't
# just ask it to transition to an 'm1wire' port at the end of the final VCC segment. # just ask it to transition to an 'm1wire' port at the end of the final VCC segment.
@ -80,12 +80,12 @@ def main() -> None:
# alternatively, via_size = v1pat.ports['top'].measure_travel(v1pat.ports['bottom'])[0][0] # alternatively, via_size = v1pat.ports['top'].measure_travel(v1pat.ports['bottom'])[0][0]
# would take into account the port orientations if we didn't already know they're along x # would take into account the port orientations if we didn't already know they're along x
rpather.straight('VCC', x=-50_000 + via_size) rpather.path_to('VCC', None, -50_000 + via_size)
rpather.plug('v1_via', {'VCC': 'top'}) rpather.plug('v1_via', {'VCC': 'top'})
# Render the path we defined # Render the path we defined
rpather.render() rpather.render()
library['Deferred_Pather_and_PathTool'] = rpather.pattern library['RenderPather_and_PathTool'] = rpather.pattern
# Convert from text-based layers to numeric layers for GDS, and output the file # Convert from text-based layers to numeric layers for GDS, and output the file

View file

@ -42,7 +42,6 @@ from .error import (
from .shapes import ( from .shapes import (
Shape as Shape, Shape as Shape,
Polygon as Polygon, Polygon as Polygon,
RectCollection as RectCollection,
Path as Path, Path as Path,
Circle as Circle, Circle as Circle,
Arc as Arc, Arc as Arc,
@ -59,24 +58,14 @@ from .pattern import (
from .utils.boolean import boolean as boolean from .utils.boolean import boolean as boolean
from .library import ( from .library import (
INameView as INameView,
ILibraryView as ILibraryView, ILibraryView as ILibraryView,
ILibrary as ILibrary, ILibrary as ILibrary,
IBorrowing as IBorrowing,
IMaterializable as IMaterializable,
LibraryView as LibraryView, LibraryView as LibraryView,
Library as Library, Library as Library,
OverlayLibrary as OverlayLibrary,
PortLoadView as PortLoadView,
LayerMappedView as LayerMappedView,
LibraryBuilder as LibraryBuilder,
BuildReport as BuildReport,
CellProvenance as CellProvenance,
LazyLibrary as LazyLibrary, LazyLibrary as LazyLibrary,
AbstractView as AbstractView, AbstractView as AbstractView,
TreeView as TreeView, TreeView as TreeView,
Tree as Tree, Tree as Tree,
cell as cell,
) )
from .ports import ( from .ports import (
Port as Port, Port as Port,
@ -84,14 +73,12 @@ from .ports import (
) )
from .abstract import Abstract as Abstract from .abstract import Abstract as Abstract
from .builder import ( from .builder import (
Builder as Builder,
Tool as Tool, Tool as Tool,
ToolContractError as ToolContractError,
Pather as Pather, Pather as Pather,
RouteError as RouteError, RenderPather as RenderPather,
RouteFailureDetails as RouteFailureDetails,
RouteFailurePolicy as RouteFailurePolicy,
MinimumStatus as MinimumStatus,
RenderStep as RenderStep, RenderStep as RenderStep,
SimpleTool as SimpleTool,
AutoTool as AutoTool, AutoTool as AutoTool,
PathTool as PathTool, PathTool as PathTool,
PortPather as PortPather, PortPather as PortPather,
@ -106,5 +93,5 @@ from .utils import (
__author__ = 'Jan Petykiewicz' __author__ = 'Jan Petykiewicz'
__version__ = '4.0a2' __version__ = '3.4'
version = __version__ # legacy version = __version__ # legacy

View file

@ -157,8 +157,6 @@ class Abstract(PortList, Mirrorable):
self.mirror() self.mirror()
self.rotate_ports(ref.rotation) self.rotate_ports(ref.rotation)
self.rotate_port_offsets(ref.rotation) self.rotate_port_offsets(ref.rotation)
if ref.scale != 1:
self.scale_by(ref.scale)
self.translate_ports(ref.offset) self.translate_ports(ref.offset)
return self return self
@ -176,8 +174,6 @@ class Abstract(PortList, Mirrorable):
# TODO test undo_ref_transform # TODO test undo_ref_transform
""" """
self.translate_ports(-ref.offset) self.translate_ports(-ref.offset)
if ref.scale != 1:
self.scale_by(1 / ref.scale)
self.rotate_port_offsets(-ref.rotation) self.rotate_port_offsets(-ref.rotation)
self.rotate_ports(-ref.rotation) self.rotate_ports(-ref.rotation)
if ref.mirrored: if ref.mirrored:

View file

@ -1,90 +1,12 @@
""" from .builder import Builder as Builder
Builder helpers for port-based assembly and primitive-offer routing. from .pather import Pather as Pather
from .renderpather import RenderPather as RenderPather
A routing `Tool` describes the primitive route families it can provide by from .pather_mixin import PortPather as PortPather
returning `PrimitiveOffer` objects. Each offer is a parameterized planning
candidate: it exposes legal parameter domains, endpoint behavior, ptypes, cost,
optional footprint metadata, and a commit hook for producing tool-specific
render data after a concrete parameter has been selected.
`Pather` owns user-facing route operations such as `trace()`, `jog()`,
`uturn()`, and `trace_into()`. The internal planner resolves each operation into
one or more `SolverRequest`s. This normalization is why the public routing API
can remain a convenient keyword-based interface without making the solver
stringly typed internally. A pure solver search selects a `Candidate`, and a
`RouteLeg` attaches that candidate to its copied source port and Tool. Only
after selection succeeds are the chosen offers materialized through
`offer.commit(parameter)` into a `PreparedRouteResult` containing
`RenderStep.data`. `Pather` then applies that prepared result to its live ports
and pending render queue.
Selection is pure with respect to caller-owned Pattern, Library, and Pather
state. Tool offer discovery and endpoint/cost/bbox callbacks must likewise be
deterministic and must not mutate that state. `commit()` is the first
selected-offer materialization hook, but it still must not mutate the live
layout. `Tool.render()` is the geometry mutation boundary: later,
`Pather.render()` batches compatible `RenderStep`s and inserts the resulting
geometry into the Pattern and Library.
`PrimitiveOffer` and `RenderStep.data` are the tool-facing contract.
`RenderStep` is `Pather`'s deferred-render record, and
`masque.builder.planner` is an internal planner implementation rather than a
stable public API.
Custom Tool authors should run `validate_tool_contract()` as a development or
application-startup preflight. It performs the comprehensive semantic checks
that are intentionally not repeated during route selection, keeping the normal
routing path focused on search rather than contract verification.
The practical layering is:
- user code drives `Pather` and chooses Tools per port or by default,
- Tools describe local legal motion primitives without touching Pather state,
- the internal router composes those primitives into high-level route shapes,
- Pather applies the prepared result to ports, deferred render queues, and the
target pattern/library.
`Pather` intentionally remains a Pattern-oriented facade rather than exposing
separate assembly and routing objects: its user model is a working Pattern with
routing tools attached. The ownership phases above are internal boundaries,
not additional objects callers must coordinate.
Code outside the builder package should prefer the exports here over importing
from `masque.builder.planner`. The planner package is intentionally available
for tests and internal maintenance, but it is not the compatibility boundary
for custom Tools.
"""
from .pather import (
Pather as Pather,
PortPather as PortPather,
RouteCompletionCallback as RouteCompletionCallback,
)
from .error import (
ToolContractError as ToolContractError,
RouteError as RouteError,
RouteFailureDetails as RouteFailureDetails,
RouteOperation as RouteOperation,
RouteFailurePolicy as RouteFailurePolicy,
MinimumStatus as MinimumStatus,
)
from .utils import ell as ell from .utils import ell as ell
from .tool_testing import (
ToolContractCase as ToolContractCase,
validate_tool_contract as validate_tool_contract,
)
from .tools import ( from .tools import (
Tool as Tool, Tool as Tool,
RenderStep as RenderStep,
SimpleTool as SimpleTool,
AutoTool as AutoTool, AutoTool as AutoTool,
PathTool as PathTool, PathTool as PathTool,
RenderStep as RenderStep, )
RenderStepKind as RenderStepKind,
PrimitiveKind as PrimitiveKind,
CostCallable as CostCallable,
GeneratedEndpointFn as GeneratedEndpointFn,
PrimitiveOffer as PrimitiveOffer,
StraightOffer as StraightOffer,
BendOffer as BendOffer,
SOffer as SOffer,
UOffer as UOffer,
circular_arc_sbend_endpoint as circular_arc_sbend_endpoint,
)

View file

@ -1,48 +0,0 @@
"""Shared numeric tolerances for builder geometry and parameter comparisons."""
from math import isclose, remainder, tau
from typing import Any
import numpy
GEOMETRY_RTOL = 1e-5
GEOMETRY_ATOL = 1e-8
DOMAIN_RTOL = 1e-9
DOMAIN_ATOL = 1e-12
MANHATTAN_ANGLE_RTOL = 1e-9
MANHATTAN_ANGLE_ATOL = 1e-9
def scalar_close(a: float, b: float) -> bool:
"""Match the solver's existing scalar-comparison behavior."""
return isclose(float(a), float(b), rel_tol=GEOMETRY_RTOL, abs_tol=GEOMETRY_ATOL)
def array_close(a: Any, b: Any) -> bool:
"""Match NumPy's historical builder geometry-comparison behavior."""
return bool(numpy.allclose(a, b, rtol=GEOMETRY_RTOL, atol=GEOMETRY_ATOL))
def angles_equal(a: float, b: float) -> bool:
"""Return true when two rotations are equal modulo one full turn."""
delta = remainder(float(a) - float(b), tau)
return isclose(delta, 0.0, rel_tol=GEOMETRY_RTOL, abs_tol=GEOMETRY_ATOL)
def manhattan_axis(rotation: float) -> int | None:
"""Return 0 for horizontal, 1 for vertical, or None for a non-cardinal angle."""
angle = float(rotation) % (numpy.pi / 2)
if isclose(
angle,
0.0,
rel_tol=MANHATTAN_ANGLE_RTOL,
abs_tol=MANHATTAN_ANGLE_ATOL,
) or isclose(
angle,
numpy.pi / 2,
rel_tol=MANHATTAN_ANGLE_RTOL,
abs_tol=MANHATTAN_ANGLE_ATOL,
):
quarter_turn = round(float(rotation) / (numpy.pi / 2))
return quarter_turn % 2
return None

461
masque/builder/builder.py Normal file
View file

@ -0,0 +1,461 @@
"""
Simplified Pattern assembly (`Builder`)
"""
from typing import Self
from collections.abc import Iterable, Sequence, Mapping
import copy
import logging
from functools import wraps
from numpy.typing import ArrayLike
from ..pattern import Pattern
from ..library import ILibrary, TreeView
from ..error import BuildError
from ..ports import PortList, Port
from ..abstract import Abstract
logger = logging.getLogger(__name__)
class Builder(PortList):
"""
A `Builder` is a helper object used for snapping together multiple
lower-level patterns at their `Port`s.
The `Builder` mostly just holds context, in the form of a `Library`,
in addition to its underlying pattern. This simplifies some calls
to `plug` and `place`, by making the library implicit.
`Builder` can also be `set_dead()`, at which point further calls to `plug()`
and `place()` are ignored (intended for debugging).
Examples: Creating a Builder
===========================
- `Builder(library, ports={'A': port_a, 'C': port_c}, name='mypat')` makes
an empty pattern, adds the given ports, and places it into `library`
under the name `'mypat'`.
- `Builder(library)` makes an empty pattern with no ports. The pattern
is not added into `library` and must later be added with e.g.
`library['mypat'] = builder.pattern`
- `Builder(library, pattern=pattern, name='mypat')` uses an existing
pattern (including its ports) and sets `library['mypat'] = pattern`.
- `Builder.interface(other_pat, port_map=['A', 'B'], library=library)`
makes a new (empty) pattern, copies over ports 'A' and 'B' from
`other_pat`, and creates additional ports 'in_A' and 'in_B' facing
in the opposite directions. This can be used to build a device which
can plug into `other_pat` (using the 'in_*' ports) but which does not
itself include `other_pat` as a subcomponent.
- `Builder.interface(other_builder, ...)` does the same thing as
`Builder.interface(other_builder.pattern, ...)` but also uses
`other_builder.library` as its library by default.
Examples: Adding to a pattern
=============================
- `my_device.plug(subdevice, {'A': 'C', 'B': 'B'}, map_out={'D': 'myport'})`
instantiates `subdevice` into `my_device`, plugging ports 'A' and 'B'
of `my_device` into ports 'C' and 'B' of `subdevice`. The connected ports
are removed and any unconnected ports from `subdevice` are added to
`my_device`. Port 'D' of `subdevice` (unconnected) is renamed to 'myport'.
- `my_device.plug(wire, {'myport': 'A'})` places port 'A' of `wire` at 'myport'
of `my_device`. If `wire` has only two ports (e.g. 'A' and 'B'), no `map_out`,
argument is provided, and the `thru` argument is not explicitly
set to `False`, the unconnected port of `wire` is automatically renamed to
'myport'. This allows easy extension of existing ports without changing
their names or having to provide `map_out` each time `plug` is called.
- `my_device.place(pad, offset=(10, 10), rotation=pi / 2, port_map={'A': 'gnd'})`
instantiates `pad` at the specified (x, y) offset and with the specified
rotation, adding its ports to those of `my_device`. Port 'A' of `pad` is
renamed to 'gnd' so that further routing can use this signal or net name
rather than the port name on the original `pad` device.
"""
__slots__ = ('pattern', 'library', '_dead')
pattern: Pattern
""" Layout of this device """
library: ILibrary
"""
Library from which patterns should be referenced
"""
_dead: bool
""" If True, plug()/place() are skipped (for debugging)"""
@property
def ports(self) -> dict[str, Port]:
return self.pattern.ports
@ports.setter
def ports(self, value: dict[str, Port]) -> None:
self.pattern.ports = value
def __init__(
self,
library: ILibrary,
*,
pattern: Pattern | None = None,
ports: str | Mapping[str, Port] | None = None,
name: str | None = None,
) -> None:
"""
Args:
library: The library from which referenced patterns will be taken
pattern: The pattern which will be modified by subsequent operations.
If `None` (default), a new pattern is created.
ports: Allows specifying the initial set of ports, if `pattern` does
not already have any ports (or is not provided). May be a string,
in which case it is interpreted as a name in `library`.
Default `None` (no ports).
name: If specified, `library[name]` is set to `self.pattern`.
"""
self._dead = False
self.library = library
if pattern is not None:
self.pattern = pattern
else:
self.pattern = Pattern()
if ports is not None:
if self.pattern.ports:
raise BuildError('Ports supplied for pattern with pre-existing ports!')
if isinstance(ports, str):
ports = library.abstract(ports).ports
self.pattern.ports.update(copy.deepcopy(dict(ports)))
if name is not None:
library[name] = self.pattern
@classmethod
def interface(
cls: type['Builder'],
source: PortList | Mapping[str, Port] | str,
*,
library: ILibrary | None = None,
in_prefix: str = 'in_',
out_prefix: str = '',
port_map: dict[str, str] | Sequence[str] | None = None,
name: str | None = None,
) -> 'Builder':
"""
Wrapper for `Pattern.interface()`, which returns a Builder instead.
Args:
source: A collection of ports (e.g. Pattern, Builder, or dict)
from which to create the interface. May be a pattern name if
`library` is provided.
library: Library from which existing patterns should be referenced,
and to which the new one should be added (if named). If not provided,
`source.library` must exist and will be used.
in_prefix: Prepended to port names for newly-created ports with
reversed directions compared to the current device.
out_prefix: Prepended to port names for ports which are directly
copied from the current device.
port_map: Specification for ports to copy into the new device:
- If `None`, all ports are copied.
- If a sequence, only the listed ports are copied
- If a mapping, the listed ports (keys) are copied and
renamed (to the values).
Returns:
The new builder, with an empty pattern and 2x as many ports as
listed in port_map.
Raises:
`PortError` if `port_map` contains port names not present in the
current device.
`PortError` if applying the prefixes results in duplicate port
names.
"""
if library is None:
if hasattr(source, 'library') and isinstance(source.library, ILibrary):
library = source.library
else:
raise BuildError('No library was given, and `source.library` does not have one either.')
if isinstance(source, str):
source = library.abstract(source).ports
pat = Pattern.interface(source, in_prefix=in_prefix, out_prefix=out_prefix, port_map=port_map)
new = Builder(library=library, pattern=pat, name=name)
return new
@wraps(Pattern.label)
def label(self, *args, **kwargs) -> Self:
self.pattern.label(*args, **kwargs)
return self
@wraps(Pattern.ref)
def ref(self, *args, **kwargs) -> Self:
self.pattern.ref(*args, **kwargs)
return self
@wraps(Pattern.polygon)
def polygon(self, *args, **kwargs) -> Self:
self.pattern.polygon(*args, **kwargs)
return self
@wraps(Pattern.rect)
def rect(self, *args, **kwargs) -> Self:
self.pattern.rect(*args, **kwargs)
return self
# Note: We're a superclass of `Pather`, where path() means something different,
# so we shouldn't wrap Pattern.path()
#@wraps(Pattern.path)
#def path(self, *args, **kwargs) -> Self:
# self.pattern.path(*args, **kwargs)
# return self
def plug(
self,
other: Abstract | str | Pattern | TreeView,
map_in: dict[str, str],
map_out: dict[str, str | None] | None = None,
*,
mirrored: bool = False,
thru: bool | str = True,
set_rotation: bool | None = None,
append: bool = False,
ok_connections: Iterable[tuple[str, str]] = (),
) -> Self:
"""
Wrapper around `Pattern.plug` which allows a string for `other`.
The `Builder`'s library is used to dereference the string (or `Abstract`, if
one is passed with `append=True`). If a `TreeView` is passed, it is first
added into `self.library`.
Args:
other: An `Abstract`, string, `Pattern`, or `TreeView` describing the
device to be instatiated. If it is a `TreeView`, it is first
added into `self.library`, after which the topcell is plugged;
an equivalent statement is `self.plug(self.library << other, ...)`.
map_in: dict of `{'self_port': 'other_port'}` mappings, specifying
port connections between the two devices.
map_out: dict of `{'old_name': 'new_name'}` mappings, specifying
new names for ports in `other`.
mirrored: Enables mirroring `other` across the x axis prior to
connecting any ports.
thru: If map_in specifies only a single port, `thru` provides a mechainsm
to avoid repeating the port name. Eg, for `map_in={'myport': 'A'}`,
- If True (default), and `other` has only two ports total, and map_out
doesn't specify a name for the other port, its name is set to the key
in `map_in`, i.e. 'myport'.
- If a string, `map_out[thru]` is set to the key in `map_in` (i.e. 'myport').
An error is raised if that entry already exists.
This makes it easy to extend a pattern with simple 2-port devices
(e.g. wires) without providing `map_out` each time `plug` is
called. See "Examples" above for more info. Default `True`.
set_rotation: If the necessary rotation cannot be determined from
the ports being connected (i.e. all pairs have at least one
port with `rotation=None`), `set_rotation` must be provided
to indicate how much `other` should be rotated. Otherwise,
`set_rotation` must remain `None`.
append: If `True`, `other` is appended instead of being referenced.
Note that this does not flatten `other`, so its refs will still
be refs (now inside `self`).
ok_connections: Set of "allowed" ptype combinations. Identical
ptypes are always allowed to connect, as is `'unk'` with
any other ptypte. Non-allowed ptype connections will emit a
warning. Order is ignored, i.e. `(a, b)` is equivalent to
`(b, a)`.
Returns:
self
Note:
If the builder is 'dead' (see `set_dead()`), geometry generation is
skipped but ports are still updated.
Raises:
`PortError` if any ports specified in `map_in` or `map_out` do not
exist in `self.ports` or `other_names`.
`PortError` if there are any duplicate names after `map_in` and `map_out`
are applied.
`PortError` if the specified port mapping is not achieveable (the ports
do not line up)
"""
if self._dead:
logger.warning('Skipping geometry for plug() since device is dead')
if not isinstance(other, str | Abstract | Pattern):
# We got a Tree; add it into self.library and grab an Abstract for it
other = self.library << other
if isinstance(other, str):
other = self.library.abstract(other)
if append and isinstance(other, Abstract):
other = self.library[other.name]
self.pattern.plug(
other = other,
map_in = map_in,
map_out = map_out,
mirrored = mirrored,
thru = thru,
set_rotation = set_rotation,
append = append,
ok_connections = ok_connections,
skip_geometry = self._dead,
)
return self
def place(
self,
other: Abstract | str | Pattern | TreeView,
*,
offset: ArrayLike = (0, 0),
rotation: float = 0,
pivot: ArrayLike = (0, 0),
mirrored: bool = False,
port_map: dict[str, str | None] | None = None,
skip_port_check: bool = False,
append: bool = False,
) -> Self:
"""
Wrapper around `Pattern.place` which allows a string or `TreeView` for `other`.
The `Builder`'s library is used to dereference the string (or `Abstract`, if
one is passed with `append=True`). If a `TreeView` is passed, it is first
added into `self.library`.
Args:
other: An `Abstract`, string, `Pattern`, or `TreeView` describing the
device to be instatiated. If it is a `TreeView`, it is first
added into `self.library`, after which the topcell is plugged;
an equivalent statement is `self.plug(self.library << other, ...)`.
offset: Offset at which to place the instance. Default (0, 0).
rotation: Rotation applied to the instance before placement. Default 0.
pivot: Rotation is applied around this pivot point (default (0, 0)).
Rotation is applied prior to translation (`offset`).
mirrored: Whether theinstance should be mirrored across the x axis.
Mirroring is applied before translation and rotation.
port_map: dict of `{'old_name': 'new_name'}` mappings, specifying
new names for ports in the instantiated device. New names can be
`None`, which will delete those ports.
skip_port_check: Can be used to skip the internal call to `check_ports`,
in case it has already been performed elsewhere.
append: If `True`, `other` is appended instead of being referenced.
Note that this does not flatten `other`, so its refs will still
be refs (now inside `self`).
Returns:
self
Note:
If the builder is 'dead' (see `set_dead()`), geometry generation is
skipped but ports are still updated.
Raises:
`PortError` if any ports specified in `map_in` or `map_out` do not
exist in `self.ports` or `other.ports`.
`PortError` if there are any duplicate names after `map_in` and `map_out`
are applied.
"""
if self._dead:
logger.warning('Skipping geometry for place() since device is dead')
if not isinstance(other, str | Abstract | Pattern):
# We got a Tree; add it into self.library and grab an Abstract for it
other = self.library << other
if isinstance(other, str):
other = self.library.abstract(other)
if append and isinstance(other, Abstract):
other = self.library[other.name]
self.pattern.place(
other = other,
offset = offset,
rotation = rotation,
pivot = pivot,
mirrored = mirrored,
port_map = port_map,
skip_port_check = skip_port_check,
append = append,
skip_geometry = self._dead,
)
return self
def translate(self, offset: ArrayLike) -> Self:
"""
Translate the pattern and all ports.
Args:
offset: (x, y) distance to translate by
Returns:
self
"""
self.pattern.translate_elements(offset)
return self
def rotate_around(self, pivot: ArrayLike, angle: float) -> Self:
"""
Rotate the pattern and all ports.
Args:
angle: angle (radians, counterclockwise) to rotate by
pivot: location to rotate around
Returns:
self
"""
self.pattern.rotate_around(pivot, angle)
for port in self.ports.values():
port.rotate_around(pivot, angle)
return self
def mirror(self, axis: int = 0) -> Self:
"""
Mirror the pattern and all ports across the specified axis.
Args:
axis: Axis to mirror across (x=0, y=1)
Returns:
self
"""
self.pattern.mirror(axis)
return self
def set_dead(self) -> Self:
"""
Suppresses geometry generation for subsequent `plug()` and `place()`
operations. Unlike a complete skip, the port state is still tracked
and updated, using 'best-effort' fallbacks for impossible transforms.
This allows a layout script to execute through problematic sections
while maintaining valid port references for downstream code.
This is meant for debugging:
```
dev.plug(a, ...)
dev.set_dead() # added for debug purposes
dev.plug(b, ...) # usually raises an error, but now uses fallback port update
dev.plug(c, ...) # also updated via fallback
dev.pattern.visualize() # shows the device as of the set_dead() call
```
Returns:
self
"""
self._dead = True
return self
def __repr__(self) -> str:
s = f'<Builder {self.pattern} L({len(self.library)})>'
return s

View file

@ -1,109 +0,0 @@
"""Public routing failure diagnostics."""
from typing import Any, Literal
from collections.abc import Mapping
from dataclasses import dataclass
from enum import Enum, auto
from pprint import pformat
from types import MappingProxyType
import traceback
from ..error import BuildError
RouteOperation = Literal['trace', 'trace_to', 'jog', 'uturn']
class ToolContractError(BuildError):
"""A Tool returned data inconsistent with its routing contract."""
class RouteFailurePolicy(Enum):
"""Whether route failure may be recovered through alternate/dead planning.
`RECOVERABLE` means a caller-controlled fallback may try another planning
branch. `FATAL` marks an invalid request or broken planning contract that
must be reported directly.
"""
RECOVERABLE = auto()
FATAL = auto()
class MinimumStatus(Enum):
"""Outcome of preferred-minimum-length diagnosis.
`NOT_EVALUATED` is used when diagnosis is inapplicable, notably for an
invalid resolved length. `FOUND` carries `minimum_length`; `NO_ROUTE` means
exhaustive planning found no legal unconstrained route; `FAILED` means the
secondary diagnostic calculation itself raised a recoverable error.
"""
NOT_EVALUATED = auto()
FOUND = auto()
NO_ROUTE = auto()
FAILED = auto()
@dataclass(frozen=True, slots=True)
class RouteFailureDetails:
"""Structured context for a failed Pather routing request."""
operation: RouteOperation
portspec: str
in_ptype: str | None
out_ptype: str | None
request: Mapping[str, Any]
resolved_length: float | None
resolved_jog: float | None
minimum_length: float | None
minimum_status: MinimumStatus
cause: str
minimum_cause: str | None = None
def __post_init__(self) -> None:
if self.minimum_status is MinimumStatus.FOUND and self.minimum_length is None:
raise BuildError('MinimumStatus.FOUND requires minimum_length')
if self.minimum_status is not MinimumStatus.FOUND and self.minimum_length is not None:
raise BuildError(f'{self.minimum_status} requires minimum_length=None')
object.__setattr__(self, 'request', MappingProxyType(dict(self.request)))
class RouteError(BuildError):
"""A route-selection failure with structured request and saved call-stack diagnostics."""
details: RouteFailureDetails
policy: RouteFailurePolicy
_call_stack: tuple[traceback.FrameSummary, ...]
def __init__(
self,
details: RouteFailureDetails,
*,
policy: RouteFailurePolicy = RouteFailurePolicy.RECOVERABLE,
) -> None:
self.details = details
self.policy = policy
if details.minimum_status is MinimumStatus.NOT_EVALUATED:
minimum = 'not evaluated'
elif details.minimum_status is MinimumStatus.FOUND:
assert details.minimum_length is not None
minimum = f'{details.minimum_length:g}'
elif details.minimum_status is MinimumStatus.NO_ROUTE:
minimum = 'unavailable (no legal route exists at any length)'
else:
minimum = 'unavailable (minimum-length calculation failed)'
lines = [
f'Unable to plan {details.operation} route for port {details.portspec!r}:',
f' in_ptype: {details.in_ptype!r}',
f' out_ptype: {details.out_ptype!r}',
f' request: {pformat(dict(details.request), compact=True)}',
f' resolved_length: {details.resolved_length!r}',
f' resolved_jog: {details.resolved_jog!r}',
f' preferred_minimum_length: {minimum}',
f' cause: {details.cause}',
]
if details.minimum_cause is not None:
lines.append(f' minimum_failure: {details.minimum_cause}')
self._call_stack = tuple(traceback.extract_stack()[:-1])
super().__init__('\n'.join(lines))

View file

@ -1,80 +0,0 @@
"""Logging helpers for Pather."""
from typing import TYPE_CHECKING, Any
from collections.abc import Iterator, Sequence
import logging
import numpy
from contextlib import contextmanager
if TYPE_CHECKING:
from .pather import Pather
def _format_log_args(**kwargs) -> str:
arg_strs = []
for k, v in kwargs.items():
if isinstance(v, str | int | float | bool | None):
arg_strs.append(f"{k}={v}")
elif isinstance(v, numpy.ndarray):
arg_strs.append(f"{k}={v.tolist()}")
elif isinstance(v, list | tuple) and len(v) <= 10:
arg_strs.append(f"{k}={v}")
else:
arg_strs.append(f"{k}=...")
return ", ".join(arg_strs)
class PatherLogger:
"""
Encapsulates state for Pather diagnostic logging.
"""
debug: bool
indent: int
depth: int
def __init__(self, debug: bool = False) -> None:
self.debug = debug
self.indent = 0
self.depth = 0
def _log(self, module_name: str, msg: str) -> None:
if self.debug and self.depth <= 1:
log_obj = logging.getLogger(module_name)
log_obj.info(' ' * self.indent + msg)
@contextmanager
def log_operation(
self,
pather: 'Pather',
op: str,
portspec: str | Sequence[str] | None = None,
**kwargs: Any,
) -> Iterator[None]:
if not self.debug or self.depth > 0:
self.depth += 1
try:
yield
finally:
self.depth -= 1
return
target = f"({portspec})" if portspec else ""
module_name = pather.__class__.__module__
self._log(module_name, f"Operation: {op}{target} {_format_log_args(**kwargs)}")
before_ports = {name: port.copy() for name, port in pather.ports.items()}
self.depth += 1
self.indent += 1
try:
yield
finally:
after_ports = pather.ports
for name in sorted(after_ports.keys()):
if name not in before_ports or after_ports[name] != before_ports[name]:
self._log(module_name, f"Port {name}: {pather.ports[name].describe()}")
for name in sorted(before_ports.keys()):
if name not in after_ports:
self._log(module_name, f"Port {name}: removed")
self.indent -= 1
self.depth -= 1

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,677 @@
from typing import Self, overload
from collections.abc import Sequence, Iterator, Iterable
import logging
from contextlib import contextmanager
from abc import abstractmethod, ABCMeta
import numpy
from numpy import pi
from numpy.typing import ArrayLike
from ..pattern import Pattern
from ..library import ILibrary, TreeView
from ..error import PortError, BuildError
from ..utils import SupportsBool
from ..abstract import Abstract
from .tools import Tool
from .utils import ell
from ..ports import PortList
logger = logging.getLogger(__name__)
class PatherMixin(PortList, metaclass=ABCMeta):
pattern: Pattern
""" Layout of this device """
library: ILibrary
""" Library from which patterns should be referenced """
_dead: bool
""" If True, plug()/place() are skipped (for debugging) """
tools: dict[str | None, Tool]
"""
Tool objects are used to dynamically generate new single-use Devices
(e.g wires or waveguides) to be plugged into this device.
"""
@abstractmethod
def path(
self,
portspec: str,
ccw: SupportsBool | None,
length: float,
*,
plug_into: str | None = None,
**kwargs,
) -> Self:
pass
@abstractmethod
def pathS(
self,
portspec: str,
length: float,
jog: float,
*,
plug_into: str | None = None,
**kwargs,
) -> Self:
pass
@abstractmethod
def plug(
self,
other: Abstract | str | Pattern | TreeView,
map_in: dict[str, str],
map_out: dict[str, str | None] | None = None,
*,
mirrored: bool = False,
thru: bool | str = True,
set_rotation: bool | None = None,
append: bool = False,
ok_connections: Iterable[tuple[str, str]] = (),
) -> Self:
pass
def retool(
self,
tool: Tool,
keys: str | Sequence[str | None] | None = None,
) -> Self:
"""
Update the `Tool` which will be used when generating `Pattern`s for the ports
given by `keys`.
Args:
tool: The new `Tool` to use for the given ports.
keys: Which ports the tool should apply to. `None` indicates the default tool,
used when there is no matching entry in `self.tools` for the port in question.
Returns:
self
"""
if keys is None or isinstance(keys, str):
self.tools[keys] = tool
else:
for key in keys:
self.tools[key] = tool
return self
@contextmanager
def toolctx(
self,
tool: Tool,
keys: str | Sequence[str | None] | None = None,
) -> Iterator[Self]:
"""
Context manager for temporarily `retool`-ing and reverting the `retool`
upon exiting the context.
Args:
tool: The new `Tool` to use for the given ports.
keys: Which ports the tool should apply to. `None` indicates the default tool,
used when there is no matching entry in `self.tools` for the port in question.
Returns:
self
"""
if keys is None or isinstance(keys, str):
keys = [keys]
saved_tools = {kk: self.tools.get(kk, None) for kk in keys} # If not in self.tools, save `None`
try:
yield self.retool(tool=tool, keys=keys)
finally:
for kk, tt in saved_tools.items():
if tt is None:
# delete if present
self.tools.pop(kk, None)
else:
self.tools[kk] = tt
def path_to(
self,
portspec: str,
ccw: SupportsBool | None,
position: float | None = None,
*,
x: float | None = None,
y: float | None = None,
plug_into: str | None = None,
**kwargs,
) -> Self:
"""
Build a "wire"/"waveguide" extending from the port `portspec`, with the aim
of ending exactly at a target position.
The wire will travel so that the output port will be placed at exactly the target
position along the input port's axis. There can be an unspecified (tool-dependent)
offset in the perpendicular direction. The output port will be rotated (or not)
based on the `ccw` parameter.
If using `RenderPather`, `RenderPather.render` must be called after all paths have been fully planned.
Args:
portspec: The name of the port into which the wire will be plugged.
ccw: If `None`, the output should be along the same axis as the input.
Otherwise, cast to bool and turn counterclockwise if True
and clockwise otherwise.
position: The final port position, along the input's axis only.
(There may be a tool-dependent offset along the other axis.)
Only one of `position`, `x`, and `y` may be specified.
x: The final port position along the x axis.
`portspec` must refer to a horizontal port if `x` is passed, otherwise a
BuildError will be raised.
y: The final port position along the y axis.
`portspec` must refer to a vertical port if `y` is passed, otherwise a
BuildError will be raised.
plug_into: If not None, attempts to plug the wire's output port into the provided
port on `self`.
Returns:
self
Raises:
BuildError if `position`, `x`, or `y` is too close to fit the bend (if a bend
is present).
BuildError if `x` or `y` is specified but does not match the axis of `portspec`.
BuildError if more than one of `x`, `y`, and `position` is specified.
"""
if self._dead:
logger.error('Skipping path_to() since device is dead')
return self
pos_count = sum(vv is not None for vv in (position, x, y))
if pos_count > 1:
raise BuildError('Only one of `position`, `x`, and `y` may be specified at once')
if pos_count < 1:
raise BuildError('One of `position`, `x`, and `y` must be specified')
port = self.pattern[portspec]
if port.rotation is None:
raise PortError(f'Port {portspec} has no rotation and cannot be used for path_to()')
if not numpy.isclose(port.rotation % (pi / 2), 0):
raise BuildError('path_to was asked to route from non-manhattan port')
is_horizontal = numpy.isclose(port.rotation % pi, 0)
if is_horizontal:
if y is not None:
raise BuildError('Asked to path to y-coordinate, but port is horizontal')
if position is None:
position = x
else:
if x is not None:
raise BuildError('Asked to path to x-coordinate, but port is vertical')
if position is None:
position = y
x0, y0 = port.offset
if is_horizontal:
if numpy.sign(numpy.cos(port.rotation)) == numpy.sign(position - x0):
raise BuildError(f'path_to routing to behind source port: x0={x0:g} to {position:g}')
length = numpy.abs(position - x0)
else:
if numpy.sign(numpy.sin(port.rotation)) == numpy.sign(position - y0):
raise BuildError(f'path_to routing to behind source port: y0={y0:g} to {position:g}')
length = numpy.abs(position - y0)
return self.path(
portspec,
ccw,
length,
plug_into = plug_into,
**kwargs,
)
def path_into(
self,
portspec_src: str,
portspec_dst: str,
*,
out_ptype: str | None = None,
plug_destination: bool = True,
thru: str | None = None,
**kwargs,
) -> Self:
"""
Create a "wire"/"waveguide" traveling between the ports `portspec_src` and
`portspec_dst`, and `plug` it into both (or just the source port).
Only unambiguous scenarios are allowed:
- Straight connector between facing ports
- Single 90 degree bend
- Jog between facing ports
(jog is done as late as possible, i.e. only 2 L-shaped segments are used)
By default, the destination's `pytpe` will be used as the `out_ptype` for the
wire, and the `portspec_dst` will be plugged (i.e. removed).
If using `RenderPather`, `RenderPather.render` must be called after all paths have been fully planned.
Args:
portspec_src: The name of the starting port into which the wire will be plugged.
portspec_dst: The name of the destination port.
out_ptype: Passed to the pathing tool in order to specify the desired port type
to be generated at the destination end. If `None` (default), the destination
port's `ptype` will be used.
thru: If not `None`, the port by this name will be rename to `portspec_src`.
This can be used when routing a signal through a pre-placed 2-port device.
Returns:
self
Raises:
PortError if either port does not have a specified rotation.
BuildError if and invalid port config is encountered:
- Non-manhattan ports
- U-bend
- Destination too close to (or behind) source
"""
if self._dead:
logger.error('Skipping path_into() since device is dead')
return self
port_src = self.pattern[portspec_src]
port_dst = self.pattern[portspec_dst]
if out_ptype is None:
out_ptype = port_dst.ptype
if port_src.rotation is None:
raise PortError(f'Port {portspec_src} has no rotation and cannot be used for path_into()')
if port_dst.rotation is None:
raise PortError(f'Port {portspec_dst} has no rotation and cannot be used for path_into()')
if not numpy.isclose(port_src.rotation % (pi / 2), 0):
raise BuildError('path_into was asked to route from non-manhattan port')
if not numpy.isclose(port_dst.rotation % (pi / 2), 0):
raise BuildError('path_into was asked to route to non-manhattan port')
src_is_horizontal = numpy.isclose(port_src.rotation % pi, 0)
dst_is_horizontal = numpy.isclose(port_dst.rotation % pi, 0)
xs, ys = port_src.offset
xd, yd = port_dst.offset
angle = (port_dst.rotation - port_src.rotation) % (2 * pi)
dst_extra_args = {'out_ptype': out_ptype}
if plug_destination:
dst_extra_args['plug_into'] = portspec_dst
src_args = {**kwargs}
dst_args = {**src_args, **dst_extra_args}
if src_is_horizontal and not dst_is_horizontal:
# single bend should suffice
self.path_to(portspec_src, angle > pi, x=xd, **src_args)
self.path_to(portspec_src, None, y=yd, **dst_args)
elif dst_is_horizontal and not src_is_horizontal:
# single bend should suffice
self.path_to(portspec_src, angle > pi, y=yd, **src_args)
self.path_to(portspec_src, None, x=xd, **dst_args)
elif numpy.isclose(angle, pi):
if src_is_horizontal and ys == yd:
# straight connector
self.path_to(portspec_src, None, x=xd, **dst_args)
elif not src_is_horizontal and xs == xd:
# straight connector
self.path_to(portspec_src, None, y=yd, **dst_args)
else:
# S-bend, delegate to implementations
(travel, jog), _ = port_src.measure_travel(port_dst)
self.pathS(portspec_src, -travel, -jog, **dst_args)
elif numpy.isclose(angle, 0):
raise BuildError('Don\'t know how to route a U-bend yet (TODO)!')
else:
raise BuildError(f'Don\'t know how to route ports with relative angle {angle}')
if thru is not None:
self.rename_ports({thru: portspec_src})
return self
def mpath(
self,
portspec: str | Sequence[str],
ccw: SupportsBool | None,
*,
spacing: float | ArrayLike | None = None,
set_rotation: float | None = None,
**kwargs,
) -> Self:
"""
`mpath` is a superset of `path` and `path_to` which can act on bundles or buses
of "wires or "waveguides".
The wires will travel so that the output ports will be placed at well-defined
locations along the axis of their input ports, but may have arbitrary (tool-
dependent) offsets in the perpendicular direction.
If `ccw` is not `None`, the wire bundle will turn 90 degres in either the
clockwise (`ccw=False`) or counter-clockwise (`ccw=True`) direction. Within the
bundle, the center-to-center wire spacings after the turn are set by `spacing`,
which is required when `ccw` is not `None`. The final position of bundle as a
whole can be set in a number of ways:
=A>---------------------------V turn direction: `ccw=False`
=B>-------------V |
=C>-----------------------V |
=D=>----------------V |
|
x---x---x---x `spacing` (can be scalar or array)
<--------------> `emin=`
<------> `bound_type='min_past_furthest', bound=`
<--------------------------------> `emax=`
x `pmin=`
x `pmax=`
- `emin=`, equivalent to `bound_type='min_extension', bound=`
The total extension value for the furthest-out port (B in the diagram).
- `emax=`, equivalent to `bound_type='max_extension', bound=`:
The total extension value for the closest-in port (C in the diagram).
- `pmin=`, equivalent to `xmin=`, `ymin=`, or `bound_type='min_position', bound=`:
The coordinate of the innermost bend (D's bend).
The x/y versions throw an error if they do not match the port axis (for debug)
- `pmax=`, `xmax=`, `ymax=`, or `bound_type='max_position', bound=`:
The coordinate of the outermost bend (A's bend).
The x/y versions throw an error if they do not match the port axis (for debug)
- `bound_type='min_past_furthest', bound=`:
The distance between furthest out-port (B) and the innermost bend (D's bend).
If `ccw=None`, final output positions (along the input axis) of all wires will be
identical (i.e. wires will all be cut off evenly). In this case, `spacing=None` is
required. In this case, `emin=` and `emax=` are equivalent to each other, and
`pmin=`, `pmax=`, `xmin=`, etc. are also equivalent to each other.
If using `RenderPather`, `RenderPather.render` must be called after all paths have been fully planned.
Args:
portspec: The names of the ports which are to be routed.
ccw: If `None`, the outputs should be along the same axis as the inputs.
Otherwise, cast to bool and turn 90 degrees counterclockwise if `True`
and clockwise otherwise.
spacing: Center-to-center distance between output ports along the input port's axis.
Must be provided if (and only if) `ccw` is not `None`.
set_rotation: If the provided ports have `rotation=None`, this can be used
to set a rotation for them.
Returns:
self
Raises:
BuildError if the implied length for any wire is too close to fit the bend
(if a bend is requested).
BuildError if `xmin`/`xmax` or `ymin`/`ymax` is specified but does not
match the axis of `portspec`.
BuildError if an incorrect bound type or spacing is specified.
"""
if self._dead:
logger.error('Skipping mpath() since device is dead')
return self
bound_types = set()
if 'bound_type' in kwargs:
bound_types.add(kwargs.pop('bound_type'))
bound = kwargs.pop('bound')
for bt in ('emin', 'emax', 'pmin', 'pmax', 'xmin', 'xmax', 'ymin', 'ymax', 'min_past_furthest'):
if bt in kwargs:
bound_types.add(bt)
bound = kwargs.pop(bt)
if not bound_types:
raise BuildError('No bound type specified for mpath')
if len(bound_types) > 1:
raise BuildError(f'Too many bound types specified for mpath: {bound_types}')
bound_type = tuple(bound_types)[0]
if isinstance(portspec, str):
portspec = [portspec]
ports = self.pattern[tuple(portspec)]
extensions = ell(ports, ccw, spacing=spacing, bound=bound, bound_type=bound_type, set_rotation=set_rotation)
#if container:
# assert not getattr(self, 'render'), 'Containers not implemented for RenderPather'
# bld = self.interface(source=ports, library=self.library, tools=self.tools)
# for port_name, length in extensions.items():
# bld.path(port_name, ccw, length, **kwargs)
# self.library[container] = bld.pattern
# self.plug(Abstract(container, bld.pattern.ports), {sp: 'in_' + sp for sp in ports}) # TODO safe to use 'in_'?
#else:
for port_name, length in extensions.items():
self.path(port_name, ccw, length, **kwargs)
return self
# TODO def bus_join()?
def flatten(self) -> Self:
"""
Flatten the contained pattern, using the contained library to resolve references.
Returns:
self
"""
self.pattern.flatten(self.library)
return self
def at(self, portspec: str | Iterable[str]) -> 'PortPather':
return PortPather(portspec, self)
class PortPather:
"""
Port state manager
This class provides a convenient way to perform multiple pathing operations on a
set of ports without needing to repeatedly pass their names.
"""
ports: list[str]
pather: PatherMixin
def __init__(self, ports: str | Iterable[str], pather: PatherMixin) -> None:
self.ports = [ports] if isinstance(ports, str) else list(ports)
self.pather = pather
#
# Delegate to pather
#
def retool(self, tool: Tool) -> Self:
self.pather.retool(tool, keys=self.ports)
return self
@contextmanager
def toolctx(self, tool: Tool) -> Iterator[Self]:
with self.pather.toolctx(tool, keys=self.ports):
yield self
def path(self, *args, **kwargs) -> Self:
if len(self.ports) > 1:
logger.warning('Use path_each() when pathing multiple ports independently')
for port in self.ports:
self.pather.path(port, *args, **kwargs)
return self
def path_each(self, *args, **kwargs) -> Self:
for port in self.ports:
self.pather.path(port, *args, **kwargs)
return self
def pathS(self, *args, **kwargs) -> Self:
if len(self.ports) > 1:
logger.warning('Use pathS_each() when pathing multiple ports independently')
for port in self.ports:
self.pather.pathS(port, *args, **kwargs)
return self
def pathS_each(self, *args, **kwargs) -> Self:
for port in self.ports:
self.pather.pathS(port, *args, **kwargs)
return self
def path_to(self, *args, **kwargs) -> Self:
if len(self.ports) > 1:
logger.warning('Use path_each_to() when pathing multiple ports independently')
for port in self.ports:
self.pather.path_to(port, *args, **kwargs)
return self
def path_each_to(self, *args, **kwargs) -> Self:
for port in self.ports:
self.pather.path_to(port, *args, **kwargs)
return self
def mpath(self, *args, **kwargs) -> Self:
self.pather.mpath(self.ports, *args, **kwargs)
return self
def path_into(self, *args, **kwargs) -> Self:
""" Path_into, using the current port as the source """
if len(self.ports) > 1:
raise BuildError(f'Unable use implicit path_into() with {len(self.ports)} (>1) ports.')
self.pather.path_into(self.ports[0], *args, **kwargs)
return self
def path_from(self, *args, **kwargs) -> Self:
""" Path_into, using the current port as the destination """
if len(self.ports) > 1:
raise BuildError(f'Unable use implicit path_from() with {len(self.ports)} (>1) ports.')
thru = kwargs.pop('thru', None)
self.pather.path_into(args[0], self.ports[0], *args[1:], **kwargs)
if thru is not None:
self.rename_from(thru)
return self
def plug(
self,
other: Abstract | str,
other_port: str,
*args,
**kwargs,
) -> Self:
if len(self.ports) > 1:
raise BuildError(f'Unable use implicit plug() with {len(self.ports)} ports.'
'Use the pather or pattern directly to plug multiple ports.')
self.pather.plug(other, {self.ports[0]: other_port}, *args, **kwargs)
return self
def plugged(self, other_port: str) -> Self:
if len(self.ports) > 1:
raise BuildError(f'Unable use implicit plugged() with {len(self.ports)} (>1) ports.')
self.pather.plugged({self.ports[0]: other_port})
return self
#
# Delegate to port
#
def set_ptype(self, ptype: str) -> Self:
for port in self.ports:
self.pather[port].set_ptype(ptype)
return self
def translate(self, *args, **kwargs) -> Self:
for port in self.ports:
self.pather[port].translate(*args, **kwargs)
return self
def mirror(self, *args, **kwargs) -> Self:
for port in self.ports:
self.pather[port].mirror(*args, **kwargs)
return self
def rotate(self, rotation: float) -> Self:
for port in self.ports:
self.pather[port].rotate(rotation)
return self
def set_rotation(self, rotation: float | None) -> Self:
for port in self.ports:
self.pather[port].set_rotation(rotation)
return self
def rename_to(self, new_name: str) -> Self:
if len(self.ports) > 1:
BuildError('Use rename_ports() for >1 port')
self.pather.rename_ports({self.ports[0]: new_name})
self.ports[0] = new_name
return self
def rename_from(self, old_name: str) -> Self:
if len(self.ports) > 1:
BuildError('Use rename_ports() for >1 port')
self.pather.rename_ports({old_name: self.ports[0]})
return self
def rename_ports(self, name_map: dict[str, str | None]) -> Self:
self.pather.rename_ports(name_map)
self.ports = [mm for mm in [name_map.get(pp, pp) for pp in self.ports] if mm is not None]
return self
def add_ports(self, ports: Iterable[str]) -> Self:
ports = list(ports)
conflicts = set(ports) & set(self.ports)
if conflicts:
raise BuildError(f'ports {conflicts} already selected')
self.ports += ports
return self
def add_port(self, port: str, index: int | None = None) -> Self:
if port in self.ports:
raise BuildError(f'{port=} already selected')
if index is not None:
self.ports.insert(index, port)
else:
self.ports.append(port)
return self
def drop_port(self, port: str) -> Self:
if port not in self.ports:
raise BuildError(f'{port=} already not selected')
self.ports = [pp for pp in self.ports if pp != port]
return self
def into_copy(self, new_name: str, src: str | None = None) -> Self:
""" Copy a port and replace it with the copy """
if not self.ports:
raise BuildError('Have no ports to copy')
if len(self.ports) == 1:
src = self.ports[0]
elif src is None:
raise BuildError('Must specify src when >1 port is available')
if src not in self.ports:
raise BuildError(f'{src=} not available')
self.pather.ports[new_name] = self.pather[src].copy()
self.ports = [(new_name if pp == src else pp) for pp in self.ports]
return self
def save_copy(self, new_name: str, src: str | None = None) -> Self:
""" Copy a port and but keep using the original """
if not self.ports:
raise BuildError('Have no ports to copy')
if len(self.ports) == 1:
src = self.ports[0]
elif src is None:
raise BuildError('Must specify src when >1 port is available')
if src not in self.ports:
raise BuildError(f'{src=} not available')
self.pather.ports[new_name] = self.pather[src].copy()
return self
@overload
def delete(self, name: None) -> None: ...
@overload
def delete(self, name: str) -> Self: ...
def delete(self, name: str | None = None) -> Self | None:
if name is None:
for pp in self.ports:
del self.pather.ports[pp]
return None
del self.pather.ports[name]
self.ports = [pp for pp in self.ports if pp != name]
return self

View file

@ -1,17 +0,0 @@
"""
Simplified primitive-offer route planner used by `Pather`.
This package is the Pather-facing route-selection implementation. It keeps
the public Tool contract narrow: offers are evaluated during planning, and
offer commits are deferred until after a complete route is selected.
"""
from .interface import (
PreparedRouteAction as PreparedRouteAction,
PreparedRouteResult as PreparedRouteResult,
RoutePlanningError as RoutePlanningError,
RoutePortContext as RoutePortContext,
route_failure_policy as route_failure_policy,
)
from .planner import RouteTieBreakStrategy as RouteTieBreakStrategy
from .planner import TraceIntoBendPolicy as TraceIntoBendPolicy
from .planner import RoutingPlanner as RoutingPlanner

View file

@ -1,284 +0,0 @@
"""
Argument validation and bound resolution for Pather routing calls.
This module keeps user-facing mode validation outside the solver. It converts
single-port positional bounds into local travel lengths and derives multi-port
S/U bundle specs before primitive offers are considered.
The solver expects one coherent route intent at a time. This module enforces
that public routing modes are not mixed: explicit length, per-port `each`,
positional bounds, and bundle bounds are mutually constrained before any Tool
offers are queried. Multi-port S/U bundles are also normalized here into exact
per-port public lengths and offsets.
"""
from __future__ import annotations
# ruff: noqa: TC001,TC002,TC003
from typing import Any
from collections.abc import Mapping, Sequence
from pprint import pformat
import numpy
from numpy import pi
from numpy.typing import ArrayLike, NDArray
from ...error import BuildError, PortError
from ...ports import Port
from ...utils import rotation_matrix_2d
from .._tolerances import manhattan_axis
from .interface import RoutePortContext
POSITION_KEYS: tuple[str, ...] = ('p', 'x', 'y', 'pos', 'position')
BUNDLE_BOUND_KEYS: tuple[str, ...] = (
'emin', 'emax', 'pmin', 'pmax', 'xmin', 'xmax', 'ymin', 'ymax', 'min_past_furthest',
)
def finite_scalar(value: Any, name: str, *, nonnegative: bool = False) -> float:
"""Return a finite scalar, preserving duck-typed numeric inputs."""
try:
array = numpy.asarray(value, dtype=float)
except (TypeError, ValueError) as err:
raise BuildError(f'{name} must be a finite numeric scalar') from err
if array.size != 1:
raise BuildError(f'{name} must be a scalar; got {array.size} values')
result = float(array.reshape(-1)[0])
if not numpy.isfinite(result):
raise BuildError(f'{name} must be finite')
if nonnegative and result < 0:
raise BuildError(f'{name} must be nonnegative')
return result
def resolved_position_bound(
port: Port,
bounds: Mapping[str, Any],
*,
allow_length: bool,
) -> tuple[str, Any, float] | None:
"""Resolve a single positional bound for a single port into a travel length."""
present = [(key, bounds[key]) for key in POSITION_KEYS if bounds.get(key) is not None]
if not present:
return None
if len(present) > 1:
keys = ', '.join(key for key, _value in present)
raise BuildError(f'Provide exactly one positional bound; got {keys}')
if not allow_length and bounds.get('length') is not None:
raise BuildError('length cannot be combined with a positional bound')
key, raw_value = present[0]
value = finite_scalar(raw_value, f'{key} positional bound')
if port.rotation is None:
raise BuildError('Ports must have rotation')
axis = manhattan_axis(port.rotation)
if axis is None:
raise BuildError(
'Positional bounds require a nearly Manhattan port direction; '
f'got rotation {port.rotation:g}'
)
if axis == 0:
if key == 'y':
raise BuildError('Port is horizontal')
target = Port((value, port.offset[1]), rotation=None)
else:
if key == 'x':
raise BuildError('Port is vertical')
target = Port((port.offset[0], value), rotation=None)
(travel, _jog), _ = port.measure_travel(target)
return key, value, -float(travel)
def present_keys(bounds: Mapping[str, Any], keys: Sequence[str]) -> list[str]:
"""Return keys whose bound value is explicitly present and non-None."""
return [key for key in keys if bounds.get(key) is not None]
def present_bundle_bounds(bounds: Mapping[str, Any]) -> list[str]:
"""Return active multi-port trace bound keys."""
return present_keys(bounds, BUNDLE_BOUND_KEYS)
def validate_trace_args(
portspec: Sequence[str],
*,
length: float | None,
spacing: float | ArrayLike | None,
bounds: Mapping[str, Any],
) -> None:
"""
Validate mutually-exclusive `trace()` routing modes.
A trace request is either an explicit single-port length, an `each` length
for all ports, a single-port omitted-length solve, or a bundle solve with
exactly one bundle bound.
"""
bundle_bounds = present_bundle_bounds(bounds)
if len(bundle_bounds) > 1:
args = ', '.join(bundle_bounds)
raise BuildError(f'Provide exactly one bundle bound for trace(); got {args}')
invalid_with_length = present_keys(bounds, ('each', 'set_rotation')) + bundle_bounds
invalid_with_each = present_keys(bounds, ('set_rotation',)) + bundle_bounds
if length is not None:
if len(portspec) > 1:
raise BuildError('length only allowed with a single port')
if spacing is not None:
invalid_with_length.append('spacing')
if invalid_with_length:
args = ', '.join(invalid_with_length)
raise BuildError(f'length cannot be combined with other routing bounds: {args}')
return
if bounds.get('each') is not None:
if spacing is not None:
invalid_with_each.append('spacing')
if invalid_with_each:
args = ', '.join(invalid_with_each)
raise BuildError(f'each cannot be combined with other routing bounds: {args}')
return
if not bundle_bounds and len(portspec) == 1:
if spacing is not None:
raise BuildError('spacing cannot be combined with omitted-length single-port trace()')
invalid = present_keys(bounds, ('set_rotation',))
if invalid:
args = ', '.join(invalid)
raise BuildError(f'Unsupported routing bounds for omitted-length trace(): {args}')
return
if not bundle_bounds:
raise BuildError('No bound type specified for trace()')
def validate_trace_to_positional_args(
*,
spacing: float | ArrayLike | None,
bounds: Mapping[str, Any],
) -> None:
"""Reject bound combinations that cannot be mixed with a single positional `trace_to()` target."""
invalid = present_keys(bounds, ('each', 'set_rotation')) + present_bundle_bounds(bounds)
if spacing is not None:
invalid.append('spacing')
if invalid:
args = ', '.join(invalid)
raise BuildError(f'Positional bounds cannot be combined with other routing bounds: {args}')
def validate_jog_args(
portspec: Sequence[str],
*,
length: float | None,
spacing: float | ArrayLike | None,
bounds: Mapping[str, Any],
) -> None:
"""
Validate `jog()` mode constraints before S-route planning.
Single-port jogs may derive length from a positional bound. Multi-port jogs
require spacing and cannot combine omitted length with positional bounds.
"""
invalid = present_keys(bounds, ('each', 'set_rotation')) + present_bundle_bounds(bounds)
if len(portspec) == 1 and spacing is not None:
invalid.append('spacing')
if len(portspec) > 1 and length is None:
invalid += present_keys(bounds, POSITION_KEYS)
if length is not None:
invalid = present_keys(bounds, POSITION_KEYS) + invalid
if invalid:
args = ', '.join(invalid)
raise BuildError(f'length cannot be combined with other routing bounds in jog(): {args}')
return
if invalid:
args = ', '.join(invalid)
raise BuildError(f'Unsupported routing bounds for jog(): {args}')
def validate_uturn_args(
portspec: Sequence[str],
*,
spacing: float | ArrayLike | None,
bounds: Mapping[str, Any],
) -> None:
"""Validate `uturn()` arguments, which do not support positional or bundle-bound keywords."""
invalid = present_keys(bounds, POSITION_KEYS + ('each', 'set_rotation')) + present_bundle_bounds(bounds)
if len(portspec) == 1 and spacing is not None:
invalid.append('spacing')
if invalid:
args = ', '.join(invalid)
raise BuildError(f'Unsupported routing bounds for uturn(): {args}')
def su_bundle_specs(
contexts: Sequence[RoutePortContext],
offset: float,
length: float,
spacing: float | ArrayLike | None,
*,
route_name: str,
) -> tuple[tuple[str, float, float], ...]:
"""
Normalize a multi-port S/U bundle into per-port `(name, length, offset)` specs.
Ports are ordered from the inside of the first bend outward. The first spec
receives the requested base route; later specs add cumulative spacing to
both route length and lateral offset so the bundle keeps the requested
separation.
"""
if spacing is None:
raise BuildError(f'Must provide spacing for multi-port {route_name}()')
finite_scalar(offset, 'offset')
finite_scalar(length, 'length', nonnegative=True)
ports = {context.portspec: context.port for context in contexts}
has_rotation = numpy.array([port.rotation is not None for port in ports.values()], dtype=bool)
if not has_rotation.all():
raise PortError(f'Ports must have rotation for multi-port {route_name}()')
rotations = numpy.array([port.rotation for port in ports.values()], dtype=float)
if not numpy.allclose(rotations[0], rotations):
port_rotations = {name: numpy.rad2deg(port.rotation) for name, port in ports.items()}
raise BuildError(
f'Asked to find multi-port {route_name}() bundle for ports that face in different directions:\n'
+ pformat(port_rotations)
)
direction = rotations[0] + pi
rot_matrix = rotation_matrix_2d(-direction)
orig_offsets = numpy.array([port.offset for port in ports.values()])
rot_offsets = (rot_matrix @ orig_offsets.T).T
first_ccw = bool(offset > 0)
y_order = ((-1 if first_ccw else 1) * rot_offsets[:, 1]).argsort(kind='stable')
spacing_arr = numpy.asarray(spacing, dtype=float).reshape(-1)
if numpy.any(spacing_arr < 0):
raise BuildError('spacing must be nonnegative')
steps: NDArray[numpy.float64] = numpy.zeros(len(ports), dtype=float)
if spacing_arr.size == 1:
steps[1:] = spacing_arr[0]
elif spacing_arr.size == len(ports) - 1:
steps[1:] = spacing_arr
else:
raise BuildError(
f'spacing must be scalar or have length {len(ports) - 1} for {len(ports)} ports; '
f'got length {spacing_arr.size}'
)
if not numpy.all(numpy.isfinite(steps)):
raise BuildError('spacing must contain only finite values')
names = tuple(ports.keys())
ordered_spacings = numpy.cumsum(steps)
anchor_y = float(rot_offsets[y_order[0], 1])
specs: list[tuple[str, float, float]] = []
for order_index, port_index in enumerate(y_order):
spacing_offset = float(ordered_spacings[order_index])
start_y = float(rot_offsets[port_index, 1])
specs.append((
names[port_index],
float(length) + spacing_offset,
float(offset) - start_y + anchor_y + spacing_offset,
))
return tuple(specs)

Some files were not shown because too many files have changed in this diff Show more