Compare commits
91 changed files with 3832 additions and 22274 deletions
703
MIGRATION.md
703
MIGRATION.md
|
|
@ -1,8 +1,7 @@
|
||||||
# Migration Guide
|
# Migration Guide
|
||||||
|
|
||||||
This guide covers changes between the `master` branch and the current tree.
|
This guide covers changes between the git tag `release` and the current tree.
|
||||||
Both `master` and the current tree report `masque.__version__ == '3.4'`; the
|
At `release`, `masque.__version__` was `3.3`; the current tree reports `3.4`.
|
||||||
version string has not yet been bumped for these changes.
|
|
||||||
|
|
||||||
Most downstream changes are in `masque/builder/*`, but there are a few other
|
Most downstream changes are in `masque/builder/*`, but there are a few other
|
||||||
API changes that may require code updates.
|
API changes that may require code updates.
|
||||||
|
|
@ -23,13 +22,13 @@ The biggest migration point is that the old routing verbs were renamed:
|
||||||
| `Pather.pathU(...)` | `Pather.uturn(...)` |
|
| `Pather.pathU(...)` | `Pather.uturn(...)` |
|
||||||
| `Pather.path_into(...)` | `Pather.trace_into(...)` |
|
| `Pather.path_into(...)` | `Pather.trace_into(...)` |
|
||||||
| `Pather.path_from(src, dst)` | `Pather.at(src).trace_into(dst)` |
|
| `Pather.path_from(src, dst)` | `Pather.at(src).trace_into(dst)` |
|
||||||
| `RenderPather.path(...)` | `Pather(..., render='deferred').trace(...)` |
|
| `RenderPather.path(...)` | `Pather(..., auto_render=False).trace(...)` |
|
||||||
| `RenderPather.path_to(...)` | `Pather(..., render='deferred').trace_to(...)` |
|
| `RenderPather.path_to(...)` | `Pather(..., auto_render=False).trace_to(...)` |
|
||||||
| `RenderPather.mpath(...)` | `Pather(..., render='deferred').trace(...)` / `Pather(..., render='deferred').trace_to(...)` |
|
| `RenderPather.mpath(...)` | `Pather(..., auto_render=False).trace(...)` / `Pather(..., auto_render=False).trace_to(...)` |
|
||||||
| `RenderPather.pathS(...)` | `Pather(..., render='deferred').jog(...)` |
|
| `RenderPather.pathS(...)` | `Pather(..., auto_render=False).jog(...)` |
|
||||||
| `RenderPather.pathU(...)` | `Pather(..., render='deferred').uturn(...)` |
|
| `RenderPather.pathU(...)` | `Pather(..., auto_render=False).uturn(...)` |
|
||||||
| `RenderPather.path_into(...)` | `Pather(..., render='deferred').trace_into(...)` |
|
| `RenderPather.path_into(...)` | `Pather(..., auto_render=False).trace_into(...)` |
|
||||||
| `RenderPather.path_from(src, dst)` | `Pather(..., render='deferred').at(src).trace_into(dst)` |
|
| `RenderPather.path_from(src, dst)` | `Pather(..., auto_render=False).at(src).trace_into(dst)` |
|
||||||
|
|
||||||
There are also new convenience wrappers:
|
There are also new convenience wrappers:
|
||||||
|
|
||||||
|
|
@ -124,107 +123,89 @@ from masque.builder.renderpather import RenderPather
|
||||||
from masque.builder import Pather
|
from masque.builder import Pather
|
||||||
|
|
||||||
builder = Pather(...)
|
builder = Pather(...)
|
||||||
deferred = Pather(..., render='deferred')
|
deferred = Pather(..., auto_render=False)
|
||||||
```
|
```
|
||||||
|
|
||||||
The new `Pather` remains importable from both `masque` and `masque.builder`.
|
Top-level imports from `masque` also continue to work.
|
||||||
The removed `Builder` and `RenderPather` names are no longer exported from
|
|
||||||
either location.
|
|
||||||
|
|
||||||
`Pather` now defaults to `render='auto'`, so plain construction replaces the
|
`Pather` now defaults to `auto_render=True`, so plain construction replaces the
|
||||||
old `Builder` behavior. Use `Pather(..., render='deferred')` where you
|
old `Builder` behavior. Use `Pather(..., auto_render=False)` where you
|
||||||
previously used `RenderPather`.
|
previously used `RenderPather`.
|
||||||
|
|
||||||
## `SimpleTool` was removed and `AutoTool` registration changed
|
## `BasicTool` was replaced
|
||||||
|
|
||||||
`SimpleTool` is no longer exported. `AutoTool` remains, but its old public
|
`BasicTool` is no longer exported. Use:
|
||||||
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`
|
- `SimpleTool` for the simple "one straight generator + one bend cell" case
|
||||||
|
- `AutoTool` if you need transitions, multiple candidate straights/bends, or
|
||||||
|
S-bends/U-bends
|
||||||
|
|
||||||
|
### Old `BasicTool`
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from masque.builder import AutoTool
|
from masque.builder.tools import BasicTool
|
||||||
|
|
||||||
tool = AutoTool(
|
tool = BasicTool(
|
||||||
straights=[
|
straight=(make_straight, 'input', 'output'),
|
||||||
AutoTool.Straight('m1wire', make_straight, 'input', 'output'),
|
bend=(lib.abstract('bend'), 'input', 'output'),
|
||||||
],
|
|
||||||
bends=[
|
|
||||||
AutoTool.Bend(lib.abstract('bend'), 'input', 'output'),
|
|
||||||
],
|
|
||||||
sbends=[],
|
|
||||||
transitions={
|
transitions={
|
||||||
('m2wire', 'm1wire'): AutoTool.Transition(
|
'm2wire': (lib.abstract('via'), 'top', 'bottom'),
|
||||||
lib.abstract('via'), 'top', 'bottom'
|
|
||||||
),
|
|
||||||
},
|
},
|
||||||
default_out_ptype='m1wire',
|
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
### New `AutoTool`
|
### New `AutoTool`
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from masque.builder import AutoTool
|
from masque.builder.tools import AutoTool
|
||||||
|
|
||||||
tool = (
|
tool = AutoTool(
|
||||||
AutoTool()
|
straights=[
|
||||||
.add_straight(make_straight, 'm1wire', 'input')
|
AutoTool.Straight(
|
||||||
.add_bend(lib.abstract('bend'), 'input', 'output', clockwise=True)
|
ptype='m1wire',
|
||||||
.add_transition(lib.abstract('via'), 'top', 'bottom')
|
fn=make_straight,
|
||||||
|
in_port_name='input',
|
||||||
|
out_port_name='output',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
bends=[
|
||||||
|
AutoTool.Bend(
|
||||||
|
abstract=lib.abstract('bend'),
|
||||||
|
in_port_name='input',
|
||||||
|
out_port_name='output',
|
||||||
|
clockwise=True,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
sbends=[],
|
||||||
|
transitions={
|
||||||
|
('m2wire', 'm1wire'): AutoTool.Transition(
|
||||||
|
lib.abstract('via'),
|
||||||
|
'top',
|
||||||
|
'bottom',
|
||||||
|
),
|
||||||
|
},
|
||||||
|
default_out_ptype='m1wire',
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
The key differences are:
|
The key differences are:
|
||||||
|
|
||||||
- `SimpleTool` was removed; use `AutoTool` or implement the new `Tool`
|
- `BasicTool` -> `SimpleTool` or `AutoTool`
|
||||||
primitive-offer interface
|
- `straight=(fn, in_name, out_name)` -> `straights=[AutoTool.Straight(...)]`
|
||||||
- `AutoTool.Straight(...)` -> `add_straight(fn, ptype, in_name)`
|
- `bend=(abstract, in_name, out_name)` -> `bends=[AutoTool.Bend(...)]`
|
||||||
- `AutoTool.Bend(...)` -> `add_bend(abstract, in_name, out_name)`
|
- transition keys are now `(external_ptype, internal_ptype)` tuples
|
||||||
- `AutoTool.SBend(...)` -> `add_sbend(fn, ptype, in_name, out_name)`
|
- transitions use `AutoTool.Transition(...)` instead of raw tuples
|
||||||
- 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
|
If your old `BasicTool` usage did not rely on transitions or multiple routing
|
||||||
order. Every `add_*()` method accepts `cost=`, as do the concrete offer
|
options, `SimpleTool` is the closest replacement.
|
||||||
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
|
## Custom `Tool` subclasses
|
||||||
|
|
||||||
If you maintain your own `Tool` subclass, the interface changed:
|
If you maintain your own `Tool` subclass, the interface changed:
|
||||||
|
|
||||||
- `primitive_offers()` is now the planning boundary
|
- `Tool.path(...)` became `Tool.traceL(...)`
|
||||||
- `render()` consumes committed primitive render tokens
|
- `Tool.traceS(...)` and `Tool.traceU(...)` were added for native S/U routes
|
||||||
- `Tool.path(...)`, `traceL()`, `traceS()`, `traceU()`, `planL()`,
|
- `planL()` / `planS()` / `planU()` remain the planning hooks used by deferred rendering
|
||||||
`planS()`, and `planU()` are no longer part of the public `Tool` API
|
|
||||||
|
|
||||||
In practice, a minimal old implementation like:
|
In practice, a minimal old implementation like:
|
||||||
|
|
||||||
|
|
@ -237,269 +218,14 @@ class MyTool(Tool):
|
||||||
should now become:
|
should now become:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from collections.abc import Sequence
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
from masque import Port
|
|
||||||
from masque.builder import RenderStep, StraightOffer, Tool
|
|
||||||
|
|
||||||
|
|
||||||
class MyTool(Tool):
|
class MyTool(Tool):
|
||||||
def primitive_offers(self, kind, *, in_ptype=None, out_ptype=None, **kwargs):
|
def traceL(self, ccw, length, **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`
|
If you do not implement `traceS()` or `traceU()`, the unified pather will
|
||||||
will compose available primitive offers where the route family allows it.
|
either fall back to the planning hooks or synthesize those routes from simpler
|
||||||
|
steps where possible.
|
||||||
### 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
|
## Transform semantics changed
|
||||||
|
|
||||||
|
|
@ -536,305 +262,26 @@ Check code that calls:
|
||||||
- `Ref.rotate(...)`
|
- `Ref.rotate(...)`
|
||||||
- `Ref.mirror(...)`
|
- `Ref.mirror(...)`
|
||||||
- `Label.rotate_around(...)` / `Label.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
|
If that code expected offsets or repetition grids to move automatically, it
|
||||||
needs updating. For whole-pattern transforms, prefer calling `Pattern.mirror()`
|
needs updating. For whole-pattern transforms, prefer calling `Pattern.mirror()`
|
||||||
or `Pattern.rotate_around(...)` at the container level.
|
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
|
## 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
|
### DXF environments
|
||||||
|
|
||||||
If you install the DXF extra, the supported `ezdxf` baseline moved from
|
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.
|
`~=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
|
### New exports
|
||||||
|
|
||||||
These are additive, but available now from `masque` and `masque.builder`:
|
These are additive, but available now from `masque` and `masque.builder`:
|
||||||
|
|
||||||
- from `masque`: `RectCollection`, `boolean`, `OverlayLibrary`,
|
- `PortPather`
|
||||||
`PortLoadView`, `LayerMappedView`, `IMaterializable`, `IBorrowing`, `LibraryBuilder`,
|
- `SimpleTool`
|
||||||
`BuildReport`, `CellProvenance`, and `cell`
|
- `AutoTool`
|
||||||
- from `masque.builder`: `CostCallable`, `RenderStepKind`, the concrete
|
- `boolean`
|
||||||
primitive-offer classes, structured route error/status types,
|
|
||||||
`ToolContractCase`, and `validate_tool_contract`
|
|
||||||
|
|
||||||
## Minimal migration checklist
|
## Minimal migration checklist
|
||||||
|
|
||||||
|
|
@ -842,15 +289,11 @@ If your code uses the routing stack, do these first:
|
||||||
|
|
||||||
1. Replace `path`/`path_to`/`mpath`/`path_into` calls with
|
1. Replace `path`/`path_to`/`mpath`/`path_into` calls with
|
||||||
`trace`/`trace_to`/multi-port `trace`/`trace_into`.
|
`trace`/`trace_to`/multi-port `trace`/`trace_into`.
|
||||||
2. Replace `SimpleTool` and old `AutoTool` descriptor construction with the
|
2. Replace `BasicTool` with `SimpleTool` or `AutoTool`.
|
||||||
new `AutoTool.add_*()` methods.
|
|
||||||
3. Fix imports that still reference `masque.builder.builder` or
|
3. Fix imports that still reference `masque.builder.builder` or
|
||||||
`masque.builder.renderpather`.
|
`masque.builder.renderpather`.
|
||||||
4. Audit any low-level `mirror()` usage, especially on `Port` and `Ref`.
|
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
|
If your code only uses `Pattern`, `Library`, `place()`, and `plug()` without the
|
||||||
routing helpers, audit transforms, dangling-reference graph calls, raw shape
|
routing helpers, you may not need any changes beyond the transform audit and any
|
||||||
construction, and any stale imports.
|
stale imports.
|
||||||
|
|
|
||||||
|
|
@ -275,6 +275,8 @@ my_pattern.ref(_make_my_subpattern(), offset=..., ...)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
## Development
|
## TODO
|
||||||
|
|
||||||
Project-level planned work is tracked in [TODO.md](TODO.md).
|
* PolyCollection & arrow-based read/write
|
||||||
|
* Bus-to-bus connections?
|
||||||
|
* tuple / string layer auto-translation
|
||||||
|
|
|
||||||
|
|
@ -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())
|
|
||||||
|
|
@ -20,16 +20,16 @@ Contents
|
||||||
* Use `Pather` to snap ports together into a circuit
|
* Use `Pather` to snap ports together into 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`
|
* Continue from `devices.py` using a lazy library
|
||||||
* Import source-backed GDS cells and register python-generated recipes together
|
* Create a `LazyLibrary`, which loads / generates patterns only when they are first used
|
||||||
* 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 `Pather(auto_render=False)` 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
|
||||||
|
|
|
||||||
|
|
@ -1,133 +1,142 @@
|
||||||
"""
|
"""
|
||||||
Tutorial: authoring a mixed library with `LibraryBuilder`.
|
Tutorial: using `LazyLibrary` and `Pather.interface()`.
|
||||||
|
|
||||||
This example assumes you have already read `devices.py` and generated the
|
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
|
`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
|
itself, but rather how Masque lets you mix lazily loaded GDS content with
|
||||||
python-generated recipes, then turn that declaration set into a normal library
|
python-generated devices inside one 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 Pather, 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()
|
# A `LazyLibrary` delays work until a pattern is actually needed.
|
||||||
cells = builder.cells
|
# That applies both to GDS cells we load from disk and to python callables
|
||||||
|
# that generate patterns on demand.
|
||||||
# Naming and export policy can be bound once without changing individual
|
lib = LazyLibrary()
|
||||||
# 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 those cells into our lazy library.
|
||||||
|
# Nothing is read yet; we are only registering how to fetch and postprocess
|
||||||
|
# each pattern when it is first requested.
|
||||||
|
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 lambdas are only recipes for building the
|
||||||
cells.tri_wg05 = cell(devices.waveguide)(length=5, mirror_periods=5, **opts)
|
# patterns; they do not execute until someone asks for the cell.
|
||||||
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()
|
# Start a new design by copying the ports from an existing library cell.
|
||||||
print('Built library contains:\n' + pformat(list(built.keys())))
|
# This gives `circ2` the same external interface as `tri_l3cav`.
|
||||||
print('Build dependency graph:\n' + pformat(report.dependency_graph))
|
circ2 = Pather(library=lib, ports='tri_l3cav')
|
||||||
|
|
||||||
|
# First way to specify what we are plugging in: request an explicit abstract.
|
||||||
|
# This works with `Pattern` methods directly as well as with `Pather`.
|
||||||
|
circ2.plug(lib.abstract('wg10'), {'input': 'right'})
|
||||||
|
|
||||||
|
# Second way: use an `AbstractView`, which behaves like a mapping of names
|
||||||
|
# to abstracts.
|
||||||
|
abstracts = lib.abstract_view()
|
||||||
|
circ2.plug(abstracts['wg10'], {'output': 'left'})
|
||||||
|
|
||||||
|
# Third way: let `Pather` resolve a pattern name through its own library.
|
||||||
|
# This shorthand is convenient, but it is specific to helpers that already
|
||||||
|
# carry a library reference.
|
||||||
|
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 second device that is explicitly designed to mate with `circ2`.
|
||||||
#
|
#
|
||||||
|
|
||||||
# The built result behaves like a normal mutable library, so downstream code
|
# `Pather.interface()` makes a new pattern whose ports mirror an existing
|
||||||
# can use Pather, abstract views, and writing without going back through the
|
# design's external interface. That is useful when you want to design an
|
||||||
# builder interface.
|
# adapter, continuation, or mating structure.
|
||||||
circ = Pather.interface(source='mixed_wg_cav', library=built)
|
circ3 = Pather.interface(source=circ2)
|
||||||
circ.plug('tri_bend0', {'input': 'right'})
|
|
||||||
circ.plug('tri_bend0', {'input': 'left'}, mirrored=True) # mirror since no tri y-symmetry
|
# Continue routing outward from those inherited ports.
|
||||||
circ.plug('tri_bend0', {'input': 'right'})
|
circ3.plug('tri_bend0', {'input': 'right'})
|
||||||
circ.plug('bend0', {'output': 'left'})
|
circ3.plug('tri_bend0', {'input': 'left'}, mirrored=True) # mirror since no tri y-symmetry
|
||||||
circ.plug('bend0', {'output': 'left'})
|
circ3.plug('tri_bend0', {'input': 'right'})
|
||||||
circ.plug('bend0', {'output': 'left'})
|
circ3.plug('bend0', {'output': 'left'})
|
||||||
circ.plug('tri_wg10', {'input': 'right'})
|
circ3.plug('bend0', {'output': 'left'})
|
||||||
circ.plug('tri_wg28', {'input': 'right'})
|
circ3.plug('bend0', {'output': 'left'})
|
||||||
circ.plug('tri_wg10', {'input': 'right', 'output': 'left'})
|
circ3.plug('tri_wg10', {'input': 'right'})
|
||||||
built['loop_segment'] = circ.pattern
|
circ3.plug('tri_wg28', {'input': 'right'})
|
||||||
|
circ3.plug('tri_wg10', {'input': 'right', 'output': 'left'})
|
||||||
|
|
||||||
|
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
|
||||||
|
#
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
|
|
||||||
|
|
@ -121,256 +111,6 @@ def map_layer(layer: layer_t) -> layer_t:
|
||||||
return 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]:
|
||||||
"""
|
"""
|
||||||
Create some basic library elements and tools for drawing M1 and M2
|
Create some basic library elements and tools for drawing M1 and M2
|
||||||
|
|
@ -393,46 +133,71 @@ 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
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -527,7 +292,7 @@ def main() -> None:
|
||||||
pather.straight('GND', x=-50_000)
|
pather.straight('GND', x=-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)
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ def main() -> None:
|
||||||
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 deferred Pather and place some initial pads (same as Pather tutorial)
|
||||||
rpather = Pather(library, tools=M2_tool, render='deferred')
|
rpather = Pather(library, tools=M2_tool, auto_render=False)
|
||||||
|
|
||||||
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'})
|
||||||
|
|
@ -157,7 +157,7 @@ def main() -> None:
|
||||||
#
|
#
|
||||||
# Rendering and Saving
|
# Rendering and Saving
|
||||||
#
|
#
|
||||||
# Since routing is deferred, we must call .render() to generate the geometry.
|
# Since we deferred auto-rendering, we must call .render() to generate the geometry.
|
||||||
rpather.render()
|
rpather.render()
|
||||||
|
|
||||||
library['PortPather_Tutorial'] = rpather.pattern
|
library['PortPather_Tutorial'] = rpather.pattern
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
Manual wire routing tutorial: deferred Pather and PathTool
|
Manual wire routing tutorial: deferred Pather and PathTool
|
||||||
"""
|
"""
|
||||||
from masque import Pather, Library
|
from masque import Pather, 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
|
||||||
|
|
@ -13,7 +13,7 @@ def main() -> None:
|
||||||
#
|
#
|
||||||
# To illustrate deferred routing with `Pather`, we use `PathTool` instead
|
# To illustrate deferred routing with `Pather`, 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 `Pather(auto_render=False)`, 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 = Pather(tools=M2_ptool, library=library, auto_render=False)
|
||||||
|
|
||||||
# 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'})
|
||||||
|
|
|
||||||
|
|
@ -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,
|
||||||
|
|
@ -85,13 +74,9 @@ from .ports import (
|
||||||
from .abstract import Abstract as Abstract
|
from .abstract import Abstract as Abstract
|
||||||
from .builder import (
|
from .builder import (
|
||||||
Tool as Tool,
|
Tool as Tool,
|
||||||
ToolContractError as ToolContractError,
|
|
||||||
Pather as Pather,
|
Pather as Pather,
|
||||||
RouteError as RouteError,
|
|
||||||
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 +91,5 @@ from .utils import (
|
||||||
|
|
||||||
__author__ = 'Jan Petykiewicz'
|
__author__ = 'Jan Petykiewicz'
|
||||||
|
|
||||||
__version__ = '4.0a2'
|
__version__ = '3.4'
|
||||||
version = __version__ # legacy
|
version = __version__ # legacy
|
||||||
|
|
|
||||||
|
|
@ -1,90 +1,13 @@
|
||||||
"""
|
|
||||||
Builder helpers for port-based assembly and primitive-offer routing.
|
|
||||||
|
|
||||||
A routing `Tool` describes the primitive route families it can provide by
|
|
||||||
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 (
|
from .pather import (
|
||||||
Pather as Pather,
|
Pather as Pather,
|
||||||
PortPather as PortPather,
|
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,
|
|
||||||
)
|
)
|
||||||
|
from .logging import logged_op as logged_op
|
||||||
|
|
|
||||||
|
|
@ -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
|
|
||||||
|
|
@ -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))
|
|
||||||
|
|
@ -1,13 +1,19 @@
|
||||||
"""Logging helpers for Pather."""
|
"""
|
||||||
|
Logging and operation decorators for Pather
|
||||||
|
"""
|
||||||
from typing import TYPE_CHECKING, Any
|
from typing import TYPE_CHECKING, Any
|
||||||
from collections.abc import Iterator, Sequence
|
from collections.abc import Iterator, Sequence, Callable
|
||||||
import logging
|
import logging
|
||||||
|
from functools import wraps
|
||||||
|
import inspect
|
||||||
import numpy
|
import numpy
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from .pather import Pather
|
from .pather import Pather
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def _format_log_args(**kwargs) -> str:
|
def _format_log_args(**kwargs) -> str:
|
||||||
arg_strs = []
|
arg_strs = []
|
||||||
|
|
@ -78,3 +84,37 @@ class PatherLogger:
|
||||||
|
|
||||||
self.indent -= 1
|
self.indent -= 1
|
||||||
self.depth -= 1
|
self.depth -= 1
|
||||||
|
|
||||||
|
|
||||||
|
def logged_op(
|
||||||
|
portspec_getter: Callable[[dict[str, Any]], str | Sequence[str] | None] | None = None,
|
||||||
|
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
|
||||||
|
"""
|
||||||
|
Decorator to wrap Pather methods with logging.
|
||||||
|
"""
|
||||||
|
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
||||||
|
sig = inspect.signature(func)
|
||||||
|
|
||||||
|
@wraps(func)
|
||||||
|
def wrapper(self: 'Pather', *args: Any, **kwargs: Any) -> Any:
|
||||||
|
logger_obj = getattr(self, '_logger', None)
|
||||||
|
if logger_obj is None or not logger_obj.debug:
|
||||||
|
return func(self, *args, **kwargs)
|
||||||
|
|
||||||
|
bound = sig.bind(self, *args, **kwargs)
|
||||||
|
bound.apply_defaults()
|
||||||
|
all_args = bound.arguments
|
||||||
|
# remove 'self' from logged args
|
||||||
|
logged_args = {k: v for k, v in all_args.items() if k != 'self'}
|
||||||
|
|
||||||
|
ps = portspec_getter(all_args) if portspec_getter else None
|
||||||
|
|
||||||
|
# Remove portspec from logged_args if it's there to avoid duplicate arg to log_operation
|
||||||
|
logged_args.pop('portspec', None)
|
||||||
|
|
||||||
|
with logger_obj.log_operation(self, func.__name__, ps, **logged_args):
|
||||||
|
if getattr(self, '_dead', False) and func.__name__ in ('plug', 'place'):
|
||||||
|
logger.warning(f"Skipping geometry for {func.__name__}() since device is dead")
|
||||||
|
return func(self, *args, **kwargs)
|
||||||
|
return wrapper
|
||||||
|
return decorator
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -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
|
|
||||||
|
|
@ -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)
|
|
||||||
|
|
@ -1,96 +0,0 @@
|
||||||
"""
|
|
||||||
Planner/Pather exchange types.
|
|
||||||
|
|
||||||
`Pather` snapshots live routing state into these records before calling the
|
|
||||||
planner. The planner returns prepared actions that `Pather` can apply without
|
|
||||||
needing to know solver internals.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
# ruff: noqa: TC001
|
|
||||||
|
|
||||||
from dataclasses import dataclass
|
|
||||||
|
|
||||||
from ...error import BuildError
|
|
||||||
from ...ports import Port
|
|
||||||
from ..tools import RenderStep, Tool
|
|
||||||
from ..error import RouteError, RouteFailurePolicy, ToolContractError
|
|
||||||
|
|
||||||
|
|
||||||
class RoutePlanningError(BuildError):
|
|
||||||
"""Route-planning error with fallback policy metadata."""
|
|
||||||
|
|
||||||
policy: RouteFailurePolicy
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
*args: object,
|
|
||||||
policy: RouteFailurePolicy = RouteFailurePolicy.RECOVERABLE,
|
|
||||||
) -> None:
|
|
||||||
super().__init__(*args)
|
|
||||||
self.policy = policy
|
|
||||||
|
|
||||||
|
|
||||||
def route_failure_policy(err: Exception) -> RouteFailurePolicy:
|
|
||||||
"""Return typed route recovery policy, defaulting generic errors to recoverable."""
|
|
||||||
if isinstance(err, ToolContractError):
|
|
||||||
return RouteFailurePolicy.FATAL
|
|
||||||
if isinstance(err, RoutePlanningError):
|
|
||||||
return err.policy
|
|
||||||
if isinstance(err, RouteError):
|
|
||||||
return err.policy
|
|
||||||
return RouteFailurePolicy.RECOVERABLE
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
|
||||||
class RoutePortContext:
|
|
||||||
"""
|
|
||||||
Immutable planning view of one live Pather port.
|
|
||||||
|
|
||||||
`port` is a copy of the live port so failed route selection leaves Pather
|
|
||||||
state unchanged. `tool` is the already-resolved routing Tool for this
|
|
||||||
portspec.
|
|
||||||
"""
|
|
||||||
portspec: str
|
|
||||||
"""Live Pather port name being planned."""
|
|
||||||
port: Port
|
|
||||||
"""Copied live port used as immutable route input."""
|
|
||||||
tool: Tool
|
|
||||||
"""Resolved Tool for this port."""
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
|
||||||
class PreparedRouteAction:
|
|
||||||
"""
|
|
||||||
Prepared mutation for one routed Pather port.
|
|
||||||
|
|
||||||
Pure selection has already completed, and the planner has materialized the
|
|
||||||
selected primitive offers into `render_steps` and computed the final live
|
|
||||||
port. `plug_into`, when set, names the destination port to consume after the
|
|
||||||
route endpoint is applied.
|
|
||||||
"""
|
|
||||||
portspec: str
|
|
||||||
"""Live Pather port name to update."""
|
|
||||||
render_steps: tuple[RenderStep, ...]
|
|
||||||
"""Committed route steps to append to Pather's pending render queue."""
|
|
||||||
final_port: Port
|
|
||||||
"""Final live port value after all route steps."""
|
|
||||||
plug_into: str | None = None
|
|
||||||
"""Optional destination port to consume after the final port is applied."""
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
|
||||||
class PreparedRouteResult:
|
|
||||||
"""
|
|
||||||
Complete prepared result for one Pather routing operation.
|
|
||||||
|
|
||||||
`actions` contain materialized, committed render data and are applied first.
|
|
||||||
`renames` are deferred until after all route actions so trace-into/thru
|
|
||||||
behavior can be represented without exposing the solver's selected
|
|
||||||
primitive sequence to Pather.
|
|
||||||
"""
|
|
||||||
actions: tuple[PreparedRouteAction, ...]
|
|
||||||
"""Prepared per-port route mutations."""
|
|
||||||
renames: tuple[tuple[str, str], ...] = ()
|
|
||||||
"""Deferred `(old_name, new_name)` port renames applied after actions."""
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,368 +0,0 @@
|
||||||
"""Pytest-independent contract checks for custom routing Tools."""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from copy import deepcopy
|
|
||||||
from dataclasses import dataclass, field
|
|
||||||
from math import isfinite
|
|
||||||
from types import MappingProxyType
|
|
||||||
from typing import TYPE_CHECKING, Any
|
|
||||||
|
|
||||||
import numpy
|
|
||||||
from numpy import pi
|
|
||||||
|
|
||||||
from ..library import ILibrary, SINGLE_USE_PREFIX
|
|
||||||
from ..ports import Port
|
|
||||||
from ..utils import ptypes_compatible
|
|
||||||
from ._tolerances import angles_equal, array_close, scalar_close
|
|
||||||
from .error import ToolContractError
|
|
||||||
from .tools import (
|
|
||||||
BendOffer, PrimitiveKind, PrimitiveOffer, RenderStep, SOffer, StraightOffer, Tool, UOffer,
|
|
||||||
)
|
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
|
||||||
from collections.abc import Mapping, Sequence
|
|
||||||
|
|
||||||
|
|
||||||
_RESERVED_OPTION_KEYS = frozenset(('kind', 'in_ptype', 'out_ptype', 'ccw'))
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
|
||||||
class ToolContractCase:
|
|
||||||
"""One primitive-discovery query to exercise against a custom Tool."""
|
|
||||||
|
|
||||||
kind: PrimitiveKind
|
|
||||||
in_ptype: str | None = None
|
|
||||||
out_ptype: str | None = None
|
|
||||||
ccw: bool | None = None
|
|
||||||
tool_options: Mapping[str, Any] = field(default_factory=lambda: MappingProxyType({}))
|
|
||||||
probe_parameters: tuple[float, ...] = ()
|
|
||||||
require_offers: bool = True
|
|
||||||
check_bbox: bool = False
|
|
||||||
label: str | None = None
|
|
||||||
|
|
||||||
def __post_init__(self) -> None:
|
|
||||||
if self.kind not in ('straight', 'bend', 's', 'u'):
|
|
||||||
raise ValueError(f'Unrecognized primitive kind {self.kind!r}')
|
|
||||||
if self.kind == 'bend':
|
|
||||||
if self.ccw is None:
|
|
||||||
raise ValueError('Bend ToolContractCase requires ccw')
|
|
||||||
elif self.ccw is not None:
|
|
||||||
raise ValueError('ccw is only valid for bend ToolContractCase')
|
|
||||||
|
|
||||||
try:
|
|
||||||
options = deepcopy(dict(self.tool_options))
|
|
||||||
except Exception as err:
|
|
||||||
raise ValueError('ToolContractCase.tool_options must be a deep-copyable mapping') from err
|
|
||||||
nonstring = [key for key in options if not isinstance(key, str)]
|
|
||||||
if nonstring:
|
|
||||||
raise ValueError(f'ToolContractCase.tool_options keys must be strings; got {nonstring!r}')
|
|
||||||
collisions = sorted(_RESERVED_OPTION_KEYS & options.keys())
|
|
||||||
if collisions:
|
|
||||||
raise ValueError(f'ToolContractCase.tool_options contains reserved keys: {", ".join(collisions)}')
|
|
||||||
|
|
||||||
try:
|
|
||||||
probes = tuple(float(value) for value in self.probe_parameters)
|
|
||||||
except (TypeError, ValueError, OverflowError) as err:
|
|
||||||
raise ValueError('ToolContractCase.probe_parameters must contain numeric scalars') from err
|
|
||||||
if not all(isfinite(value) for value in probes):
|
|
||||||
raise ValueError('ToolContractCase.probe_parameters must be finite')
|
|
||||||
|
|
||||||
object.__setattr__(self, 'ccw', None if self.ccw is None else bool(self.ccw))
|
|
||||||
object.__setattr__(self, 'tool_options', MappingProxyType(options))
|
|
||||||
object.__setattr__(self, 'probe_parameters', probes)
|
|
||||||
|
|
||||||
|
|
||||||
def _automatic_probes(offer: PrimitiveOffer) -> tuple[float, ...]:
|
|
||||||
"""Choose deterministic representative parameters inside one offer domain."""
|
|
||||||
lower, upper = (float(value) for value in offer.parameter_domain)
|
|
||||||
if lower == upper:
|
|
||||||
return (lower,)
|
|
||||||
if numpy.isfinite(lower) and numpy.isfinite(upper):
|
|
||||||
midpoint = lower / 2 + upper / 2
|
|
||||||
if midpoint == upper:
|
|
||||||
midpoint = float(numpy.nextafter(upper, lower))
|
|
||||||
return (lower, midpoint)
|
|
||||||
if numpy.isfinite(lower):
|
|
||||||
step = max(1.0, abs(lower) * 0.1)
|
|
||||||
return (lower, lower + step)
|
|
||||||
if numpy.isfinite(upper):
|
|
||||||
step = max(1.0, abs(upper) * 0.1)
|
|
||||||
return (upper - step, upper - 2 * step)
|
|
||||||
return (-1.0, 1.0)
|
|
||||||
|
|
||||||
|
|
||||||
def _offer_probes(offer: PrimitiveOffer, extras: Sequence[float]) -> tuple[float, ...]:
|
|
||||||
"""Combine automatic and applicable explicit probes without duplicates."""
|
|
||||||
probes: list[float] = []
|
|
||||||
for parameter in (*_automatic_probes(offer), *extras):
|
|
||||||
try:
|
|
||||||
selected = offer.canonicalize_parameter(parameter)
|
|
||||||
except Exception:
|
|
||||||
continue
|
|
||||||
if not any(scalar_close(selected, previous) for previous in probes):
|
|
||||||
probes.append(selected)
|
|
||||||
return tuple(probes)
|
|
||||||
|
|
||||||
|
|
||||||
def _offer_metadata(offer: PrimitiveOffer) -> tuple[Any, ...]:
|
|
||||||
"""Return discovery metadata that must remain stable across repeated queries."""
|
|
||||||
cost_policy: tuple[str, Any]
|
|
||||||
if callable(offer.cost):
|
|
||||||
cost_policy = ('callable', type(offer.cost).__qualname__)
|
|
||||||
else:
|
|
||||||
cost_policy = ('factor', float(offer.cost))
|
|
||||||
return (
|
|
||||||
type(offer),
|
|
||||||
offer.kind,
|
|
||||||
offer.in_ptype,
|
|
||||||
offer.out_ptype,
|
|
||||||
tuple(float(value) for value in offer.parameter_domain),
|
|
||||||
getattr(offer, 'ccw', None),
|
|
||||||
cost_policy,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _evaluated_cost(offer: PrimitiveOffer, parameter: float, endpoint: Port) -> float:
|
|
||||||
"""Mirror the solver's one-endpoint base-cost path while honoring overrides."""
|
|
||||||
if type(offer).cost_at is PrimitiveOffer.cost_at:
|
|
||||||
return PrimitiveOffer._cost_for_endpoint(offer, parameter, endpoint)
|
|
||||||
return float(offer.cost_at(parameter))
|
|
||||||
|
|
||||||
|
|
||||||
def validate_tool_contract(tool: Tool, cases: Sequence[ToolContractCase]) -> None:
|
|
||||||
"""Validate Tool discovery, offer callbacks, and one-step rendering.
|
|
||||||
|
|
||||||
All independent violations are collected and raised as one
|
|
||||||
`ExceptionGroup` containing contextual `ToolContractError` instances.
|
|
||||||
"""
|
|
||||||
cases = tuple(cases)
|
|
||||||
if not cases:
|
|
||||||
raise ValueError('validate_tool_contract() requires at least one case')
|
|
||||||
|
|
||||||
errors: list[ToolContractError] = []
|
|
||||||
|
|
||||||
def violation(context: str, message: str, cause: Exception | None = None) -> None:
|
|
||||||
err = ToolContractError(f'{context}: {message}')
|
|
||||||
if cause is not None:
|
|
||||||
err.__cause__ = cause
|
|
||||||
errors.append(err)
|
|
||||||
|
|
||||||
def discover(case: ToolContractCase, context: str, repetition: str) -> tuple[PrimitiveOffer, ...] | None:
|
|
||||||
expected_offer_type = {
|
|
||||||
'straight': StraightOffer,
|
|
||||||
'bend': BendOffer,
|
|
||||||
's': SOffer,
|
|
||||||
'u': UOffer,
|
|
||||||
}[case.kind]
|
|
||||||
try:
|
|
||||||
kwargs = deepcopy(dict(case.tool_options))
|
|
||||||
if case.kind == 'bend':
|
|
||||||
kwargs['ccw'] = case.ccw
|
|
||||||
offers = tool.primitive_offers(
|
|
||||||
case.kind,
|
|
||||||
in_ptype=case.in_ptype,
|
|
||||||
out_ptype=case.out_ptype,
|
|
||||||
**kwargs,
|
|
||||||
)
|
|
||||||
except Exception as err:
|
|
||||||
violation(context, f'{repetition} discovery raised {type(err).__name__}: {err}', err)
|
|
||||||
return None
|
|
||||||
|
|
||||||
if not isinstance(offers, tuple):
|
|
||||||
violation(context, f'{repetition} discovery returned {type(offers).__name__}, expected tuple')
|
|
||||||
return None
|
|
||||||
valid = True
|
|
||||||
for offer_index, offer in enumerate(offers):
|
|
||||||
if not isinstance(offer, PrimitiveOffer):
|
|
||||||
violation(
|
|
||||||
context,
|
|
||||||
f'{repetition} discovery item {offer_index} is {type(offer).__name__}, expected PrimitiveOffer',
|
|
||||||
)
|
|
||||||
valid = False
|
|
||||||
elif offer.kind != case.kind:
|
|
||||||
violation(
|
|
||||||
context,
|
|
||||||
f'{repetition} discovery item {offer_index} has kind {offer.kind!r}, expected {case.kind!r}',
|
|
||||||
)
|
|
||||||
valid = False
|
|
||||||
elif not isinstance(offer, expected_offer_type):
|
|
||||||
violation(
|
|
||||||
context,
|
|
||||||
f'{repetition} discovery item {offer_index} is {type(offer).__name__}, '
|
|
||||||
f'expected {expected_offer_type.__name__}',
|
|
||||||
)
|
|
||||||
valid = False
|
|
||||||
return offers if valid else None
|
|
||||||
|
|
||||||
for case_index, case in enumerate(cases):
|
|
||||||
context = case.label or f'case {case_index} ({case.kind})'
|
|
||||||
first = discover(case, context, 'first')
|
|
||||||
second = discover(case, context, 'repeated')
|
|
||||||
if first is None or second is None:
|
|
||||||
continue
|
|
||||||
if case.require_offers and not first:
|
|
||||||
violation(context, 'discovery returned no offers')
|
|
||||||
if len(first) != len(second):
|
|
||||||
violation(context, f'discovery count changed from {len(first)} to {len(second)}')
|
|
||||||
|
|
||||||
matched_explicit = [False] * len(case.probe_parameters)
|
|
||||||
for offer_index, offer in enumerate(first):
|
|
||||||
offer_context = f'{context}, offer {offer_index}'
|
|
||||||
repeated = second[offer_index] if offer_index < len(second) else None
|
|
||||||
if repeated is not None and _offer_metadata(offer) != _offer_metadata(repeated):
|
|
||||||
violation(offer_context, 'discovery metadata changed between repeated queries')
|
|
||||||
|
|
||||||
probes = _offer_probes(offer, case.probe_parameters)
|
|
||||||
for explicit_index, parameter in enumerate(case.probe_parameters):
|
|
||||||
try:
|
|
||||||
offer.canonicalize_parameter(parameter)
|
|
||||||
except Exception:
|
|
||||||
continue
|
|
||||||
matched_explicit[explicit_index] = True
|
|
||||||
|
|
||||||
stable_ptype: str | None = None
|
|
||||||
stable_rotation: float | None = None
|
|
||||||
has_stable_endpoint = False
|
|
||||||
for parameter in probes:
|
|
||||||
probe_context = f'{offer_context}, parameter {parameter:g}'
|
|
||||||
try:
|
|
||||||
endpoint = offer.endpoint_at(parameter)
|
|
||||||
except Exception as err:
|
|
||||||
violation(probe_context, f'endpoint_at() raised {type(err).__name__}: {err}', err)
|
|
||||||
continue
|
|
||||||
if not isinstance(endpoint, Port):
|
|
||||||
violation(probe_context, f'endpoint_at() returned {type(endpoint).__name__}, expected Port')
|
|
||||||
continue
|
|
||||||
if not numpy.all(numpy.isfinite(endpoint.offset)):
|
|
||||||
violation(probe_context, 'endpoint offset must be finite')
|
|
||||||
if endpoint.rotation is None or not numpy.isfinite(endpoint.rotation):
|
|
||||||
violation(probe_context, 'endpoint rotation must be finite and specified')
|
|
||||||
if not ptypes_compatible(endpoint.ptype, offer.out_ptype):
|
|
||||||
violation(probe_context, 'endpoint ptype does not match declared out_ptype')
|
|
||||||
|
|
||||||
if offer.kind in ('straight', 'bend') and not scalar_close(endpoint.x, parameter):
|
|
||||||
violation(probe_context, 'straight/bend endpoint x must equal its parameter')
|
|
||||||
if offer.kind in ('s', 'u') and not scalar_close(endpoint.y, parameter):
|
|
||||||
violation(probe_context, 'S/U endpoint y must equal its parameter')
|
|
||||||
expected_rotation = {
|
|
||||||
'straight': pi,
|
|
||||||
'bend': -pi / 2 if isinstance(offer, BendOffer) and offer.ccw else pi / 2,
|
|
||||||
's': pi,
|
|
||||||
'u': 0.0,
|
|
||||||
}[offer.kind]
|
|
||||||
if endpoint.rotation is not None and not angles_equal(endpoint.rotation, expected_rotation):
|
|
||||||
violation(
|
|
||||||
probe_context,
|
|
||||||
f'endpoint rotation does not match {offer.kind!r} geometry',
|
|
||||||
)
|
|
||||||
|
|
||||||
if has_stable_endpoint:
|
|
||||||
if endpoint.ptype != stable_ptype:
|
|
||||||
violation(probe_context, 'endpoint ptype changes across the offer domain')
|
|
||||||
if (
|
|
||||||
endpoint.rotation is None
|
|
||||||
or stable_rotation is None
|
|
||||||
or not angles_equal(endpoint.rotation, stable_rotation)
|
|
||||||
):
|
|
||||||
violation(probe_context, 'endpoint rotation changes across the offer domain')
|
|
||||||
else:
|
|
||||||
stable_ptype = endpoint.ptype
|
|
||||||
stable_rotation = endpoint.rotation
|
|
||||||
has_stable_endpoint = True
|
|
||||||
|
|
||||||
try:
|
|
||||||
cost = float(_evaluated_cost(offer, parameter, endpoint))
|
|
||||||
if not numpy.isfinite(cost) or cost < 0:
|
|
||||||
violation(probe_context, f'cost must be finite and nonnegative, got {cost!r}')
|
|
||||||
except Exception as err:
|
|
||||||
violation(probe_context, f'cost_at() raised {type(err).__name__}: {err}', err)
|
|
||||||
cost = None
|
|
||||||
|
|
||||||
if repeated is not None:
|
|
||||||
try:
|
|
||||||
repeated_endpoint = repeated.endpoint_at(parameter)
|
|
||||||
repeated_cost = float(_evaluated_cost(repeated, parameter, repeated_endpoint))
|
|
||||||
if (
|
|
||||||
not isinstance(repeated_endpoint, Port)
|
|
||||||
or not array_close(repeated_endpoint.offset, endpoint.offset)
|
|
||||||
or repeated_endpoint.ptype != endpoint.ptype
|
|
||||||
or repeated_endpoint.rotation is None
|
|
||||||
or endpoint.rotation is None
|
|
||||||
or not angles_equal(repeated_endpoint.rotation, endpoint.rotation)
|
|
||||||
):
|
|
||||||
violation(probe_context, 'endpoint result changed after repeated discovery')
|
|
||||||
if cost is not None and not scalar_close(repeated_cost, cost):
|
|
||||||
violation(probe_context, 'cost result changed after repeated discovery')
|
|
||||||
except Exception as err:
|
|
||||||
violation(
|
|
||||||
probe_context,
|
|
||||||
f'repeated offer evaluation raised {type(err).__name__}: {err}',
|
|
||||||
err,
|
|
||||||
)
|
|
||||||
|
|
||||||
if case.check_bbox:
|
|
||||||
try:
|
|
||||||
offer.bbox_at(parameter)
|
|
||||||
except Exception as err:
|
|
||||||
violation(probe_context, f'bbox_at() raised {type(err).__name__}: {err}', err)
|
|
||||||
|
|
||||||
try:
|
|
||||||
data = offer.commit(parameter)
|
|
||||||
except Exception as err:
|
|
||||||
violation(probe_context, f'commit() raised {type(err).__name__}: {err}', err)
|
|
||||||
continue
|
|
||||||
|
|
||||||
try:
|
|
||||||
start = Port((0, 0), rotation=pi, ptype=offer.in_ptype or 'unk')
|
|
||||||
tree = tool.render((RenderStep(offer.kind, tool, start, endpoint.copy(), data),))
|
|
||||||
except Exception as err:
|
|
||||||
violation(probe_context, f'render() raised {type(err).__name__}: {err}', err)
|
|
||||||
continue
|
|
||||||
if not isinstance(tree, ILibrary):
|
|
||||||
violation(probe_context, f'render() returned {type(tree).__name__}, expected ILibrary')
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
top_name = tree.top()
|
|
||||||
pattern = tree.top_pattern()
|
|
||||||
except Exception as err:
|
|
||||||
violation(probe_context, f'rendered tree has no valid top cell: {err}', err)
|
|
||||||
continue
|
|
||||||
missing = sorted(
|
|
||||||
name
|
|
||||||
for name in tree.dangling_refs(top_name)
|
|
||||||
if isinstance(name, str) and name.startswith(SINGLE_USE_PREFIX)
|
|
||||||
)
|
|
||||||
if missing:
|
|
||||||
violation(probe_context, f'rendered tree has missing single-use refs: {missing}')
|
|
||||||
missing_ports = [name for name in ('A', 'B') if name not in pattern.ports]
|
|
||||||
if missing_ports:
|
|
||||||
violation(probe_context, f'rendered top cell is missing ports: {missing_ports}')
|
|
||||||
continue
|
|
||||||
input_port, output_port = pattern.ports['A'], pattern.ports['B']
|
|
||||||
if not ptypes_compatible(input_port.ptype, offer.in_ptype):
|
|
||||||
violation(probe_context, 'rendered input ptype does not match offer in_ptype')
|
|
||||||
try:
|
|
||||||
rendered_offset, rendered_rotation = input_port.measure_travel(output_port)
|
|
||||||
except Exception as err:
|
|
||||||
violation(probe_context, f'unable to measure rendered endpoint: {err}', err)
|
|
||||||
continue
|
|
||||||
if not array_close(rendered_offset, endpoint.offset):
|
|
||||||
violation(probe_context, 'rendered output offset does not match planned endpoint')
|
|
||||||
if (
|
|
||||||
rendered_rotation is None
|
|
||||||
or endpoint.rotation is None
|
|
||||||
or not angles_equal(rendered_rotation, endpoint.rotation)
|
|
||||||
):
|
|
||||||
violation(probe_context, 'rendered output rotation does not match planned endpoint')
|
|
||||||
if not ptypes_compatible(output_port.ptype, endpoint.ptype):
|
|
||||||
violation(probe_context, 'rendered output ptype does not match planned endpoint')
|
|
||||||
|
|
||||||
for parameter, matched in zip(case.probe_parameters, matched_explicit, strict=True):
|
|
||||||
if not matched:
|
|
||||||
violation(context, f'explicit probe {parameter:g} is outside every discovered offer domain')
|
|
||||||
|
|
||||||
if errors:
|
|
||||||
raise ExceptionGroup(
|
|
||||||
f'{type(tool).__name__} failed Tool contract validation with {len(errors)} violation(s)',
|
|
||||||
errors,
|
|
||||||
)
|
|
||||||
File diff suppressed because it is too large
Load diff
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue