Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 31b853be38 | |||
| 6a5b711e59 | |||
| 2026fdddf5 | |||
| 31211e03e7 | |||
| 6fee234a7e | |||
| 848fd95e2c | |||
| eb81101672 | |||
| d48c0f2879 | |||
| db96464111 | |||
| ac61b8bab7 | |||
| 70c4cb3589 | |||
| 890e7e5c0f | |||
| b62879b410 | |||
| 4d9aaf2fd9 | |||
| 1b84c87d9b | |||
| ce7463e57c | |||
| 91a5d63b57 | |||
| 1da5ac550a | |||
| ac34108253 | |||
| 4b0a899e17 | |||
| 2b6782c93e | |||
| e397b3f96e | |||
| 93dd3503ca | |||
| 29947c6c01 | |||
| 635f612630 | |||
| 95e54acf96 | |||
| cbf75319ad | |||
| 412133533a | |||
| 42d291b1b6 | |||
| e7f7cae8b9 | |||
| 7b589e4f44 | |||
| ddb7742493 | |||
| f9611933ac | |||
| 8712398990 | |||
| 0edd735a11 | |||
| 67afee7704 | |||
| 49713896c3 | |||
| 3a3cd854a5 | |||
| 09b131026f | |||
| 306f0b4c83 | |||
| fe4e2f760b | |||
| cf3f72b828 | |||
| 0230fb49a6 | |||
| 7083edc7ca | |||
| 520f37aa29 | |||
| 088c37e9d2 | |||
| 02a3708b30 | |||
| 4c64352152 | |||
| 9a39a436b2 | |||
| 84664303f1 | |||
| f864ebbeab | |||
| 54c4cd9a4a | |||
| b6c222cdc2 | |||
| 583bd5bd77 | |||
| 22e645e527 | |||
| 0f39ce8816 | |||
| 5e0cc0e20f | |||
| 1b83034b7e | |||
| 1723212424 | |||
| c420ac8085 | |||
| 08bbb10827 | |||
| 3dea61b05e | |||
| 0fba187d8c | |||
| 6d494142fe | |||
| e108199bcd | |||
| 151a7f846f | |||
| f3a60da30b | |||
| fd01e369e1 | |||
| c83846afb3 | |||
| e009417eed | |||
| 85aed4388e | |||
| f6ad86cdc2 | |||
| a279ccec21 | |||
| b6ee0d4929 | |||
| 4aca8acd3d | |||
| 46a15e2f0f | |||
| 8b7dd947fb | |||
| 262f2dee3a | |||
| 624d707123 | |||
| 29bd0f63e9 | |||
| d36a1a53e6 | |||
| 833f5dd159 | |||
| f4df8e0553 | |||
| 4d57936da8 | |||
| 51c7fa9add | |||
| e4a52b2c90 | |||
| e33a0f5ae1 | |||
| 950d144ead | |||
| d95ddbb6b9 | |||
| bdc4dfdd06 | |||
| 6cf9600193 | |||
| e6f5136357 | |||
| 778b3d9be7 | |||
| 02f0833fb3 | |||
| 47f150f579 | |||
| 84106dc355 | |||
| 429e687666 | |||
| c501a8ff99 | |||
| fd2698c503 | |||
| 8100d8095a | |||
| 2c5243237e | |||
| cf0a245143 | |||
| bbe3586ba9 | |||
| e071bd89b0 | |||
| 06ed2ce54a | |||
| 0f2b4d713b | |||
| 524503031c | |||
| ce7bf5ce70 | |||
| f0a4b08a31 | |||
| b3a1489258 | |||
| d366db5a62 | |||
| 20f37ea0f7 | |||
| 6fd73b9d46 | |||
| 32744512e0 | |||
| 75a9114709 | |||
| df578d7764 | |||
| 786716fc62 | |||
| a82365ec8c | |||
| 28be89f047 | |||
| afc49f945d | |||
| ce46cc18dc | |||
| 7c50f95fde | |||
| ae314cce93 | |||
| 09a95a6608 | |||
| fbe138d443 | |||
| 4b416745da | |||
| 0830dce50c | |||
| ac87179da2 | |||
| f0eea0382b | |||
| 0c9b435e94 | |||
| f461222852 | |||
| 9767ee4e62 | |||
| 395ad4df9d | |||
| 35b42c397b | |||
| 6a7b3b2259 | |||
| 8d50f497f1 | |||
| 2176d56b4c | |||
| f1e25debec | |||
| 4b07bb9e25 | |||
| 2952e6ef8f | |||
| c303a0c114 | |||
| f34b9b2f5c | |||
| 89cdd23f00 | |||
| 620b001af5 | |||
| 46a3559391 | |||
| 08421d6a54 | |||
| 462a05a665 | |||
| 2b29e46b93 | |||
| 2e0b64bdab | |||
| 20c845a881 | |||
| 707a16fe64 | |||
| 932565d531 | |||
| e7f847d4c7 | |||
| 3beadd2bf0 | |||
| 1bcf5901d6 | |||
| 56e401196a | |||
| 83ec64158a | |||
| aa7007881f | |||
| d03fafcaf6 | |||
| d3be6aeba3 | |||
| ffbe15c465 | |||
| b44c962e07 | |||
| 20bd0640e1 | |||
| 4ae8115139 | |||
| c2ef3e4217 | |||
| c32168dc64 | |||
| b843ffb4d3 | |||
| 9adfcac437 | |||
| 26cc0290b9 | |||
| 548b51df47 | |||
| 06f8611a90 | |||
| 9ede16df5d | |||
| add82e955d | |||
| cfec9e8c76 | |||
| 2275bf415a | |||
| fa3dfa1e74 | |||
| 75dc391540 | |||
| feb5d87cf4 | |||
| 5f91bd9c6c | |||
| db22237369 | |||
| a6ea5c08e6 | |||
| 3792248cd1 | |||
| e8083cc24c | |||
| d307589995 | |||
| ea93a7ef37 | |||
| 495babf837 | |||
| 5d20a061fd | |||
| 25b8fe8448 | |||
| f154303bef | |||
| 5596e2b1af | |||
| 6c42049b23 | |||
| da20922224 | |||
| b8ee4bb05d | |||
| 169f66cc85 | |||
| a38c5bb085 | |||
| 0ad89d6d95 | |||
| 6c96968341 | |||
| b7143e3287 | |||
| 0cce5e0586 | |||
| 36cb86a15d | |||
| 5e0936e15f | |||
| a467a0baca | |||
| 564ff10db3 | |||
| e261585894 | |||
| f42114bf43 | |||
| 5eb460ecb7 | |||
| fb822829ec | |||
| 838c742651 | |||
| 9a76ce5b66 | |||
| 2019fc0d74 | |||
| e3f8d28529 | |||
| 9296011d4b | |||
| 92d0140093 | |||
| c4dc9f9573 | |||
| 0b8e11e8bf | |||
| 5989e45906 | |||
| 7eec2b7acf | |||
| 2a6458b1ac | |||
| 9ee3c7ff89 | |||
| 3bedab2301 | |||
| 4eb1d8d486 | |||
| 3ceeba23b8 | |||
| 963103b859 | |||
| e5a6aab940 | |||
| 042941c838 | |||
| 0f63acbad0 | |||
| a0d7d0ed26 | |||
| d32a5ee762 | |||
| 19dafad157 | |||
| 5cb608734d | |||
| d0b48e6bfc | |||
| ef5c8c715e | |||
| 049864ddc7 | |||
| 3bf7efc404 | |||
| 74fa377450 | |||
| c3581243c8 | |||
| 338c123fb1 | |||
| a89f07c441 | |||
| bb7f4906af | |||
| 2513c7f8fd | |||
| ad4e9af59d | |||
| 46555dbd4d | |||
| 26e6a44559 | |||
| 32681edb47 | |||
| 84f37195ad | |||
| 0189756df4 | |||
| 1070815730 | |||
| 8a45c6d8d6 | |||
| 9d6fb985d8 | |||
| 69ac25078c | |||
| babbe78daa | |||
| 16875e9cd6 | |||
| 4332cf14c0 | |||
| ff8ca92963 | |||
| ed021e3d81 | |||
| 07a25ec290 | |||
| 504f89796c | |||
| 0f49924aa6 | |||
| ebfe1b559c | |||
| 7ad59d6b89 | |||
| 5d040061f4 | |||
| f42e720c68 | |||
| cf822c7dcf | |||
| 59e996e680 | |||
| abf236a046 | |||
| d40bdb1cb2 | |||
| 5e08579498 | |||
| c18e5b8d3e | |||
| 48f7569c1f | |||
| 8a56679884 | |||
| 1cce6c1f70 | |||
| d9adb4e1b9 | |||
| 1de76bff47 | |||
| 9bb0d5190d | |||
| ad49276345 | |||
| fe70d0574b | |||
| 36fed84249 | |||
| 278f0783da | |||
| 72f462d077 | |||
| 66d6fae2bd | |||
| 2b7ad00204 | |||
| 2d63e72802 | |||
| 51ced2fe83 | |||
| 19fac463e4 | |||
| 44986bac67 | |||
| accad3db9f | |||
| 05098c0c13 | |||
| f64b080b15 | |||
| 54f3b273bc | |||
| add0600bac | |||
| 737d41d592 | |||
| 395244ee83 | |||
| 43ccd8de2f | |||
| dfa0259997 | |||
| 37418d2137 | |||
| d8702af5b9 | |||
| 49e3917a6e | |||
| 48034b7a30 | |||
| 28e2864ce1 | |||
| ba2bc2b444 | |||
| 05b73066ea | |||
| f7138ee8e4 | |||
| dca0df940b | |||
| c18249c4d5 | |||
| fc963cfbfc | |||
| c366add952 | |||
| 84629ea614 | |||
| fdd776f4d7 | |||
| 0f8078127d | |||
| 48ccf3e148 | |||
| 88a3d261aa | |||
| c1c83afc98 | |||
| f8a82336f6 | |||
| 62a030dd14 | |||
| 7ca3dd5b09 | |||
| d46be245c6 | |||
| 54cddaddd9 | |||
| 1c7ee9bef4 | |||
| 7c928a59fa | |||
| bc8c0ee580 | |||
| d3216c680c | |||
| 3593b4aec7 | |||
| e8e630bb2f | |||
| feba7c699d | |||
| 70559308a1 | |||
| 021142533d | |||
| b1c838c8fd | |||
| 7c033edc21 | |||
| 601773d17e | |||
| cf92cc06b3 | |||
| fcb622441b | |||
| 2e57724095 | |||
| a69860ad9c | |||
| 82f3e7ab8f | |||
| a308b1515a | |||
| 38d4c4b6af | |||
| 4822ae8708 | |||
| d00899bb39 | |||
| a908fadfc3 | |||
| 92875cfdb6 | |||
| 11306dbb56 | |||
| fc9d4c6ba2 | |||
| 8fa1d0479c | |||
| a4b93419b4 | |||
| 549193534f | |||
| 6a494b99a0 | |||
| 705a1cef78 | |||
| b8ab3b91f5 | |||
| 34a43a707c | |||
| aca49dc7e3 | |||
| e231fa89cb | |||
| 0c04bf8ea3 | |||
| e5f0c85560 | |||
| 2961ae5471 | |||
| ba05e40f84 | |||
| 314910d363 | |||
| fbe804750b | |||
| aee0d5b619 | |||
| e00d82bbc4 | |||
| 4d74eea253 | |||
| 325a8b9590 | |||
| c071b33732 | |||
| 42a7df3055 | |||
| 5e0eef7c59 | |||
| ad00ade097 | |||
| 385a37e0a2 | |||
| 35e28acb89 | |||
| c1bfee1ddd | |||
| 560c165f2e | |||
| 284c7e4fd0 | |||
| 1eac3baf6a | |||
| 5a4b9609bd |
142 changed files with 31460 additions and 4258 deletions
856
MIGRATION.md
Normal file
856
MIGRATION.md
Normal file
|
|
@ -0,0 +1,856 @@
|
||||||
|
# Migration Guide
|
||||||
|
|
||||||
|
This guide covers changes between the `master` branch and the current tree.
|
||||||
|
Both `master` and the current tree report `masque.__version__ == '3.4'`; the
|
||||||
|
version string has not yet been bumped for these changes.
|
||||||
|
|
||||||
|
Most downstream changes are in `masque/builder/*`, but there are a few other
|
||||||
|
API changes that may require code updates.
|
||||||
|
|
||||||
|
## Routing API: renamed and consolidated
|
||||||
|
|
||||||
|
The routing helpers were consolidated into a single implementation in
|
||||||
|
`masque/builder/pather.py`.
|
||||||
|
|
||||||
|
The biggest migration point is that the old routing verbs were renamed:
|
||||||
|
|
||||||
|
| Old API | New API |
|
||||||
|
| --- | --- |
|
||||||
|
| `Pather.path(...)` | `Pather.trace(...)` |
|
||||||
|
| `Pather.path_to(...)` | `Pather.trace_to(...)` |
|
||||||
|
| `Pather.mpath(...)` | `Pather.trace(...)` / `Pather.trace_to(...)` with multiple ports |
|
||||||
|
| `Pather.pathS(...)` | `Pather.jog(...)` |
|
||||||
|
| `Pather.pathU(...)` | `Pather.uturn(...)` |
|
||||||
|
| `Pather.path_into(...)` | `Pather.trace_into(...)` |
|
||||||
|
| `Pather.path_from(src, dst)` | `Pather.at(src).trace_into(dst)` |
|
||||||
|
| `RenderPather.path(...)` | `Pather(..., render='deferred').trace(...)` |
|
||||||
|
| `RenderPather.path_to(...)` | `Pather(..., render='deferred').trace_to(...)` |
|
||||||
|
| `RenderPather.mpath(...)` | `Pather(..., render='deferred').trace(...)` / `Pather(..., render='deferred').trace_to(...)` |
|
||||||
|
| `RenderPather.pathS(...)` | `Pather(..., render='deferred').jog(...)` |
|
||||||
|
| `RenderPather.pathU(...)` | `Pather(..., render='deferred').uturn(...)` |
|
||||||
|
| `RenderPather.path_into(...)` | `Pather(..., render='deferred').trace_into(...)` |
|
||||||
|
| `RenderPather.path_from(src, dst)` | `Pather(..., render='deferred').at(src).trace_into(dst)` |
|
||||||
|
|
||||||
|
There are also new convenience wrappers:
|
||||||
|
|
||||||
|
- `straight(...)` for `trace_to(..., ccw=None, ...)`
|
||||||
|
- `ccw(...)` for `trace_to(..., ccw=True, ...)`
|
||||||
|
- `cw(...)` for `trace_to(..., ccw=False, ...)`
|
||||||
|
- `jog(...)` for S-bends
|
||||||
|
- `uturn(...)` for U-bends
|
||||||
|
|
||||||
|
Important: `Pather.path()` is no longer the routing API. It now forwards to
|
||||||
|
`Pattern.path()` and creates a geometric `Path` element. Any old routing code
|
||||||
|
that still calls `pather.path(...)` must be renamed.
|
||||||
|
|
||||||
|
### Common rewrites
|
||||||
|
|
||||||
|
```python
|
||||||
|
# old
|
||||||
|
pather.path('VCC', False, 6_000)
|
||||||
|
pather.path_to('VCC', None, x=0)
|
||||||
|
pather.mpath(['GND', 'VCC'], True, xmax=-10_000, spacing=5_000)
|
||||||
|
pather.pathS('VCC', offset=-2_000, length=8_000)
|
||||||
|
pather.pathU('VCC', offset=4_000, length=5_000)
|
||||||
|
pather.path_into('src', 'dst')
|
||||||
|
pather.path_from('src', 'dst')
|
||||||
|
|
||||||
|
# new
|
||||||
|
pather.cw('VCC', 6_000)
|
||||||
|
pather.straight('VCC', x=0)
|
||||||
|
pather.ccw(['GND', 'VCC'], xmax=-10_000, spacing=5_000)
|
||||||
|
pather.jog('VCC', offset=-2_000, length=8_000)
|
||||||
|
pather.uturn('VCC', offset=4_000, length=5_000)
|
||||||
|
pather.trace_into('src', 'dst')
|
||||||
|
pather.at('src').trace_into('dst')
|
||||||
|
```
|
||||||
|
|
||||||
|
If you prefer the more explicit spelling, `trace(...)` and `trace_to(...)`
|
||||||
|
remain the underlying primitives:
|
||||||
|
|
||||||
|
```python
|
||||||
|
pather.trace('VCC', False, 6_000)
|
||||||
|
pather.trace_to('VCC', None, x=0)
|
||||||
|
```
|
||||||
|
|
||||||
|
## `PortPather` and `.at(...)`
|
||||||
|
|
||||||
|
Routing can now be written in a fluent style via `.at(...)`, which returns a
|
||||||
|
`PortPather`.
|
||||||
|
|
||||||
|
```python
|
||||||
|
(rpather.at('VCC')
|
||||||
|
.trace(False, length=6_000)
|
||||||
|
.trace_to(None, x=0)
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
This is additive, not required for migration. Existing code can stay with the
|
||||||
|
non-fluent `Pather` methods after renaming the verbs above.
|
||||||
|
|
||||||
|
Old `PortPather` helper names were also cleaned up:
|
||||||
|
|
||||||
|
| Old API | New API |
|
||||||
|
| --- | --- |
|
||||||
|
| `save_copy(...)` | `mark(...)` |
|
||||||
|
| `rename_to(...)` | `rename(...)` |
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
```python
|
||||||
|
# old
|
||||||
|
pp.save_copy('branch')
|
||||||
|
pp.rename_to('feed')
|
||||||
|
|
||||||
|
# new
|
||||||
|
pp.mark('branch')
|
||||||
|
pp.rename('feed')
|
||||||
|
```
|
||||||
|
|
||||||
|
## Imports and module layout
|
||||||
|
|
||||||
|
`Pather` now provides the remaining builder/routing surface in
|
||||||
|
`masque/builder/pather.py`. The old module files
|
||||||
|
`masque/builder/builder.py` and `masque/builder/renderpather.py` were removed.
|
||||||
|
|
||||||
|
Update imports like this:
|
||||||
|
|
||||||
|
```python
|
||||||
|
# old
|
||||||
|
from masque.builder.builder import Builder
|
||||||
|
from masque.builder.renderpather import RenderPather
|
||||||
|
|
||||||
|
# new
|
||||||
|
from masque.builder import Pather
|
||||||
|
|
||||||
|
builder = Pather(...)
|
||||||
|
deferred = Pather(..., render='deferred')
|
||||||
|
```
|
||||||
|
|
||||||
|
The new `Pather` remains importable from both `masque` and `masque.builder`.
|
||||||
|
The removed `Builder` and `RenderPather` names are no longer exported from
|
||||||
|
either location.
|
||||||
|
|
||||||
|
`Pather` now defaults to `render='auto'`, so plain construction replaces the
|
||||||
|
old `Builder` behavior. Use `Pather(..., render='deferred')` where you
|
||||||
|
previously used `RenderPather`.
|
||||||
|
|
||||||
|
## `SimpleTool` was removed and `AutoTool` registration changed
|
||||||
|
|
||||||
|
`SimpleTool` is no longer exported. `AutoTool` remains, but its old public
|
||||||
|
descriptor classes and constructor-oriented configuration were replaced by
|
||||||
|
registration methods. Use it for generated straights and S-bends and reusable
|
||||||
|
bends, U-turns, and transitions.
|
||||||
|
|
||||||
|
### Old `AutoTool`
|
||||||
|
|
||||||
|
```python
|
||||||
|
from masque.builder import AutoTool
|
||||||
|
|
||||||
|
tool = AutoTool(
|
||||||
|
straights=[
|
||||||
|
AutoTool.Straight('m1wire', make_straight, 'input', 'output'),
|
||||||
|
],
|
||||||
|
bends=[
|
||||||
|
AutoTool.Bend(lib.abstract('bend'), 'input', 'output'),
|
||||||
|
],
|
||||||
|
sbends=[],
|
||||||
|
transitions={
|
||||||
|
('m2wire', 'm1wire'): AutoTool.Transition(
|
||||||
|
lib.abstract('via'), 'top', 'bottom'
|
||||||
|
),
|
||||||
|
},
|
||||||
|
default_out_ptype='m1wire',
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### New `AutoTool`
|
||||||
|
|
||||||
|
```python
|
||||||
|
from masque.builder import AutoTool
|
||||||
|
|
||||||
|
tool = (
|
||||||
|
AutoTool()
|
||||||
|
.add_straight(make_straight, 'm1wire', 'input')
|
||||||
|
.add_bend(lib.abstract('bend'), 'input', 'output', clockwise=True)
|
||||||
|
.add_transition(lib.abstract('via'), 'top', 'bottom')
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
The key differences are:
|
||||||
|
|
||||||
|
- `SimpleTool` was removed; use `AutoTool` or implement the new `Tool`
|
||||||
|
primitive-offer interface
|
||||||
|
- `AutoTool.Straight(...)` -> `add_straight(fn, ptype, in_name)`
|
||||||
|
- `AutoTool.Bend(...)` -> `add_bend(abstract, in_name, out_name)`
|
||||||
|
- `AutoTool.SBend(...)` -> `add_sbend(fn, ptype, in_name, out_name)`
|
||||||
|
- reusable native U-turns can be registered with `add_uturn(...)`
|
||||||
|
- transitions are registered with `add_transition(abstract, external_port, internal_port)`
|
||||||
|
- transitions are bidirectional by default; pass `one_way=True` to inhibit the reverse adapter
|
||||||
|
|
||||||
|
Primitive costs are now explicit and independent of `AutoTool` registration
|
||||||
|
order. Every `add_*()` method accepts `cost=`, as do the concrete offer
|
||||||
|
factories. A numeric value scales the default geometric cost; for example,
|
||||||
|
`cost=2` makes a primitive twice as expensive. A callable receives the
|
||||||
|
canonical primitive parameter and local endpoint and returns the complete
|
||||||
|
cost:
|
||||||
|
|
||||||
|
```python
|
||||||
|
tool.add_straight(make_straight, 'm1wire', 'input', cost=1.5)
|
||||||
|
tool.add_sbend(
|
||||||
|
make_sbend,
|
||||||
|
'm1wire',
|
||||||
|
'input',
|
||||||
|
'output',
|
||||||
|
cost=lambda jog, endpoint: abs(jog) + 2 * abs(endpoint.x),
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
`PrimitiveOffer.priority_bias` was removed; custom offers should use `cost`
|
||||||
|
instead. Exact equal-cost candidates still use deterministic discovery order
|
||||||
|
as the final tie-break, but registration order no longer changes their
|
||||||
|
reported cost.
|
||||||
|
|
||||||
|
For two-port primitives, `AutoTool` can infer omitted port names and, for
|
||||||
|
generated straight/S-bend primitives, omitted ptype metadata by sampling an
|
||||||
|
in-domain example. Supply those values explicitly when generation requires
|
||||||
|
route-specific keyword arguments, because metadata inference does not receive
|
||||||
|
`tool_options`.
|
||||||
|
|
||||||
|
## Custom `Tool` subclasses
|
||||||
|
|
||||||
|
If you maintain your own `Tool` subclass, the interface changed:
|
||||||
|
|
||||||
|
- `primitive_offers()` is now the planning boundary
|
||||||
|
- `render()` consumes committed primitive render tokens
|
||||||
|
- `Tool.path(...)`, `traceL()`, `traceS()`, `traceU()`, `planL()`,
|
||||||
|
`planS()`, and `planU()` are no longer part of the public `Tool` API
|
||||||
|
|
||||||
|
In practice, a minimal old implementation like:
|
||||||
|
|
||||||
|
```python
|
||||||
|
class MyTool(Tool):
|
||||||
|
def path(self, ccw, length, **kwargs):
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
should now become:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from masque import Port
|
||||||
|
from masque.builder import RenderStep, StraightOffer, Tool
|
||||||
|
|
||||||
|
|
||||||
|
class MyTool(Tool):
|
||||||
|
def primitive_offers(self, kind, *, in_ptype=None, out_ptype=None, **kwargs):
|
||||||
|
if kind != 'straight':
|
||||||
|
return ()
|
||||||
|
|
||||||
|
def endpoint(length):
|
||||||
|
ptype = out_ptype or in_ptype
|
||||||
|
return Port((length, 0), rotation=3.141592653589793, ptype=ptype)
|
||||||
|
|
||||||
|
def commit(length):
|
||||||
|
return {'length': length}
|
||||||
|
|
||||||
|
return (StraightOffer(
|
||||||
|
in_ptype=in_ptype,
|
||||||
|
out_ptype=out_ptype or in_ptype,
|
||||||
|
endpoint_planner=endpoint,
|
||||||
|
commit_planner=commit,
|
||||||
|
),)
|
||||||
|
|
||||||
|
def render(self, batch: Sequence[RenderStep]):
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
If a tool does not provide a primitive kind, return `()` for that kind. `Pather`
|
||||||
|
will compose available primitive offers where the route family allows it.
|
||||||
|
|
||||||
|
### Primitive offers
|
||||||
|
|
||||||
|
Tools describe legal routing primitives through `Tool.primitive_offers()`.
|
||||||
|
`Pather` composes those primitive offers to implement `trace()`, `jog()`,
|
||||||
|
`uturn()`, and `trace_into()`.
|
||||||
|
|
||||||
|
For custom tools, construct the concrete offer class that matches the primitive
|
||||||
|
you are exposing:
|
||||||
|
|
||||||
|
- `StraightOffer` for non-turning length-parameterized primitives
|
||||||
|
- `BendOffer` for single-turn length-parameterized primitives
|
||||||
|
- `SOffer` for S-like jog-parameterized primitives
|
||||||
|
- `UOffer` for U-like jog-parameterized primitives
|
||||||
|
|
||||||
|
`PrimitiveOffer` is the shared base type used for generic annotations and
|
||||||
|
common callback behavior. It is not the normal class users should instantiate.
|
||||||
|
The concrete offer classes carry the semantic fields (`length_domain`,
|
||||||
|
`jog_domain`, `ccw`) so tools do not need to encode primitive identity in
|
||||||
|
strings. Each concrete offer now also exposes a class-level canonical `kind`.
|
||||||
|
Tools must return the matching offer kind for the discovery query; for example,
|
||||||
|
`primitive_offers('s', ...)` must return only `SOffer` instances. Mismatches are
|
||||||
|
reported as fatal `ToolContractError`s rather than silently ignored.
|
||||||
|
|
||||||
|
`RenderStep` now stores that same canonical kind. Code that constructs render
|
||||||
|
steps directly must use the kind rather than a legacy opcode:
|
||||||
|
|
||||||
|
```python
|
||||||
|
# old
|
||||||
|
RenderStep('L', tool, start, end, data)
|
||||||
|
|
||||||
|
# new
|
||||||
|
RenderStep('straight', tool, start, end, data)
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `'bend'`, `'s'`, `'u'`, or `'plug'` for the other step types. The read-only
|
||||||
|
`RenderStep.opcode` and `PrimitiveOffer.opcode` properties remain available for
|
||||||
|
code that only consumes steps, but opcodes are now derived rather than stored.
|
||||||
|
|
||||||
|
Minimal straight-only example:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
from masque import Port
|
||||||
|
from masque.builder import RenderStep, StraightOffer, Tool
|
||||||
|
|
||||||
|
|
||||||
|
class MyTool(Tool):
|
||||||
|
def primitive_offers(
|
||||||
|
self,
|
||||||
|
kind: Literal['straight', 'bend', 's', 'u'],
|
||||||
|
*,
|
||||||
|
in_ptype=None,
|
||||||
|
out_ptype=None,
|
||||||
|
**kwargs,
|
||||||
|
):
|
||||||
|
if kind != 'straight':
|
||||||
|
return ()
|
||||||
|
|
||||||
|
def endpoint(length):
|
||||||
|
ptype = out_ptype or in_ptype
|
||||||
|
return Port((length, 0), rotation=3.141592653589793, ptype=ptype)
|
||||||
|
|
||||||
|
def commit(length):
|
||||||
|
return {'length': length}
|
||||||
|
|
||||||
|
return (StraightOffer(
|
||||||
|
in_ptype=in_ptype,
|
||||||
|
out_ptype=out_ptype or in_ptype,
|
||||||
|
endpoint_planner=endpoint,
|
||||||
|
commit_planner=commit,
|
||||||
|
),)
|
||||||
|
|
||||||
|
def render(self, batch: Sequence[RenderStep]):
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
Routing entry points now name every supported route argument explicitly.
|
||||||
|
Custom per-route Tool values must be placed under `tool_options`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
pather.jog('A', 4, length=10, tool_options={'process_corner': 'slow'})
|
||||||
|
```
|
||||||
|
|
||||||
|
The mapping is unpacked only for `Tool.primitive_offers()`. Route arguments do
|
||||||
|
not leak into that namespace, and tool options are not forwarded to
|
||||||
|
`Tool.render()`. An offer that needs route-specific render behavior must capture
|
||||||
|
the selected value in its `commit()` result (`RenderStep.data`). `AutoTool`
|
||||||
|
does this automatically for generated straight and S-bend primitives: the
|
||||||
|
mapping is deep-copied per offer discovery and passed to its generator as
|
||||||
|
keyword arguments during rendering. Consequently every AutoTool option value
|
||||||
|
must be deep-copyable, and later mutation of nested caller-owned values does
|
||||||
|
not affect a pending route. AutoTool options must not change generated
|
||||||
|
ports or endpoint geometry. `PathTool` defines no tool options and rejects
|
||||||
|
nonempty mappings.
|
||||||
|
|
||||||
|
AutoTool does not validate generator keyword signatures during planning. A bad
|
||||||
|
keyword therefore raises when the generator runs, normally during rendering.
|
||||||
|
Generators that require route options must provide explicit port metadata at
|
||||||
|
registration; S-bend generators must also provide an explicit `endpoint`.
|
||||||
|
|
||||||
|
Primitive offers are local planning objects:
|
||||||
|
|
||||||
|
- `endpoint_at(parameter)` returns the local output `Port`
|
||||||
|
- `cost_at(parameter)` returns an additive scalar route-selection cost
|
||||||
|
- `bbox_at(parameter)` returns local primitive bounds when a footprint hook is supplied
|
||||||
|
- `parameterized_bbox` may carry opaque future-router footprint metadata
|
||||||
|
- `commit(parameter)` returns opaque render data consumed later by `render()`
|
||||||
|
- `(min, max)` parameter domains are half-open; `(value, value)` is a fixed singleton
|
||||||
|
- domains are validated when an offer is constructed, not when it is first evaluated
|
||||||
|
- selected parameter values must be finite; domains may use infinite open bounds but not `NaN`
|
||||||
|
- straight/bend domains require a finite nonnegative minimum; fixed singleton domains must be finite
|
||||||
|
- `None` and `"unk"` ptypes are wildcards; concrete ptype mismatches reject an offer
|
||||||
|
|
||||||
|
`AutoTool.add_straight(length_range=...)` and
|
||||||
|
`AutoTool.add_sbend(jog_range=...)` now validate their ranges before metadata
|
||||||
|
inference. `jog_range` is an absolute-magnitude range and must have a finite,
|
||||||
|
nonnegative lower bound; AutoTool creates the corresponding positive and
|
||||||
|
negative S offers itself. Invalid ranges now raise immediately instead of
|
||||||
|
registering no offers.
|
||||||
|
|
||||||
|
`ToolContractError` is exported from `masque` and `masque.builder`. It marks a
|
||||||
|
broken Tool contract—such as an endpoint ptype that disagrees with its offer,
|
||||||
|
an invalid evaluated cost, or rendered output that disagrees with the planned
|
||||||
|
endpoint—and is fatal to route fallback. Ordinary `BuildError` raised by a
|
||||||
|
planning callback remains a recoverable candidate rejection. Rendered output
|
||||||
|
rotations are compared modulo one full turn; a port facing exactly backward is
|
||||||
|
no longer accepted as equivalent. A `None` rotation remains an explicit
|
||||||
|
wildcard.
|
||||||
|
|
||||||
|
Custom Tool authors can exercise discovery, offer callbacks, committed data,
|
||||||
|
and one-step rendering without depending on pytest:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from masque.builder import ToolContractCase, validate_tool_contract
|
||||||
|
|
||||||
|
validate_tool_contract(my_tool, (
|
||||||
|
ToolContractCase('straight', in_ptype='wire', probe_parameters=(10,)),
|
||||||
|
ToolContractCase('bend', in_ptype='wire', ccw=False),
|
||||||
|
ToolContractCase('bend', in_ptype='wire', ccw=True),
|
||||||
|
ToolContractCase('s', in_ptype='wire', require_offers=False),
|
||||||
|
))
|
||||||
|
```
|
||||||
|
|
||||||
|
Cases derive representative parameters from each returned offer domain and
|
||||||
|
may add explicit probes. Empty discovery is an error unless
|
||||||
|
`require_offers=False`; bbox support is required only with `check_bbox=True`.
|
||||||
|
Validation returns normally on success and otherwise raises an
|
||||||
|
`ExceptionGroup` of contextual `ToolContractError`s.
|
||||||
|
|
||||||
|
Run this validation during Tool development, testing, or application startup.
|
||||||
|
It is the comprehensive semantic preflight for custom Tools; those checks are
|
||||||
|
intentionally not repeated for every offer evaluation in the routing hot path.
|
||||||
|
|
||||||
|
Positional routing bounds (`p`, `pos`, `position`, `x`, and `y`) now require a
|
||||||
|
nearly Manhattan input-port direction. Arbitrarily angled ports remain valid
|
||||||
|
for non-positional/extension routing.
|
||||||
|
|
||||||
|
Heterogeneous `StraightOffer` and `SOffer` objects may be used as ptype
|
||||||
|
adapters. Requested `out_ptype` constrains only the final route endpoint; any
|
||||||
|
intermediate ptypes are chosen by the route solver.
|
||||||
|
|
||||||
|
`Tool` subclasses must override `primitive_offers()` and return `()` themselves
|
||||||
|
for recognized unsupported kinds. There is no route-level `plan*()` fallback.
|
||||||
|
Omitted-length S/U behavior comes from direct `SOffer` and `UOffer` endpoint
|
||||||
|
domains or from composed straight/bend primitives.
|
||||||
|
|
||||||
|
Offer constructors accept split `endpoint_planner` and `commit_planner`
|
||||||
|
callbacks. Provide both callbacks or override the offer methods in a subclass;
|
||||||
|
partial callback configurations are rejected during offer construction.
|
||||||
|
|
||||||
|
When writing direct primitive offers, declare the actual endpoint ptype
|
||||||
|
produced by the offer if it can differ from the requested value; `Pather`
|
||||||
|
validates evaluated endpoints against the declared offer ptype.
|
||||||
|
|
||||||
|
Stable imports for custom tool authors live in `masque.builder`. The
|
||||||
|
`masque.builder.planner` module is an internal planner implementation; do not
|
||||||
|
import it from user code.
|
||||||
|
|
||||||
|
`trace_into()` uses the same primitive-offer route selection and defaults to
|
||||||
|
the minimal main-route bend count required by the endpoint relationship: zero
|
||||||
|
for a straight, one for a quarter-turn, and two for S- and U-like connections.
|
||||||
|
Ptype adapters do not consume this bend budget. Set
|
||||||
|
`plan_options={'bend_policy': 'flexible'}` to search bounded route topologies
|
||||||
|
with up to four bend roles, including dogleg and loop-like fallbacks.
|
||||||
|
Bend-family requests then search one-bend routes before three-bend routes;
|
||||||
|
other families search zero-to-two-bend routes before four-bend routes. The
|
||||||
|
first band with a legal route wins. Within that band, candidates are ordered
|
||||||
|
by total primitive-offer cost, adapter count, step count, and deterministic
|
||||||
|
discovery order. The default planner's `strategy` option affects only that
|
||||||
|
final discovery-order tie-break and is also supplied through `plan_options`.
|
||||||
|
|
||||||
|
`plan_options` is reserved for planner-specific per-route policy, while
|
||||||
|
`tool_options` is forwarded only to `Tool.primitive_offers()`. For example:
|
||||||
|
|
||||||
|
```python
|
||||||
|
pather.jog('A', 4, length=10, plan_options={'strategy': 'turn_first'})
|
||||||
|
```
|
||||||
|
|
||||||
|
Explicit-length `jog()` routes may also be satisfied by composing a straight
|
||||||
|
primitive before or after an omitted-length native S primitive. `uturn()` routes
|
||||||
|
may compose a straight primitive before an omitted-length native U primitive.
|
||||||
|
These compositions are used when they are the lowest-cost legal route for the
|
||||||
|
explicit request.
|
||||||
|
|
||||||
|
`AutoTool` can attach `bbox_at()` hooks to its primitive offers by rendering the
|
||||||
|
selected primitive into a temporary pattern and measuring it. If the rendered
|
||||||
|
primitive contains reusable refs, pass the source library as `bbox_library=...`;
|
||||||
|
normal routing does not require this.
|
||||||
|
|
||||||
|
### Omitted-length routing
|
||||||
|
|
||||||
|
Single-port omitted-length calls now evaluate legal primitive routes at their
|
||||||
|
minimum legal length-like parameter, or at their intrinsic endpoint length when
|
||||||
|
the requested offset fixes the primitive geometry. Cost then selects among
|
||||||
|
those minimum-length candidates:
|
||||||
|
|
||||||
|
```python
|
||||||
|
pather.trace('A', None) # minimum straight-like route
|
||||||
|
pather.jog('A', offset=2) # minimum S-like route for that offset
|
||||||
|
pather.uturn('A', offset=4) # minimum U-like route for that offset
|
||||||
|
```
|
||||||
|
|
||||||
|
For U-turns, use explicit `length=0` to request the old zero-public-length
|
||||||
|
shape:
|
||||||
|
|
||||||
|
```python
|
||||||
|
pather.uturn('A', offset=4, length=0)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Transform semantics changed
|
||||||
|
|
||||||
|
The other major user-visible change is that `mirror()` and `rotate()` are now
|
||||||
|
treated more consistently as intrinsic transforms on low-level objects.
|
||||||
|
|
||||||
|
The practical migration rule is:
|
||||||
|
|
||||||
|
- use `mirror()` / `rotate()` when you want to change the object relative to its
|
||||||
|
own origin
|
||||||
|
- use `flip_across(...)`, `rotate_around(...)`, or container-level transforms
|
||||||
|
when you want to move the object in its parent coordinate system
|
||||||
|
|
||||||
|
### Example: `Port`
|
||||||
|
|
||||||
|
Old behavior:
|
||||||
|
|
||||||
|
```python
|
||||||
|
port.mirror(0) # changed both offset and orientation
|
||||||
|
```
|
||||||
|
|
||||||
|
New behavior:
|
||||||
|
|
||||||
|
```python
|
||||||
|
port.mirror(0) # changes orientation only
|
||||||
|
port.flip_across(axis=0) # old "mirror in the parent pattern" behavior
|
||||||
|
```
|
||||||
|
|
||||||
|
### What to audit
|
||||||
|
|
||||||
|
Check code that calls:
|
||||||
|
|
||||||
|
- `Port.mirror(...)`
|
||||||
|
- `Ref.rotate(...)`
|
||||||
|
- `Ref.mirror(...)`
|
||||||
|
- `Label.rotate_around(...)` / `Label.mirror(...)`
|
||||||
|
- `Abstract.mirror_port_offsets(...)` / `Abstract.mirror_ports(...)`
|
||||||
|
|
||||||
|
If that code expected offsets or repetition grids to move automatically, it
|
||||||
|
needs updating. For whole-pattern transforms, prefer calling `Pattern.mirror()`
|
||||||
|
or `Pattern.rotate_around(...)` at the container level.
|
||||||
|
|
||||||
|
`Abstract.mirror_port_offsets()` and `Abstract.mirror_ports()` were removed.
|
||||||
|
Use `Abstract.mirror(axis)` to mirror both port locations and orientations. If
|
||||||
|
you intentionally need only one half of that operation, update the individual
|
||||||
|
ports explicitly with `Port.flip_across(...)` or `Port.mirror(...)`.
|
||||||
|
|
||||||
|
## Library hierarchy and graph behavior
|
||||||
|
|
||||||
|
`masque/library.py` was split into the `masque.library` package. Imports from
|
||||||
|
the public module remain stable:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from masque import Library, LazyLibrary
|
||||||
|
# or
|
||||||
|
from masque.library import Library, LazyLibrary
|
||||||
|
```
|
||||||
|
|
||||||
|
Code importing the implementation file itself must move to the public package;
|
||||||
|
do not depend on the new internal `base`, `mapping`, or `lazy` module paths.
|
||||||
|
|
||||||
|
Hierarchy helpers now handle dangling references explicitly. The following
|
||||||
|
methods accept `dangling='error' | 'ignore' | 'include'` and default to
|
||||||
|
`'error'`:
|
||||||
|
|
||||||
|
- `child_graph()`
|
||||||
|
- `parent_graph()`
|
||||||
|
- `child_order()`
|
||||||
|
- `find_refs_local()`
|
||||||
|
- `find_refs_global()`
|
||||||
|
- `prune_empty()`
|
||||||
|
|
||||||
|
On `master`, graph construction could expose missing targets implicitly or
|
||||||
|
fail later with a `KeyError`. If dangling refs are intentional, choose the
|
||||||
|
behavior explicitly, for example:
|
||||||
|
|
||||||
|
```python
|
||||||
|
graph = library.child_graph(dangling='include')
|
||||||
|
order = library.child_order(dangling='ignore')
|
||||||
|
```
|
||||||
|
|
||||||
|
Graph cycles and invalid hierarchy states are now reported as `LibraryError`
|
||||||
|
with context. Audit code that caught `KeyError` or `graphlib.CycleError` from
|
||||||
|
these helpers.
|
||||||
|
|
||||||
|
Invalid `dangling=` strings now raise `ValueError`; they no longer fall through
|
||||||
|
to the `include` behavior. Empty lists stored in `Pattern.refs` are consistently
|
||||||
|
treated as absent references by hierarchy and geometry traversal. Code that
|
||||||
|
uses a `defaultdict` lookup such as `pattern.refs[name]` without appending a
|
||||||
|
`Ref` will therefore not create an edge or force that target to be loaded.
|
||||||
|
|
||||||
|
`Library.add()` now resolves the full name plan and remaps references before it
|
||||||
|
starts inserting cells. Name-resolution and preparation failures no longer
|
||||||
|
leave partially-added cells behind. A `rename_theirs` callback now receives an
|
||||||
|
`INameView` containing both existing names and names reserved earlier in the
|
||||||
|
same addition. Use membership, iteration, `len()`, or `get_name()`; the callback
|
||||||
|
argument is not the destination object and does not support pattern lookup or
|
||||||
|
mapping helpers such as `keys()` and `items()`. Update callback annotations from
|
||||||
|
`ILibraryView` to `INameView`. Custom `_merge()` implementations remain
|
||||||
|
responsible for their own rollback if they fail during the final commit.
|
||||||
|
|
||||||
|
Reference transforms returned by `find_refs_local()` and
|
||||||
|
`find_refs_global()` are now Nx5 arrays. The fifth column is the cumulative
|
||||||
|
scale, so rows have the form `(x, y, rotation, mirrored, scale)` rather than the
|
||||||
|
old Nx4 form.
|
||||||
|
|
||||||
|
`BuildReport` mapping fields are now defensively copied and read-only. Copy a
|
||||||
|
field to a new `dict` before adding or removing report entries.
|
||||||
|
|
||||||
|
`PortLoadView`, `LayerMappedView`, `OverlayLibrary`, and source-backed outputs
|
||||||
|
returned by `LibraryBuilder.build()` borrow their sources. They do not close
|
||||||
|
source resources, and the views are not context managers. Keep each lazy
|
||||||
|
source open and unchanged until every borrowing view or overlay is finished,
|
||||||
|
then close the owning source explicitly. An eager `build(output='library')`
|
||||||
|
result is detached and does not need its sources afterward.
|
||||||
|
|
||||||
|
Lazy GDS sources no longer provide `with_ports_from_data()` or
|
||||||
|
`with_port_overrides()` convenience methods. Construct the generic view
|
||||||
|
directly instead: `PortLoadView(source, layers=...)` imports port data, and
|
||||||
|
`PortLoadView(source, ports=..., replace=...)` applies explicit overrides.
|
||||||
|
|
||||||
|
`LayerMappedView(source, map_layer)` lazily remaps shape and label layers while
|
||||||
|
leaving the source untouched. Its default `copy_through=False` forces mapped
|
||||||
|
serialization of every cell. Set `copy_through=True` only when source-aware
|
||||||
|
writers may copy untouched cells unchanged and intentionally skip their layer
|
||||||
|
mapping; persistently accessed cells are mapped and no longer copied through.
|
||||||
|
|
||||||
|
`preflight_source_aware(...)` preserves that per-cell provenance. It returns a
|
||||||
|
borrowing `OverlayLibrary`, skips source-backed cells completely, and applies
|
||||||
|
pattern sorting, named-layer validation, safe empty-cell pruning, and
|
||||||
|
repeated-shape wrapping only to cells without reusable source provenance.
|
||||||
|
Library name order is retained because sorting source-backed cells would
|
||||||
|
require loading them. Always use the returned overlay for writing, and keep the
|
||||||
|
original lazy source open until the write finishes. The comprehensive
|
||||||
|
`preflight(...)` operation continues to materialize every cell when sorting is
|
||||||
|
enabled.
|
||||||
|
|
||||||
|
Generic borrowing views no longer expose GDS-specific `raw_struct_bytes()`,
|
||||||
|
`can_copy_raw_struct()`, or forwarded `library_info` attributes. Keep the
|
||||||
|
owning GDS source or the metadata returned by `readfile()` when direct access is
|
||||||
|
needed. `IBorrowing.source_cell()` now provides format-neutral per-cell
|
||||||
|
provenance; GDS writers use it internally to preserve safe raw copy-through.
|
||||||
|
|
||||||
|
Read-only `subtree()` results are now borrowed lazy views rather than eager
|
||||||
|
`LibraryView` snapshots. Creating one no longer loads its reachable patterns,
|
||||||
|
and the view preserves source ordering, hierarchy metadata, and lazy GDS
|
||||||
|
copy-through. Mutable `Library`, `LazyLibrary`, and `OverlayLibrary` subtrees
|
||||||
|
return the same writable type as their source. Overlay subtrees retain their
|
||||||
|
source layers and lazy GDS capabilities. Mutable subtree containers are
|
||||||
|
structurally independent, but already-materialized patterns remain shared.
|
||||||
|
Keep borrowed sources open and structurally unchanged for the subtree's
|
||||||
|
lifetime.
|
||||||
|
|
||||||
|
`ILibrary` no longer inherits `collections.abc.MutableMapping`. It remains a
|
||||||
|
readable `Mapping` with explicit insert-only item assignment and deletion, but
|
||||||
|
generic mutation helpers such as `update()`, `setdefault()`, `pop()`,
|
||||||
|
`popitem()`, and `clear()` are no longer supplied. Use `add()`, `rename()`,
|
||||||
|
`delete()`, item insertion, and item deletion so library name and reference
|
||||||
|
invariants remain explicit.
|
||||||
|
|
||||||
|
Library-level `referenced_patterns()` and `dangling_refs()` now report only
|
||||||
|
named cell targets and return `set[str]`. Populated refs whose target is `None`
|
||||||
|
are ignored, matching `child_graph()` and recursive geometry behavior;
|
||||||
|
`Pattern.referenced_patterns()` continues to report `None` locally.
|
||||||
|
|
||||||
|
Port-importing views now always process detached patterns, including when the
|
||||||
|
raw source cell was already cached. Code can safely retain and compare raw and
|
||||||
|
processed views without port overrides leaking back into the raw pattern.
|
||||||
|
Once a processed cell is persistently materialized, lazy GDS writers no longer
|
||||||
|
copy the raw source structure for that cell, so later mutations to the returned
|
||||||
|
`Pattern` are serialized. Non-persistent materialization does not mark the cell
|
||||||
|
as changed.
|
||||||
|
|
||||||
|
Underscore-prefixed declarations work through the attribute authoring surface:
|
||||||
|
`builder.cells._helper = pattern` now declares `_helper`. Only the view's exact
|
||||||
|
internal `_library` attribute is reserved.
|
||||||
|
|
||||||
|
Recursive geometry operations now reject cyclic reference hierarchies with a
|
||||||
|
contextual `PatternError` instead of eventually leaking `RecursionError`. This
|
||||||
|
applies to bounds calculation, flattened layer polygon extraction, and
|
||||||
|
visualization as well as the existing flattening checks.
|
||||||
|
|
||||||
|
`LibraryBuilder.validate(names=...)` now accepts either one string or a sequence
|
||||||
|
of strings. Non-string roots raise `TypeError`, and duplicate roots are reduced
|
||||||
|
to their first occurrence. A recipe may build a different `LibraryBuilder`, but
|
||||||
|
calling `build()` or `validate()` recursively on its own active builder now
|
||||||
|
raises `BuildError` before starting another session.
|
||||||
|
|
||||||
|
`LibraryBuilder` is an authoring registry, not an `ILibraryView` or mapping.
|
||||||
|
Use membership, iteration, `keys()`, `get_name()`, assignment, and deletion to
|
||||||
|
manage declarations, then use the library returned by `build()` for reads and
|
||||||
|
hierarchy operations. Recipes that need an active library must receive the
|
||||||
|
builder-owned placeholder as a direct argument:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def make_top(lib: ILibrary) -> Pattern:
|
||||||
|
return Pather(library=lib, ports='device').pattern
|
||||||
|
|
||||||
|
builder.cells.top = cell(make_top)(builder.library)
|
||||||
|
builder.cells.device = cell(factory)(hole_lib=builder.library)
|
||||||
|
```
|
||||||
|
|
||||||
|
The builder-owned `builder.library` placeholder is read-only. Only direct
|
||||||
|
positional and keyword values equal to it are substituted; placeholders nested
|
||||||
|
inside containers are not interpreted. A placeholder from another builder is
|
||||||
|
rejected when the recipe is assigned.
|
||||||
|
|
||||||
|
`IMaterializable` now identifies libraries which support explicit
|
||||||
|
`materialize()` and `materialize_many()` operations. `LibraryBuilder.add()`
|
||||||
|
borrows these marked inputs, while ordinary mappings and `ILibraryView`
|
||||||
|
instances are copied eagerly. Use `add_source()` to force borrowing of an
|
||||||
|
unmarked view. Wrapping a materializable library in `LibraryView` intentionally
|
||||||
|
erases the marker.
|
||||||
|
|
||||||
|
`IBorrowing` separately identifies composite views which retain direct source
|
||||||
|
libraries and expose them through `borrowed_sources()`. Keep those sources open
|
||||||
|
and unchanged for the lifetime of the borrowing view. Owner libraries such as
|
||||||
|
`LazyLibrary` and the lazy GDS readers are materializable but do not implement
|
||||||
|
`IBorrowing`. Borrowing views may expose unchanged per-cell layout provenance
|
||||||
|
through `source_cell()`; format writers decide whether that provenance permits
|
||||||
|
raw copy-through. Raw GDS structure access remains confined to GDS sources and
|
||||||
|
writers.
|
||||||
|
|
||||||
|
`LibraryBuilder`, `OverlayLibrary`, `PortLoadView`, and `LayerMappedView` are new
|
||||||
|
additive library implementations. `LibraryBuilder` supports declarative `@cell`
|
||||||
|
recipes and dependency-aware builds; `OverlayLibrary` composes source libraries
|
||||||
|
without eagerly copying all patterns; `PortLoadView` loads port metadata from
|
||||||
|
labels and/or explicit mappings; `LayerMappedView` remaps shape and label layers
|
||||||
|
on detached materialization.
|
||||||
|
|
||||||
|
Flattening with `flatten_ports=True` now rejects repeated refs whose target has
|
||||||
|
ports, because expanding them would create duplicate port names. Resolve the
|
||||||
|
repetition and assign unique port names before flattening, or use
|
||||||
|
`flatten_ports=False`.
|
||||||
|
|
||||||
|
## GDSII module and lazy-loading changes
|
||||||
|
|
||||||
|
`masque.file.gdsii` changed from a module into a package. The eager klamath
|
||||||
|
API remains available at the old import path, so ordinary `read`, `readfile`,
|
||||||
|
`write`, and `writefile` calls do not need to change:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from masque.file import gdsii
|
||||||
|
library, info = gdsii.readfile('layout.gds')
|
||||||
|
```
|
||||||
|
|
||||||
|
The old `gdsii.load_library()` and `gdsii.load_libraryfile()` entry points were
|
||||||
|
removed. Use the source-backed lazy reader instead:
|
||||||
|
|
||||||
|
```python
|
||||||
|
# old
|
||||||
|
library, info = gdsii.load_libraryfile('layout.gds')
|
||||||
|
|
||||||
|
# new
|
||||||
|
from masque.file.gdsii import lazy
|
||||||
|
|
||||||
|
library, info = lazy.readfile('layout.gds')
|
||||||
|
try:
|
||||||
|
pattern = library['TOP']
|
||||||
|
finally:
|
||||||
|
library.close()
|
||||||
|
```
|
||||||
|
|
||||||
|
`lazy.read(stream)` and `lazy.readfile(path, use_mmap=...)` return a read-only
|
||||||
|
`GdsLibrarySource`. It owns file resources when it opens them and also supports
|
||||||
|
the context-manager protocol. The old `full_load` and `postprocess` arguments
|
||||||
|
are gone; materialize/copy the desired cells and post-process them explicitly.
|
||||||
|
|
||||||
|
An optional Arrow/native backend is available through
|
||||||
|
`masque.file.gdsii.arrow` and `masque.file.gdsii.lazy_arrow`; install the new
|
||||||
|
`arrow` extra to use it. These modules are additive and are not a transparent
|
||||||
|
replacement unless their additional dependencies and native library are
|
||||||
|
available.
|
||||||
|
|
||||||
|
GDS writing now has one entry point for eager and lazy libraries. Use
|
||||||
|
`masque.file.gdsii.write()` or `masque.file.gdsii.writefile()` regardless of
|
||||||
|
which reader produced the library. The `lazy` and `lazy_arrow` modules no
|
||||||
|
longer re-export writer functions. Source-backed libraries continue to infer
|
||||||
|
their header metadata and copy untouched structures directly.
|
||||||
|
|
||||||
|
## Shape construction and geometry additions
|
||||||
|
|
||||||
|
The public `raw=True` constructor shortcut was removed from `Arc`, `Circle`,
|
||||||
|
`Ellipse`, `Path`, `Polygon`, `PolyCollection`, and `Text`. Call their normal
|
||||||
|
constructors without `raw`; `_from_raw()` is an internal fast path and is not a
|
||||||
|
compatibility API.
|
||||||
|
|
||||||
|
```python
|
||||||
|
# old
|
||||||
|
polygon = Polygon(vertices, raw=True)
|
||||||
|
|
||||||
|
# new
|
||||||
|
polygon = Polygon(vertices)
|
||||||
|
```
|
||||||
|
|
||||||
|
`Arc` radii must now be strictly positive rather than merely non-negative.
|
||||||
|
`Arc.angle_ref` is additive and defaults to `Arc.AngleRef.Center`, preserving
|
||||||
|
the previous center-referenced angle interpretation.
|
||||||
|
|
||||||
|
`RectCollection` is a new shape for batches of axis-aligned rectangles and is
|
||||||
|
exported from both `masque` and `masque.shapes`. `Polygon.boolean()` and the
|
||||||
|
top-level `masque.boolean()` helper are also new; install the `boolean` extra
|
||||||
|
for their `pyclipper` dependency.
|
||||||
|
|
||||||
|
## Other user-facing changes
|
||||||
|
|
||||||
|
### File writers
|
||||||
|
|
||||||
|
SVG writing no longer polygonizes or flattens caller-owned patterns in place;
|
||||||
|
it works from detached copies. `svg.writefile(..., annotate_ports=True)` can
|
||||||
|
add port arrows. DXF writing now expands shape repetitions into individual DXF
|
||||||
|
entities, so callers no longer need to wrap repeated shapes solely for DXF
|
||||||
|
output.
|
||||||
|
|
||||||
|
### DXF environments
|
||||||
|
|
||||||
|
If you install the DXF extra, the supported `ezdxf` baseline moved from
|
||||||
|
`~=1.0.2` to `~=1.4`. Any pinned environments should be updated accordingly.
|
||||||
|
|
||||||
|
### Optional dependency names
|
||||||
|
|
||||||
|
The misspelled `manhatanize_slow` extra was corrected to
|
||||||
|
`manhattanize_slow`. A separate `manhattanize` extra now installs the
|
||||||
|
scikit-image implementation. The `arrow` and `boolean` extras are also new.
|
||||||
|
|
||||||
|
### New exports
|
||||||
|
|
||||||
|
These are additive, but available now from `masque` and `masque.builder`:
|
||||||
|
|
||||||
|
- from `masque`: `RectCollection`, `boolean`, `OverlayLibrary`,
|
||||||
|
`PortLoadView`, `LayerMappedView`, `IMaterializable`, `IBorrowing`, `LibraryBuilder`,
|
||||||
|
`BuildReport`, `CellProvenance`, and `cell`
|
||||||
|
- from `masque.builder`: `CostCallable`, `RenderStepKind`, the concrete
|
||||||
|
primitive-offer classes, structured route error/status types,
|
||||||
|
`ToolContractCase`, and `validate_tool_contract`
|
||||||
|
|
||||||
|
## Minimal migration checklist
|
||||||
|
|
||||||
|
If your code uses the routing stack, do these first:
|
||||||
|
|
||||||
|
1. Replace `path`/`path_to`/`mpath`/`path_into` calls with
|
||||||
|
`trace`/`trace_to`/multi-port `trace`/`trace_into`.
|
||||||
|
2. Replace `SimpleTool` and old `AutoTool` descriptor construction with the
|
||||||
|
new `AutoTool.add_*()` methods.
|
||||||
|
3. Fix imports that still reference `masque.builder.builder` or
|
||||||
|
`masque.builder.renderpather`.
|
||||||
|
4. Audit any low-level `mirror()` usage, especially on `Port` and `Ref`.
|
||||||
|
5. Move lazy GDS calls from `gdsii.load_library*()` to
|
||||||
|
`masque.file.gdsii.lazy`.
|
||||||
|
6. Remove `raw=True` from public shape constructors.
|
||||||
|
|
||||||
|
If your code only uses `Pattern`, `Library`, `place()`, and `plug()` without the
|
||||||
|
routing helpers, audit transforms, dangling-reference graph calls, raw shape
|
||||||
|
construction, and any stale imports.
|
||||||
69
README.md
69
README.md
|
|
@ -37,6 +37,55 @@ A layout consists of a hierarchy of `Pattern`s stored in a single `Library`.
|
||||||
Each `Pattern` can contain `Ref`s pointing at other patterns, `Shape`s, `Label`s, and `Port`s.
|
Each `Pattern` can contain `Ref`s pointing at other patterns, `Shape`s, `Label`s, and `Port`s.
|
||||||
|
|
||||||
|
|
||||||
|
Library / Pattern hierarchy:
|
||||||
|
```
|
||||||
|
+-----------------------------------------------------------------------+
|
||||||
|
| Library |
|
||||||
|
| |
|
||||||
|
| Name: "MyChip" ...> Name: "Transistor" |
|
||||||
|
| +---------------------------+ : +---------------------------+ |
|
||||||
|
| | [Pattern] | : | [Pattern] | |
|
||||||
|
| | | : | | |
|
||||||
|
| | shapes: {...} | : | shapes: { | |
|
||||||
|
| | ports: {...} | : | "Si": [<Polygon>, ...] | |
|
||||||
|
| | | : | "M1": [<Polygon>, ...]}| |
|
||||||
|
| | refs: | : | ports: {G, S, D} | |
|
||||||
|
| | "Transistor": [Ref, Ref]|..: +---------------------------+ |
|
||||||
|
| +---------------------------+ |
|
||||||
|
| |
|
||||||
|
| # (`refs` keys resolve to Patterns within the Library) |
|
||||||
|
+-----------------------------------------------------------------------+
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
Pattern internals:
|
||||||
|
```
|
||||||
|
+---------------------------------------------------------------+
|
||||||
|
| [Pattern] |
|
||||||
|
| |
|
||||||
|
| shapes: { |
|
||||||
|
| (1, 0): [Polygon, Circle, ...], # Geometry by layer |
|
||||||
|
| (2, 0): [Path, ...] |
|
||||||
|
| "M1" : [Path, ...] |
|
||||||
|
| "M2" : [Polygon, ...] |
|
||||||
|
| } |
|
||||||
|
| |
|
||||||
|
| refs: { # Key sets target name, Ref sets transform |
|
||||||
|
| "my_cell": [ |
|
||||||
|
| Ref(offset=(0,0), rotation=0), |
|
||||||
|
| Ref(offset=(10,0), rotation=R90, repetition=Grid(...)) |
|
||||||
|
| ] |
|
||||||
|
| } |
|
||||||
|
| |
|
||||||
|
| ports: { |
|
||||||
|
| "in": Port(offset=(0,0), rotation=0, ptype="M1"), |
|
||||||
|
| "out": Port(offset=(10,0), rotation=R180, ptype="wg") |
|
||||||
|
| } |
|
||||||
|
| |
|
||||||
|
+---------------------------------------------------------------+
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
`masque` departs from several "classic" GDSII paradigms:
|
`masque` departs from several "classic" GDSII paradigms:
|
||||||
- A `Pattern` object does not store its own name. A name is only assigned when the pattern is placed
|
- A `Pattern` object does not store its own name. A name is only assigned when the pattern is placed
|
||||||
into a `Library`, which is effectively a name->`Pattern` mapping.
|
into a `Library`, which is effectively a name->`Pattern` mapping.
|
||||||
|
|
@ -96,7 +145,7 @@ References are accomplished by listing the target's name, not its `Pattern` obje
|
||||||
in order to create a reference, but they also need to access the pattern's ports.
|
in order to create a reference, but they also need to access the pattern's ports.
|
||||||
* One way to provide this data is through an `Abstract`, generated via
|
* One way to provide this data is through an `Abstract`, generated via
|
||||||
`Library.abstract()` or through a `Library.abstract_view()`.
|
`Library.abstract()` or through a `Library.abstract_view()`.
|
||||||
* Another way is use `Builder.place()` or `Builder.plug()`, which automatically creates
|
* Another way is use `Pather.place()` or `Pather.plug()`, which automatically creates
|
||||||
an `Abstract` from its internally-referenced `Library`.
|
an `Abstract` from its internally-referenced `Library`.
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -133,7 +182,7 @@ tree = make_tree(...)
|
||||||
|
|
||||||
# To reference this cell in our layout, we have to add all its children to our `library` first:
|
# To reference this cell in our layout, we have to add all its children to our `library` first:
|
||||||
top_name = tree.top() # get the name of the topcell
|
top_name = tree.top() # get the name of the topcell
|
||||||
name_mapping = library.add(tree) # add all patterns from `tree`, renaming elgible conflicting patterns
|
name_mapping = library.add(tree) # add all patterns from `tree`, renaming eligible conflicting patterns
|
||||||
new_name = name_mapping.get(top_name, top_name) # get the new name for the cell (in case it was auto-renamed)
|
new_name = name_mapping.get(top_name, top_name) # get the new name for the cell (in case it was auto-renamed)
|
||||||
my_pattern.ref(new_name, ...) # instantiate the cell
|
my_pattern.ref(new_name, ...) # instantiate the cell
|
||||||
|
|
||||||
|
|
@ -144,8 +193,8 @@ my_pattern.ref(new_name, ...) # instantiate the cell
|
||||||
# In practice, you may do lots of
|
# In practice, you may do lots of
|
||||||
my_pattern.ref(lib << make_tree(...), ...)
|
my_pattern.ref(lib << make_tree(...), ...)
|
||||||
|
|
||||||
# With a `Builder` and `place()`/`plug()` the `lib <<` portion can be implicit:
|
# With a `Pather` and `place()`/`plug()` the `lib <<` portion can be implicit:
|
||||||
my_builder = Builder(library=lib, ...)
|
my_builder = Pather(library=lib, ...)
|
||||||
...
|
...
|
||||||
my_builder.place(make_tree(...))
|
my_builder.place(make_tree(...))
|
||||||
```
|
```
|
||||||
|
|
@ -172,10 +221,11 @@ my_pattern.place(abstract, ...)
|
||||||
|
|
||||||
# or
|
# or
|
||||||
my_pattern.place(library << make_tree(...), ...)
|
my_pattern.place(library << make_tree(...), ...)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
### Quickly add geometry, labels, or refs:
|
### Quickly add geometry, labels, or refs:
|
||||||
The long form for adding elements can be overly verbose:
|
Adding elements can be overly verbose:
|
||||||
```python3
|
```python3
|
||||||
my_pattern.shapes[layer].append(Polygon(vertices, ...))
|
my_pattern.shapes[layer].append(Polygon(vertices, ...))
|
||||||
my_pattern.labels[layer] += [Label('my text')]
|
my_pattern.labels[layer] += [Label('my text')]
|
||||||
|
|
@ -225,11 +275,6 @@ my_pattern.ref(_make_my_subpattern(), offset=..., ...)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
## TODO
|
## Development
|
||||||
|
|
||||||
* Better interface for polygon operations (e.g. with `pyclipper`)
|
Project-level planned work is tracked in [TODO.md](TODO.md).
|
||||||
- de-embedding
|
|
||||||
- boolean ops
|
|
||||||
* Tests tests tests
|
|
||||||
* check renderpather
|
|
||||||
* pather and renderpather examples
|
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ from masque.file import gdsii
|
||||||
from masque import Arc, Pattern
|
from masque import Arc, Pattern
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main() -> None:
|
||||||
pat = Pattern()
|
pat = Pattern()
|
||||||
layer = (0, 0)
|
layer = (0, 0)
|
||||||
pat.shapes[layer].extend([
|
pat.shapes[layer].extend([
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,5 @@
|
||||||
import numpy
|
|
||||||
from pyclipper import (
|
from pyclipper import (
|
||||||
Pyclipper, PT_CLIP, PT_SUBJECT, CT_UNION, CT_INTERSECTION, PFT_NONZERO,
|
Pyclipper, PT_SUBJECT, CT_UNION, PFT_NONZERO,
|
||||||
scale_to_clipper, scale_from_clipper,
|
|
||||||
)
|
)
|
||||||
p = Pyclipper()
|
p = Pyclipper()
|
||||||
p.AddPaths([
|
p.AddPaths([
|
||||||
|
|
@ -12,8 +10,8 @@ p.AddPaths([
|
||||||
], PT_SUBJECT, closed=True)
|
], PT_SUBJECT, closed=True)
|
||||||
#p.Execute2?
|
#p.Execute2?
|
||||||
#p.Execute?
|
#p.Execute?
|
||||||
p.Execute(PT_UNION, PT_NONZERO, PT_NONZERO)
|
p.Execute(CT_UNION, PFT_NONZERO, PFT_NONZERO)
|
||||||
p.Execute(CT_UNION, PT_NONZERO, PT_NONZERO)
|
p.Execute(CT_UNION, PFT_NONZERO, PFT_NONZERO)
|
||||||
p.Execute(CT_UNION, PFT_NONZERO, PFT_NONZERO)
|
p.Execute(CT_UNION, PFT_NONZERO, PFT_NONZERO)
|
||||||
|
|
||||||
p = Pyclipper()
|
p = Pyclipper()
|
||||||
|
|
|
||||||
131
examples/profile_gdsii_readers.py
Normal file
131
examples/profile_gdsii_readers.py
Normal file
|
|
@ -0,0 +1,131 @@
|
||||||
|
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())
|
||||||
|
|
@ -11,7 +11,7 @@ from masque.file import gdsii, dxf, oasis
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main() -> None:
|
||||||
lib = Library()
|
lib = Library()
|
||||||
|
|
||||||
cell_name = 'ellip_grating'
|
cell_name = 'ellip_grating'
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,12 @@
|
||||||
masque Tutorial
|
masque Tutorial
|
||||||
===============
|
===============
|
||||||
|
|
||||||
|
These examples are meant to be read roughly in order.
|
||||||
|
|
||||||
|
- Start with `basic_shapes.py` for the core `Pattern` / GDS concepts.
|
||||||
|
- Then read `devices.py` and `library.py` for hierarchical composition and libraries.
|
||||||
|
- Read the `pather*` tutorials separately when you want routing helpers.
|
||||||
|
|
||||||
Contents
|
Contents
|
||||||
--------
|
--------
|
||||||
|
|
||||||
|
|
@ -8,24 +14,30 @@ Contents
|
||||||
* Draw basic geometry
|
* Draw basic geometry
|
||||||
* Export to GDS
|
* Export to GDS
|
||||||
- [devices](devices.py)
|
- [devices](devices.py)
|
||||||
|
* Build hierarchical photonic-crystal example devices
|
||||||
* Reference other patterns
|
* Reference other patterns
|
||||||
* Add ports to a pattern
|
* Add ports to a pattern
|
||||||
* Snap ports together to build 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)
|
||||||
* Create a `LazyLibrary`, which loads / generates patterns only when they are first used
|
* Continue from `devices.py` by declaring a mixed library with `LibraryBuilder`
|
||||||
|
* Import source-backed GDS cells and register python-generated recipes together
|
||||||
|
* Call `build()` to produce a normal library and report for downstream `Pather` usage and writing
|
||||||
* Explore alternate ways of specifying a pattern for `.plug()` and `.place()`
|
* Explore alternate ways of specifying a pattern for `.plug()` and `.place()`
|
||||||
* Design a pattern which is meant to plug into an existing pattern (via `.interface()`)
|
|
||||||
- [pather](pather.py)
|
- [pather](pather.py)
|
||||||
* Use `Pather` to route individual wires and wire bundles
|
* Use `Pather` to route individual wires and wire bundles
|
||||||
* Use `BasicTool` to generate paths
|
* Define a custom `Tool` that exposes primitive routing offers
|
||||||
* Use `BasicTool` to automatically transition between path types
|
* Use primitive offers to automatically transition between path types
|
||||||
- [renderpather](rendpather.py)
|
- [renderpather](renderpather.py)
|
||||||
* Use `RenderPather` and `PathTool` to build a layout similar to the one in [pather](pather.py),
|
* Use `Pather(render='deferred')` 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)
|
||||||
|
* Use `PortPather` and the `.at()` syntax for more concise routing
|
||||||
|
* Advanced port manipulation and connections
|
||||||
|
|
||||||
|
|
||||||
Additionaly, [pcgen](pcgen.py) is a utility module for generating photonic crystal lattices.
|
Additionally, [pcgen](pcgen.py) is a utility module used by `devices.py` for generating
|
||||||
|
photonic-crystal lattices; it is support code rather than a step-by-step tutorial.
|
||||||
|
|
||||||
|
|
||||||
Running
|
Running
|
||||||
|
|
@ -37,3 +49,6 @@ cd examples/tutorial
|
||||||
python3 basic_shapes.py
|
python3 basic_shapes.py
|
||||||
klayout -e basic_shapes.gds
|
klayout -e basic_shapes.gds
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Some tutorials depend on outputs from earlier ones. In particular, `library.py`
|
||||||
|
expects `circuit.gds`, which is generated by `devices.py`.
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,9 @@
|
||||||
from collections.abc import Sequence
|
|
||||||
|
|
||||||
import numpy
|
import numpy
|
||||||
from numpy import pi
|
from numpy import pi
|
||||||
|
|
||||||
from masque import (
|
from masque import layer_t, Pattern, Circle, Arc, Ref
|
||||||
layer_t, Pattern, Label, Port,
|
from masque.repetition import Grid
|
||||||
Circle, Arc, Polygon,
|
|
||||||
)
|
|
||||||
import masque.file.gdsii
|
import masque.file.gdsii
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -39,6 +36,45 @@ def hole(
|
||||||
return pat
|
return pat
|
||||||
|
|
||||||
|
|
||||||
|
def hole_array(
|
||||||
|
radius: float,
|
||||||
|
num_x: int = 5,
|
||||||
|
num_y: int = 3,
|
||||||
|
pitch: float = 2000,
|
||||||
|
layer: layer_t = (1, 0),
|
||||||
|
) -> Pattern:
|
||||||
|
"""
|
||||||
|
Generate an array of circular holes using `Repetition`.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
radius: Circle radius.
|
||||||
|
num_x, num_y: Number of holes in x and y.
|
||||||
|
pitch: Center-to-center spacing.
|
||||||
|
layer: Layer to draw the holes on.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Pattern containing a grid of holes.
|
||||||
|
"""
|
||||||
|
# First, make a pattern for a single hole
|
||||||
|
hpat = hole(radius, layer)
|
||||||
|
|
||||||
|
# Now, create a pattern that references it multiple times using a Grid
|
||||||
|
pat = Pattern()
|
||||||
|
pat.refs['hole'] = [
|
||||||
|
Ref(
|
||||||
|
offset=(0, 0),
|
||||||
|
repetition=Grid(a_vector=(pitch, 0), a_count=num_x,
|
||||||
|
b_vector=(0, pitch), b_count=num_y)
|
||||||
|
)]
|
||||||
|
|
||||||
|
# We can also add transformed references (rotation, mirroring, etc.)
|
||||||
|
pat.refs['hole'].append(
|
||||||
|
Ref(offset=(0, -pitch), rotation=pi / 4, mirrored=True)
|
||||||
|
)
|
||||||
|
|
||||||
|
return pat, hpat
|
||||||
|
|
||||||
|
|
||||||
def triangle(
|
def triangle(
|
||||||
radius: float,
|
radius: float,
|
||||||
layer: layer_t = (1, 0),
|
layer: layer_t = (1, 0),
|
||||||
|
|
@ -60,9 +96,7 @@ def triangle(
|
||||||
]) * radius
|
]) * radius
|
||||||
|
|
||||||
pat = Pattern()
|
pat = Pattern()
|
||||||
pat.shapes[layer].extend([
|
pat.polygon(layer, vertices=vertices)
|
||||||
Polygon(offset=(0, 0), vertices=vertices),
|
|
||||||
])
|
|
||||||
return pat
|
return pat
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -111,9 +145,13 @@ def main() -> None:
|
||||||
lib['smile'] = smile(1000)
|
lib['smile'] = smile(1000)
|
||||||
lib['triangle'] = triangle(1000)
|
lib['triangle'] = triangle(1000)
|
||||||
|
|
||||||
|
# Use a Grid to make many holes efficiently
|
||||||
|
lib['grid'], lib['hole'] = hole_array(1000)
|
||||||
|
|
||||||
masque.file.gdsii.writefile(lib, 'basic_shapes.gds', **GDS_OPTS)
|
masque.file.gdsii.writefile(lib, 'basic_shapes.gds', **GDS_OPTS)
|
||||||
|
|
||||||
lib['triangle'].visualize()
|
lib['triangle'].visualize()
|
||||||
|
lib['grid'].visualize(lib)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,19 @@
|
||||||
|
"""
|
||||||
|
Tutorial: building hierarchical devices with `Pattern`, `Port`, and `Pather`.
|
||||||
|
|
||||||
|
This file uses photonic-crystal components as the concrete example, so some of
|
||||||
|
the geometry-generation code is domain-specific. The tutorial value is in the
|
||||||
|
Masque patterns around it: creating reusable cells, annotating ports, composing
|
||||||
|
hierarchy with references, and snapping ports together to build a larger circuit.
|
||||||
|
"""
|
||||||
from collections.abc import Sequence, Mapping
|
from collections.abc import Sequence, Mapping
|
||||||
|
|
||||||
import numpy
|
import numpy
|
||||||
from numpy import pi
|
from numpy import pi
|
||||||
|
|
||||||
from masque import (
|
from masque import (
|
||||||
layer_t, Pattern, Ref, Label, Builder, Port, Polygon,
|
layer_t, Pattern, Ref, Pather, Port, Polygon,
|
||||||
Library, ILibraryView,
|
Library,
|
||||||
)
|
)
|
||||||
from masque.utils import ports2data
|
from masque.utils import ports2data
|
||||||
from masque.file.gdsii import writefile, check_valid_names
|
from masque.file.gdsii import writefile, check_valid_names
|
||||||
|
|
@ -64,9 +72,9 @@ def perturbed_l3(
|
||||||
Provided sequence should have same length as `shifts_a`.
|
Provided sequence should have same length as `shifts_a`.
|
||||||
xy_size: `(x, y)` number of mirror periods in each direction; total size is
|
xy_size: `(x, y)` number of mirror periods in each direction; total size is
|
||||||
`2 * n + 1` holes in each direction. Default (10, 10).
|
`2 * n + 1` holes in each direction. Default (10, 10).
|
||||||
perturbed_radius: radius of holes perturbed to form an upwards-driected beam
|
perturbed_radius: radius of holes perturbed to form an upwards-directed beam
|
||||||
(multiplicative factor). Default 1.1.
|
(multiplicative factor). Default 1.1.
|
||||||
trench width: Width of the undercut trenches. Default 1200.
|
trench_width: Width of the undercut trenches. Default 1200.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
`Pattern` object representing the L3 design.
|
`Pattern` object representing the L3 design.
|
||||||
|
|
@ -79,14 +87,15 @@ def perturbed_l3(
|
||||||
shifts_a=shifts_a,
|
shifts_a=shifts_a,
|
||||||
shifts_r=shifts_r)
|
shifts_r=shifts_r)
|
||||||
|
|
||||||
# Build L3 cavity, using references to the provided hole pattern
|
# Build the cavity by instancing the supplied `hole` pattern many times.
|
||||||
|
# Using references keeps the pattern compact even though it contains many holes.
|
||||||
pat = Pattern()
|
pat = Pattern()
|
||||||
pat.refs[hole] += [
|
pat.refs[hole] += [
|
||||||
Ref(scale=r, offset=(lattice_constant * x,
|
Ref(scale=r, offset=(lattice_constant * x,
|
||||||
lattice_constant * y))
|
lattice_constant * y))
|
||||||
for x, y, r in xyr]
|
for x, y, r in xyr]
|
||||||
|
|
||||||
# Add rectangular undercut aids
|
# Add rectangular undercut aids based on the referenced hole extents.
|
||||||
min_xy, max_xy = pat.get_bounds_nonempty(hole_lib)
|
min_xy, max_xy = pat.get_bounds_nonempty(hole_lib)
|
||||||
trench_dx = max_xy[0] - min_xy[0]
|
trench_dx = max_xy[0] - min_xy[0]
|
||||||
|
|
||||||
|
|
@ -95,7 +104,7 @@ def perturbed_l3(
|
||||||
Polygon.rect(ymax=min_xy[1], xmin=min_xy[0], lx=trench_dx, ly=trench_width),
|
Polygon.rect(ymax=min_xy[1], xmin=min_xy[0], lx=trench_dx, ly=trench_width),
|
||||||
]
|
]
|
||||||
|
|
||||||
# Ports are at outer extents of the device (with y=0)
|
# Define the interface in Masque terms: two ports at the left/right extents.
|
||||||
extent = lattice_constant * xy_size[0]
|
extent = lattice_constant * xy_size[0]
|
||||||
pat.ports = dict(
|
pat.ports = dict(
|
||||||
input=Port((-extent, 0), rotation=0, ptype='pcwg'),
|
input=Port((-extent, 0), rotation=0, ptype='pcwg'),
|
||||||
|
|
@ -125,17 +134,17 @@ def waveguide(
|
||||||
Returns:
|
Returns:
|
||||||
`Pattern` object representing the waveguide.
|
`Pattern` object representing the waveguide.
|
||||||
"""
|
"""
|
||||||
# Generate hole locations
|
# Generate the normalized lattice locations for the line defect.
|
||||||
xy = pcgen.waveguide(length=length, num_mirror=mirror_periods)
|
xy = pcgen.waveguide(length=length, num_mirror=mirror_periods)
|
||||||
|
|
||||||
# Build the pattern
|
# Build the pattern by placing repeated references to the same hole cell.
|
||||||
pat = Pattern()
|
pat = Pattern()
|
||||||
pat.refs[hole] += [
|
pat.refs[hole] += [
|
||||||
Ref(offset=(lattice_constant * x,
|
Ref(offset=(lattice_constant * x,
|
||||||
lattice_constant * y))
|
lattice_constant * y))
|
||||||
for x, y in xy]
|
for x, y in xy]
|
||||||
|
|
||||||
# Ports are at outer edges, with y=0
|
# Publish the device interface as two ports at the outer edges.
|
||||||
extent = lattice_constant * length / 2
|
extent = lattice_constant * length / 2
|
||||||
pat.ports = dict(
|
pat.ports = dict(
|
||||||
left=Port((-extent, 0), rotation=0, ptype='pcwg'),
|
left=Port((-extent, 0), rotation=0, ptype='pcwg'),
|
||||||
|
|
@ -164,17 +173,17 @@ def bend(
|
||||||
`Pattern` object representing the waveguide bend.
|
`Pattern` object representing the waveguide bend.
|
||||||
Ports are named 'left' (input) and 'right' (output).
|
Ports are named 'left' (input) and 'right' (output).
|
||||||
"""
|
"""
|
||||||
# Generate hole locations
|
# Generate the normalized lattice locations for the bend.
|
||||||
xy = pcgen.wgbend(num_mirror=mirror_periods)
|
xy = pcgen.wgbend(num_mirror=mirror_periods)
|
||||||
|
|
||||||
# Build the pattern
|
# Build the pattern by instancing the shared hole cell.
|
||||||
pat= Pattern()
|
pat = Pattern()
|
||||||
pat.refs[hole] += [
|
pat.refs[hole] += [
|
||||||
Ref(offset=(lattice_constant * x,
|
Ref(offset=(lattice_constant * x,
|
||||||
lattice_constant * y))
|
lattice_constant * y))
|
||||||
for x, y in xy]
|
for x, y in xy]
|
||||||
|
|
||||||
# Figure out port locations.
|
# Publish the bend interface as two ports.
|
||||||
extent = lattice_constant * mirror_periods
|
extent = lattice_constant * mirror_periods
|
||||||
pat.ports = dict(
|
pat.ports = dict(
|
||||||
left=Port((-extent, 0), rotation=0, ptype='pcwg'),
|
left=Port((-extent, 0), rotation=0, ptype='pcwg'),
|
||||||
|
|
@ -203,17 +212,17 @@ def y_splitter(
|
||||||
`Pattern` object representing the y-splitter.
|
`Pattern` object representing the y-splitter.
|
||||||
Ports are named 'in', 'top', and 'bottom'.
|
Ports are named 'in', 'top', and 'bottom'.
|
||||||
"""
|
"""
|
||||||
# Generate hole locations
|
# Generate the normalized lattice locations for the splitter.
|
||||||
xy = pcgen.y_splitter(num_mirror=mirror_periods)
|
xy = pcgen.y_splitter(num_mirror=mirror_periods)
|
||||||
|
|
||||||
# Build pattern
|
# Build the pattern by instancing the shared hole cell.
|
||||||
pat = Pattern()
|
pat = Pattern()
|
||||||
pat.refs[hole] += [
|
pat.refs[hole] += [
|
||||||
Ref(offset=(lattice_constant * x,
|
Ref(offset=(lattice_constant * x,
|
||||||
lattice_constant * y))
|
lattice_constant * y))
|
||||||
for x, y in xy]
|
for x, y in xy]
|
||||||
|
|
||||||
# Determine port locations
|
# Publish the splitter interface as one input and two outputs.
|
||||||
extent = lattice_constant * mirror_periods
|
extent = lattice_constant * mirror_periods
|
||||||
pat.ports = {
|
pat.ports = {
|
||||||
'in': Port((-extent, 0), rotation=0, ptype='pcwg'),
|
'in': Port((-extent, 0), rotation=0, ptype='pcwg'),
|
||||||
|
|
@ -227,13 +236,13 @@ def y_splitter(
|
||||||
|
|
||||||
|
|
||||||
def main(interactive: bool = True) -> None:
|
def main(interactive: bool = True) -> None:
|
||||||
# Generate some basic hole patterns
|
# First make a couple of reusable primitive cells.
|
||||||
shape_lib = {
|
shape_lib = {
|
||||||
'smile': basic_shapes.smile(RADIUS),
|
'smile': basic_shapes.smile(RADIUS),
|
||||||
'hole': basic_shapes.hole(RADIUS),
|
'hole': basic_shapes.hole(RADIUS),
|
||||||
}
|
}
|
||||||
|
|
||||||
# Build some devices
|
# Then build a small library of higher-level devices from those primitives.
|
||||||
a = LATTICE_CONSTANT
|
a = LATTICE_CONSTANT
|
||||||
|
|
||||||
devices = {}
|
devices = {}
|
||||||
|
|
@ -245,22 +254,23 @@ def main(interactive: bool = True) -> None:
|
||||||
devices['ysplit'] = y_splitter(lattice_constant=a, hole='hole', mirror_periods=5)
|
devices['ysplit'] = y_splitter(lattice_constant=a, hole='hole', mirror_periods=5)
|
||||||
devices['l3cav'] = perturbed_l3(lattice_constant=a, hole='smile', hole_lib=shape_lib, xy_size=(4, 10)) # uses smile :)
|
devices['l3cav'] = perturbed_l3(lattice_constant=a, hole='smile', hole_lib=shape_lib, xy_size=(4, 10)) # uses smile :)
|
||||||
|
|
||||||
# Turn our dict of devices into a Library.
|
# Turn the device mapping into a `Library`.
|
||||||
# This provides some convenience functions in the future!
|
# That gives us convenience helpers for hierarchy inspection and abstract views.
|
||||||
lib = Library(devices)
|
lib = Library(devices)
|
||||||
|
|
||||||
#
|
#
|
||||||
# Build a circuit
|
# Build a circuit
|
||||||
#
|
#
|
||||||
# Create a `Builder`, and add the circuit to our library as "my_circuit".
|
# Create a `Pather`, and register the resulting top cell as "my_circuit".
|
||||||
circ = Builder(library=lib, name='my_circuit')
|
circ = Pather(library=lib, name='my_circuit')
|
||||||
|
|
||||||
# Start by placing a waveguide. Call its ports "in" and "signal".
|
# Start by placing a waveguide and renaming its ports to match the circuit-level
|
||||||
|
# names we want to use while assembling the design.
|
||||||
circ.place('wg10', offset=(0, 0), port_map={'left': 'in', 'right': 'signal'})
|
circ.place('wg10', offset=(0, 0), port_map={'left': 'in', 'right': 'signal'})
|
||||||
|
|
||||||
# Extend the signal path by attaching the "left" port of a waveguide.
|
# Extend the signal path by attaching another waveguide.
|
||||||
# Since there is only one other port ("right") on the waveguide we
|
# Because `wg10` only has one unattached port left after the plug, Masque can
|
||||||
# are attaching (wg10), it automatically inherits the name "signal".
|
# infer that it should keep the name `signal`.
|
||||||
circ.plug('wg10', {'signal': 'left'})
|
circ.plug('wg10', {'signal': 'left'})
|
||||||
|
|
||||||
# We could have done the following instead:
|
# We could have done the following instead:
|
||||||
|
|
@ -268,8 +278,8 @@ def main(interactive: bool = True) -> None:
|
||||||
# lib['my_circuit'] = circ_pat
|
# lib['my_circuit'] = circ_pat
|
||||||
# circ_pat.place(lib.abstract('wg10'), ...)
|
# circ_pat.place(lib.abstract('wg10'), ...)
|
||||||
# circ_pat.plug(lib.abstract('wg10'), ...)
|
# circ_pat.plug(lib.abstract('wg10'), ...)
|
||||||
# but `Builder` lets us omit some of the repetition of `lib.abstract(...)`, and uses similar
|
# but `Pather` removes some repeated `lib.abstract(...)` boilerplate and keeps
|
||||||
# syntax to `Pather` and `RenderPather`, which add wire/waveguide routing functionality.
|
# the assembly code focused on port-level intent.
|
||||||
|
|
||||||
# Attach a y-splitter to the signal path.
|
# Attach a y-splitter to the signal path.
|
||||||
# Since the y-splitter has 3 ports total, we can't auto-inherit the
|
# Since the y-splitter has 3 ports total, we can't auto-inherit the
|
||||||
|
|
@ -281,13 +291,10 @@ def main(interactive: bool = True) -> None:
|
||||||
circ.plug('wg05', {'signal1': 'left'})
|
circ.plug('wg05', {'signal1': 'left'})
|
||||||
circ.plug('wg05', {'signal2': 'left'})
|
circ.plug('wg05', {'signal2': 'left'})
|
||||||
|
|
||||||
# Add a bend to both ports.
|
# Add a bend to both branches.
|
||||||
# Our bend's ports "left" and "right" refer to the original counterclockwise
|
# Our bend primitive is defined with a specific orientation, so choosing which
|
||||||
# orientation. We want the bends to turn in opposite directions, so we attach
|
# port to plug determines whether the path turns clockwise or counterclockwise.
|
||||||
# the "right" port to "signal1" to bend clockwise, and the "left" port
|
# We could also mirror one instance instead of using opposite ports.
|
||||||
# to "signal2" to bend counterclockwise.
|
|
||||||
# We could also use `mirrored=(True, False)` to mirror one of the devices
|
|
||||||
# and then use same device port on both paths.
|
|
||||||
circ.plug('bend0', {'signal1': 'right'})
|
circ.plug('bend0', {'signal1': 'right'})
|
||||||
circ.plug('bend0', {'signal2': 'left'})
|
circ.plug('bend0', {'signal2': 'left'})
|
||||||
|
|
||||||
|
|
@ -296,29 +303,26 @@ def main(interactive: bool = True) -> None:
|
||||||
circ.plug('l3cav', {'signal1': 'input'})
|
circ.plug('l3cav', {'signal1': 'input'})
|
||||||
circ.plug('wg10', {'signal1': 'left'})
|
circ.plug('wg10', {'signal1': 'left'})
|
||||||
|
|
||||||
# "signal2" just gets a single of equivalent length
|
# `signal2` gets a single waveguide of equivalent overall length.
|
||||||
circ.plug('wg28', {'signal2': 'left'})
|
circ.plug('wg28', {'signal2': 'left'})
|
||||||
|
|
||||||
# Now we bend both waveguides back towards each other
|
# Now bend both branches back towards each other.
|
||||||
circ.plug('bend0', {'signal1': 'right'})
|
circ.plug('bend0', {'signal1': 'right'})
|
||||||
circ.plug('bend0', {'signal2': 'left'})
|
circ.plug('bend0', {'signal2': 'left'})
|
||||||
circ.plug('wg05', {'signal1': 'left'})
|
circ.plug('wg05', {'signal1': 'left'})
|
||||||
circ.plug('wg05', {'signal2': 'left'})
|
circ.plug('wg05', {'signal2': 'left'})
|
||||||
|
|
||||||
# To join the waveguides, we attach a second y-junction.
|
# To join the branches, attach a second y-junction.
|
||||||
# We plug "signal1" into the "bot" port, and "signal2" into the "top" port.
|
# This succeeds only if both chosen ports agree on the same translation and
|
||||||
# The remaining port gets named "signal_out".
|
# rotation for the inserted device; otherwise Masque raises an exception.
|
||||||
# This operation would raise an exception if the ports did not line up
|
|
||||||
# correctly (i.e. they required different rotations or translations of the
|
|
||||||
# y-junction device).
|
|
||||||
circ.plug('ysplit', {'signal1': 'bot', 'signal2': 'top'}, {'in': 'signal_out'})
|
circ.plug('ysplit', {'signal1': 'bot', 'signal2': 'top'}, {'in': 'signal_out'})
|
||||||
|
|
||||||
# Finally, add some more waveguide to "signal_out".
|
# Finally, add some more waveguide to "signal_out".
|
||||||
circ.plug('wg10', {'signal_out': 'left'})
|
circ.plug('wg10', {'signal_out': 'left'})
|
||||||
|
|
||||||
# We can also add text labels for our circuit's ports.
|
# Bake the top-level port metadata into labels so it survives GDS export.
|
||||||
# They will appear at the uppermost hierarchy level, while the individual
|
# These labels appear on the circuit cell; individual child devices keep their
|
||||||
# device ports will appear further down, in their respective cells.
|
# own port labels in their own cells.
|
||||||
ports_to_data(circ.pattern)
|
ports_to_data(circ.pattern)
|
||||||
|
|
||||||
# Check if we forgot to include any patterns... ooops!
|
# Check if we forgot to include any patterns... ooops!
|
||||||
|
|
@ -330,12 +334,12 @@ def main(interactive: bool = True) -> None:
|
||||||
lib.add(shape_lib)
|
lib.add(shape_lib)
|
||||||
assert not lib.dangling_refs()
|
assert not lib.dangling_refs()
|
||||||
|
|
||||||
# We can visualize the design. Usually it's easier to just view the GDS.
|
# We can visualize the design directly, though opening the written GDS is often easier.
|
||||||
if interactive:
|
if interactive:
|
||||||
print('Visualizing... this step may be slow')
|
print('Visualizing... this step may be slow')
|
||||||
circ.pattern.visualize(lib)
|
circ.pattern.visualize(lib)
|
||||||
|
|
||||||
#Write out to GDS, only keeping patterns referenced by our circuit (including itself)
|
# Write out only the subtree reachable from our top cell.
|
||||||
subtree = lib.subtree('my_circuit') # don't include wg90, which we don't use
|
subtree = lib.subtree('my_circuit') # don't include wg90, which we don't use
|
||||||
check_valid_names(subtree.keys())
|
check_valid_names(subtree.keys())
|
||||||
writefile(subtree, 'circuit.gds', **GDS_OPTS)
|
writefile(subtree, 'circuit.gds', **GDS_OPTS)
|
||||||
|
|
|
||||||
|
|
@ -1,135 +1,133 @@
|
||||||
|
"""
|
||||||
|
Tutorial: authoring a mixed library with `LibraryBuilder`.
|
||||||
|
|
||||||
|
This example assumes you have already read `devices.py` and generated the
|
||||||
|
`circuit.gds` file it writes. The goal here is not the photonic-crystal geometry
|
||||||
|
itself, but rather how Masque lets you combine imported GDS cells with
|
||||||
|
python-generated recipes, then turn that declaration set into a normal library
|
||||||
|
for downstream assembly and writing.
|
||||||
|
"""
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from collections.abc import Sequence, Callable
|
|
||||||
from pprint import pformat
|
from pprint import pformat
|
||||||
|
|
||||||
import numpy
|
|
||||||
from numpy import pi
|
|
||||||
|
|
||||||
from masque import Pattern, Builder, LazyLibrary
|
from masque import ILibrary, LibraryBuilder, Pather, Pattern, PortLoadView, cell
|
||||||
from masque.file.gdsii import writefile, load_libraryfile
|
from masque.file.gdsii import writefile
|
||||||
|
from masque.file.gdsii.lazy import readfile
|
||||||
|
|
||||||
import pcgen
|
|
||||||
import basic_shapes
|
import basic_shapes
|
||||||
import devices
|
import devices
|
||||||
from devices import ports_to_data, 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:
|
||||||
# Define a `LazyLibrary`, which provides lazy evaluation for generating
|
builder = LibraryBuilder()
|
||||||
# patterns and lazy-loading of GDS contents.
|
cells = builder.cells
|
||||||
lib = LazyLibrary()
|
|
||||||
|
# Naming and export policy can be bound once without changing individual
|
||||||
|
# declarations. For example, a foundry-specific group could use:
|
||||||
|
#
|
||||||
|
# cells = builder.cells.prefixed(
|
||||||
|
# 'foundry_',
|
||||||
|
# facade=lambda proxy: devices.ports_to_data(proxy),
|
||||||
|
# )
|
||||||
|
#
|
||||||
|
# Dynamic names use the same view: cells[generated_name] = cell(factory)(...)
|
||||||
|
|
||||||
#
|
#
|
||||||
# Load some devices from a GDS file
|
# Load some devices from a GDS file
|
||||||
#
|
#
|
||||||
|
|
||||||
# Scan circuit.gds and prepare to lazy-load its contents
|
# Scan circuit.gds and prepare to lazy-load its contents. Port labels are
|
||||||
gds_lib, _properties = load_libraryfile('circuit.gds', postprocess=data_to_ports)
|
# imported on first materialization, but the raw source remains untouched
|
||||||
|
# until we build the final library.
|
||||||
|
gds_lib, _properties = readfile('circuit.gds')
|
||||||
|
builder.add_source(PortLoadView(gds_lib, layers=[(3, 0)], max_depth=1))
|
||||||
|
|
||||||
# Add it into the device library by providing a way to read port info
|
print('Registered imported cells:\n' + pformat(list(gds_lib.keys())))
|
||||||
# This maintains the lazy evaluation from above, so no patterns
|
|
||||||
# are actually read yet.
|
|
||||||
lib.add(gds_lib)
|
|
||||||
|
|
||||||
print('Patterns loaded from GDS into library:\n' + pformat(list(lib.keys())))
|
|
||||||
|
|
||||||
#
|
#
|
||||||
# Add some new devices to the library, this time from python code rather than GDS
|
# Register some new devices, this time from python code rather than GDS.
|
||||||
#
|
#
|
||||||
|
|
||||||
lib['triangle'] = lambda: basic_shapes.triangle(devices.RADIUS)
|
cells.triangle = 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)
|
||||||
|
cells.tri_wg05 = cell(devices.waveguide)(length=5, mirror_periods=5, **opts)
|
||||||
|
cells.tri_wg28 = cell(devices.waveguide)(length=28, mirror_periods=5, **opts)
|
||||||
|
cells.tri_bend0 = cell(devices.bend)(mirror_periods=5, **opts)
|
||||||
|
cells.tri_ysplit = cell(devices.y_splitter)(mirror_periods=5, **opts)
|
||||||
|
cells.tri_l3cav = cell(devices.perturbed_l3)(
|
||||||
|
xy_size=(4, 10),
|
||||||
|
**opts,
|
||||||
|
hole_lib=builder.library,
|
||||||
)
|
)
|
||||||
|
cells.mixed_wg_cav = cell(make_mixed_waveguide)(builder.library)
|
||||||
|
|
||||||
# Triangle-based variants. These are defined here, but they won't run until they're
|
print('Declared cells waiting to be built:\n' + pformat(list(builder.keys())))
|
||||||
# retrieved from the library.
|
|
||||||
lib['tri_wg10'] = lambda: devices.waveguide(length=10, mirror_periods=5, **opts)
|
|
||||||
lib['tri_wg05'] = lambda: devices.waveguide(length=5, mirror_periods=5, **opts)
|
|
||||||
lib['tri_wg28'] = lambda: devices.waveguide(length=28, mirror_periods=5, **opts)
|
|
||||||
lib['tri_bend0'] = lambda: devices.bend(mirror_periods=5, **opts)
|
|
||||||
lib['tri_ysplit'] = lambda: devices.y_splitter(mirror_periods=5, **opts)
|
|
||||||
lib['tri_l3cav'] = lambda: devices.perturbed_l3(xy_size=(4, 10), **opts, hole_lib=lib)
|
|
||||||
|
|
||||||
#
|
#
|
||||||
# Build a mixed waveguide with an L3 cavity in the middle
|
# Build the declaration set into a normal library.
|
||||||
#
|
#
|
||||||
|
|
||||||
# Immediately start building from an instance of the L3 cavity
|
built, report = builder.build()
|
||||||
circ2 = Builder(library=lib, ports='tri_l3cav')
|
print('Built library contains:\n' + pformat(list(built.keys())))
|
||||||
|
print('Build dependency graph:\n' + pformat(report.dependency_graph))
|
||||||
# First way to get abstracts is `lib.abstract(name)`
|
|
||||||
# We can use this syntax directly with `Pattern.plug()` and `Pattern.place()` as well as through `Builder`.
|
|
||||||
circ2.plug(lib.abstract('wg10'), {'input': 'right'})
|
|
||||||
|
|
||||||
# Second way to get abstracts is to use an AbstractView
|
|
||||||
# This also works directly with `Pattern.plug()` / `Pattern.place()`.
|
|
||||||
abstracts = lib.abstract_view()
|
|
||||||
circ2.plug(abstracts['wg10'], {'output': 'left'})
|
|
||||||
|
|
||||||
# Third way to specify an abstract works by automatically getting
|
|
||||||
# it from the library already within the Builder object.
|
|
||||||
# This wouldn't work if we only had a `Pattern` (not a `Builder`).
|
|
||||||
# Just pass the pattern name!
|
|
||||||
circ2.plug('tri_wg10', {'input': 'right'})
|
|
||||||
circ2.plug('tri_wg10', {'output': 'left'})
|
|
||||||
|
|
||||||
# Add the circuit to the device library.
|
|
||||||
lib['mixed_wg_cav'] = circ2.pattern
|
|
||||||
|
|
||||||
|
|
||||||
#
|
#
|
||||||
# Build a device that could plug into our mixed_wg_cav and joins the two ports
|
# Continue designing against the built library.
|
||||||
#
|
#
|
||||||
|
|
||||||
# We'll be designing against an existing device's interface...
|
# The built result behaves like a normal mutable library, so downstream code
|
||||||
circ3 = Builder.interface(source=circ2)
|
# can use Pather, abstract views, and writing without going back through the
|
||||||
|
# builder interface.
|
||||||
# ... that lets us continue from where we left off.
|
circ = Pather.interface(source='mixed_wg_cav', library=built)
|
||||||
circ3.plug('tri_bend0', {'input': 'right'})
|
circ.plug('tri_bend0', {'input': 'right'})
|
||||||
circ3.plug('tri_bend0', {'input': 'left'}, mirrored=True) # mirror since no tri y-symmetry
|
circ.plug('tri_bend0', {'input': 'left'}, mirrored=True) # mirror since no tri y-symmetry
|
||||||
circ3.plug('tri_bend0', {'input': 'right'})
|
circ.plug('tri_bend0', {'input': 'right'})
|
||||||
circ3.plug('bend0', {'output': 'left'})
|
circ.plug('bend0', {'output': 'left'})
|
||||||
circ3.plug('bend0', {'output': 'left'})
|
circ.plug('bend0', {'output': 'left'})
|
||||||
circ3.plug('bend0', {'output': 'left'})
|
circ.plug('bend0', {'output': 'left'})
|
||||||
circ3.plug('tri_wg10', {'input': 'right'})
|
circ.plug('tri_wg10', {'input': 'right'})
|
||||||
circ3.plug('tri_wg28', {'input': 'right'})
|
circ.plug('tri_wg28', {'input': 'right'})
|
||||||
circ3.plug('tri_wg10', {'input': 'right', 'output': 'left'})
|
circ.plug('tri_wg10', {'input': 'right', 'output': 'left'})
|
||||||
|
built['loop_segment'] = circ.pattern
|
||||||
lib['loop_segment'] = circ3.pattern
|
|
||||||
|
|
||||||
#
|
#
|
||||||
# Write all devices into a GDS file
|
# Write all devices into a GDS file.
|
||||||
#
|
#
|
||||||
print('Writing library to file...')
|
print('Writing library to file...')
|
||||||
writefile(lib, 'library.gds', **GDS_OPTS)
|
writefile(built, '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,11 +1,20 @@
|
||||||
"""
|
"""
|
||||||
Manual wire routing tutorial: Pather and BasicTool
|
Manual wire routing tutorial: Pather and primitive offers
|
||||||
"""
|
"""
|
||||||
from collections.abc import Callable
|
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, RenderPather, Library, Pattern, Port, layer_t, map_layers
|
from masque import Pather, Library, Pattern, Port, layer_t
|
||||||
from masque.builder.tools import BasicTool, PathTool
|
from masque.abstract import Abstract
|
||||||
|
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
|
||||||
|
|
||||||
|
|
@ -107,87 +116,336 @@ def map_layer(layer: layer_t) -> layer_t:
|
||||||
'M2': (20, 0),
|
'M2': (20, 0),
|
||||||
'V1': (30, 0),
|
'V1': (30, 0),
|
||||||
}
|
}
|
||||||
return layer_mapping.get(layer, layer)
|
if isinstance(layer, str):
|
||||||
|
return layer_mapping.get(layer, layer)
|
||||||
|
return layer
|
||||||
|
|
||||||
|
|
||||||
#
|
@dataclass(frozen=True, slots=True)
|
||||||
# Now we can start building up our library (collection of static cells) and pathing tools.
|
class WireStraightData:
|
||||||
#
|
length: float
|
||||||
# If any of the operations below are confusing, you can cross-reference against the `RenderPather`
|
out_transition: 'WireTransitionSpec | None' = None
|
||||||
# tutorial, which handles some things more explicitly (e.g. via placement) and simplifies others
|
|
||||||
# (e.g. geometry definition).
|
|
||||||
#
|
@dataclass(frozen=True, slots=True)
|
||||||
def main() -> None:
|
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]:
|
||||||
|
"""
|
||||||
|
Create some basic library elements and tools for drawing M1 and M2
|
||||||
|
"""
|
||||||
# Build some patterns (static cells) using the above functions and store them in a library
|
# Build some patterns (static cells) using the above functions and store them in a library
|
||||||
library = Library()
|
library = Library()
|
||||||
library['pad'] = make_pad()
|
library['pad'] = make_pad()
|
||||||
library['m1_bend'] = make_bend(layer='M1', ptype='m1wire', width=M1_WIDTH)
|
library['m1_bend'] = make_bend(layer='M1', ptype='m1wire', width=M1_WIDTH)
|
||||||
library['m2_bend'] = make_bend(layer='M2', ptype='m2wire', width=M2_WIDTH)
|
library['m2_bend'] = make_bend(layer='M2', ptype='m2wire', width=M2_WIDTH)
|
||||||
library['v1_via'] = make_via(
|
library['v1_via'] = make_via(
|
||||||
layer_top='M2',
|
layer_top = 'M2',
|
||||||
layer_via='V1',
|
layer_via = 'V1',
|
||||||
layer_bot='M1',
|
layer_bot = 'M1',
|
||||||
width_top=M2_WIDTH,
|
width_top = M2_WIDTH,
|
||||||
width_via=V1_WIDTH,
|
width_via = V1_WIDTH,
|
||||||
width_bot=M1_WIDTH,
|
width_bot = M1_WIDTH,
|
||||||
ptype_bot='m1wire',
|
ptype_bot = 'm1wire',
|
||||||
ptype_top='m2wire',
|
ptype_top = 'm2wire',
|
||||||
)
|
)
|
||||||
|
|
||||||
#
|
#
|
||||||
# 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)
|
|
||||||
#
|
#
|
||||||
# Note that while we use BasicTool for this tutorial, you can define your own `Tool`
|
# Unlike the reusable `AutoTool`, this tutorial tool exposes primitive offers
|
||||||
# with arbitrary logic inside -- e.g. with single-use bends, complex transition rules,
|
# directly: it tells `Pather` about native straight/bend primitives and about
|
||||||
# transmission line geometry, or other features.
|
# via adapters that can transition between M1 and M2 port types.
|
||||||
#
|
#
|
||||||
M1_tool = BasicTool(
|
via = library.abstract('v1_via')
|
||||||
straight = (
|
via_transitions = (
|
||||||
# First, we need a function which takes in a length and spits out an M1 wire
|
WireTransitionSpec(via, 'top', 'bottom'),
|
||||||
lambda length: make_straight_wire(layer='M1', ptype='m1wire', width=M1_WIDTH, length=length),
|
WireTransitionSpec(via, 'bottom', 'top'),
|
||||||
'input', # When we get a pattern from make_straight_wire, use the port named 'input' as the input
|
|
||||||
'output', # and use the port named 'output' as the output
|
|
||||||
),
|
|
||||||
bend = (
|
|
||||||
library.abstract('m1_bend'), # When we need a bend, we'll reference the pattern we generated earlier
|
|
||||||
'input', # To orient it clockwise, use the port named 'input' as the input
|
|
||||||
'output', # and 'output' as the output
|
|
||||||
),
|
|
||||||
transitions = { # We can automate transitions for different (normally incompatible) port types
|
|
||||||
'm2wire': ( # 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
|
|
||||||
),
|
|
||||||
},
|
|
||||||
default_out_ptype = 'm1wire', # Unless otherwise requested, we'll default to trying to stay on M1
|
|
||||||
)
|
)
|
||||||
|
|
||||||
M2_tool = BasicTool(
|
M1_tool = PrimitiveWireTool(
|
||||||
straight = (
|
layer = 'M1',
|
||||||
# Again, we use make_straight_wire, but this time we set parameters for M2
|
width = M1_WIDTH,
|
||||||
lambda length: make_straight_wire(layer='M2', ptype='m2wire', width=M2_WIDTH, length=length),
|
ptype = 'm1wire',
|
||||||
'input',
|
bend = library.abstract('m1_bend'),
|
||||||
'output',
|
transitions = via_transitions,
|
||||||
),
|
|
||||||
bend = (
|
|
||||||
library.abstract('m2_bend'), # and we use an M2 bend
|
|
||||||
'input',
|
|
||||||
'output',
|
|
||||||
),
|
|
||||||
transitions = {
|
|
||||||
'm1wire': (
|
|
||||||
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'
|
|
||||||
),
|
|
||||||
},
|
|
||||||
default_out_ptype = 'm2wire', # We default to trying to stay on M2
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
M2_tool = PrimitiveWireTool(
|
||||||
|
layer = 'M2',
|
||||||
|
width = M2_WIDTH,
|
||||||
|
ptype = 'm2wire',
|
||||||
|
bend = library.abstract('m2_bend'),
|
||||||
|
transitions = via_transitions,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 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
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# Now we can start building up our library (collection of static cells) and pathing tools.
|
||||||
|
#
|
||||||
|
# If any of the operations below are confusing, you can cross-reference against the deferred
|
||||||
|
# `Pather` tutorial, which handles some things more explicitly (e.g. via placement) and simplifies
|
||||||
|
# others (e.g. geometry definition).
|
||||||
|
#
|
||||||
|
def main() -> None:
|
||||||
|
library, M1_tool, M2_tool = prepare_tools()
|
||||||
|
|
||||||
#
|
#
|
||||||
# Create a new pather which writes to `library` and uses `M2_tool` as its default tool.
|
# Create a new pather which writes to `library` and uses `M2_tool` as its default tool.
|
||||||
# Then, place some pads and start routing wires!
|
# Then, place some pads and start routing wires!
|
||||||
|
|
@ -203,27 +461,25 @@ def main() -> None:
|
||||||
|
|
||||||
# Path VCC forward (in this case south) and turn clockwise 90 degrees (ccw=False)
|
# Path VCC forward (in this case south) and turn clockwise 90 degrees (ccw=False)
|
||||||
# The total distance forward (including the bend's forward component) must be 6um
|
# The total distance forward (including the bend's forward component) must be 6um
|
||||||
pather.path('VCC', ccw=False, length=6_000)
|
pather.cw('VCC', 6_000)
|
||||||
|
|
||||||
# Now path VCC to x=0. This time, don't include any bend (ccw=None).
|
# Now path VCC to x=0. This time, don't include any bend.
|
||||||
# Note that if we tried y=0 here, we would get an error since the VCC port is facing in the x-direction.
|
# Note that if we tried y=0 here, we would get an error since the VCC port is facing in the x-direction.
|
||||||
pather.path_to('VCC', ccw=None, x=0)
|
pather.straight('VCC', x=0)
|
||||||
|
|
||||||
# Path GND forward by 5um, turning clockwise 90 degrees.
|
# Path GND forward by 5um, turning clockwise 90 degrees.
|
||||||
# This time we use shorthand (bool(0) == False) and omit the parameter labels
|
pather.cw('GND', 5_000)
|
||||||
# Note that although ccw=0 is equivalent to ccw=False, ccw=None is not!
|
|
||||||
pather.path('GND', 0, 5_000)
|
|
||||||
|
|
||||||
# This time, path GND until it matches the current x-coordinate of VCC. Don't place a bend.
|
# This time, path GND until it matches the current x-coordinate of VCC. Don't place a bend.
|
||||||
pather.path_to('GND', None, x=pather['VCC'].offset[0])
|
pather.straight('GND', x=pather['VCC'].offset[0])
|
||||||
|
|
||||||
# Now, start using M1_tool for GND.
|
# Now, start using M1_tool for GND.
|
||||||
# Since we have defined an M2-to-M1 transition for BasicPather, we don't need to place one ourselves.
|
# Since we have defined an M2-to-M1 transition for Pather, we don't need to place one ourselves.
|
||||||
# If we wanted to place our via manually, we could add `pather.plug('m1_via', {'GND': 'top'})` here
|
# If we wanted to place our via manually, we could add `pather.plug('m1_via', {'GND': 'top'})` here
|
||||||
# and achieve the same result without having to define any transitions in M1_tool.
|
# and achieve the same result without having to define any transitions in M1_tool.
|
||||||
# Note that even though we have changed the tool used for GND, the via doesn't get placed until
|
# Note that even though we have changed the tool used for GND, the via doesn't get placed until
|
||||||
# the next time we draw a path on GND (the pather.mpath() statement below).
|
# the next time we route GND (the `pather.ccw()` call below).
|
||||||
pather.retool(M1_tool, keys=['GND'])
|
pather.retool(M1_tool, keys='GND')
|
||||||
|
|
||||||
# Bundle together GND and VCC, and path the bundle forward and counterclockwise.
|
# Bundle together GND and VCC, and path the bundle forward and counterclockwise.
|
||||||
# Pick the distance so that the leading/outermost wire (in this case GND) ends up at x=-10_000.
|
# Pick the distance so that the leading/outermost wire (in this case GND) ends up at x=-10_000.
|
||||||
|
|
@ -231,7 +487,7 @@ def main() -> None:
|
||||||
#
|
#
|
||||||
# Since we recently retooled GND, its path starts with a via down to M1 (included in the distance
|
# Since we recently retooled GND, its path starts with a via down to M1 (included in the distance
|
||||||
# calculation), and its straight segment and bend will be drawn using M1 while VCC's are drawn with M2.
|
# calculation), and its straight segment and bend will be drawn using M1 while VCC's are drawn with M2.
|
||||||
pather.mpath(['GND', 'VCC'], ccw=True, xmax=-10_000, spacing=5_000)
|
pather.ccw(['GND', 'VCC'], xmax=-10_000, spacing=5_000)
|
||||||
|
|
||||||
# Now use M1_tool as the default tool for all ports/signals.
|
# Now use M1_tool as the default tool for all ports/signals.
|
||||||
# Since VCC does not have an explicitly assigned tool, it will now transition down to M1.
|
# Since VCC does not have an explicitly assigned tool, it will now transition down to M1.
|
||||||
|
|
@ -241,38 +497,37 @@ def main() -> None:
|
||||||
# The total extension (travel distance along the forward direction) for the longest segment (in
|
# The total extension (travel distance along the forward direction) for the longest segment (in
|
||||||
# this case the segment being added to GND) should be exactly 50um.
|
# this case the segment being added to GND) should be exactly 50um.
|
||||||
# After turning, the wire pitch should be reduced only 1.2um.
|
# After turning, the wire pitch should be reduced only 1.2um.
|
||||||
pather.mpath(['GND', 'VCC'], ccw=True, emax=50_000, spacing=1_200)
|
pather.ccw(['GND', 'VCC'], emax=50_000, spacing=1_200)
|
||||||
|
|
||||||
# Make a U-turn with the bundle and expand back out to 4.5um wire pitch.
|
# Make a U-turn with the bundle and expand back out to 4.5um wire pitch.
|
||||||
# Here, emin specifies the travel distance for the shortest segment. For the first mpath() call
|
# Here, emin specifies the travel distance for the shortest segment. For the first call
|
||||||
# that applies to VCC, and for teh second call, that applies to GND; the relative lengths of the
|
# that applies to VCC, and for the second call, that applies to GND; the relative lengths of the
|
||||||
# segments depend on their starting positions and their ordering within the bundle.
|
# segments depend on their starting positions and their ordering within the bundle.
|
||||||
pather.mpath(['GND', 'VCC'], ccw=False, emin=1_000, spacing=1_200)
|
pather.cw(['GND', 'VCC'], emin=1_000, spacing=1_200)
|
||||||
pather.mpath(['GND', 'VCC'], ccw=False, emin=2_000, spacing=4_500)
|
pather.cw(['GND', 'VCC'], emin=2_000, spacing=4_500)
|
||||||
|
|
||||||
# Now, set the default tool back to M2_tool. Note that GND remains on M1 since it has been
|
# Now, set the default tool back to M2_tool. Note that GND remains on M1 since it has been
|
||||||
# explicitly assigned a tool. We could `del pather.tools['GND']` to force it to use the default.
|
# explicitly assigned a tool.
|
||||||
pather.retool(M2_tool)
|
pather.retool(M2_tool)
|
||||||
|
|
||||||
# Now path both ports to x=-28_000.
|
# Now path both ports to x=-28_000.
|
||||||
# When ccw is not None, xmin constrains the trailing/innermost port to stop at the target x coordinate,
|
# With ccw=None, all ports stop at the same coordinate, and so specifying xmin= or xmax= is
|
||||||
# However, with ccw=None, all ports stop at the same coordinate, and so specifying xmin= or xmax= is
|
|
||||||
# equivalent.
|
# equivalent.
|
||||||
pather.mpath(['GND', 'VCC'], None, xmin=-28_000)
|
pather.straight(['GND', 'VCC'], xmin=-28_000)
|
||||||
|
|
||||||
# Further extend VCC out to x=-50_000, and specify that we would like to get an output on M1.
|
# Further extend VCC out to x=-50_000, and specify that we would like to get an output on M1.
|
||||||
# This results in a via at the end of the wire (instead of having one at the start like we got
|
# This results in a via at the end of the wire (instead of having one at the start like we got
|
||||||
# when using pather.retool().
|
# when using pather.retool().
|
||||||
pather.path_to('VCC', None, -50_000, out_ptype='m1wire')
|
pather.straight('VCC', x=-50_000, out_ptype='m1wire')
|
||||||
|
|
||||||
# Now extend GND out to x=-50_000, using M2 for a portion of the path.
|
# Now extend GND out to x=-50_000, using M2 for a portion of the path.
|
||||||
# We can use `pather.toolctx()` to temporarily retool, instead of calling `retool()` twice.
|
# We can use `pather.toolctx()` to temporarily retool, instead of calling `retool()` twice.
|
||||||
with pather.toolctx(M2_tool, keys=['GND']):
|
with pather.toolctx(M2_tool, keys='GND'):
|
||||||
pather.path_to('GND', None, -40_000)
|
pather.straight('GND', x=-40_000)
|
||||||
pather.path_to('GND', None, -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_BasicTool'] = pather.pattern
|
library['Pather_and_PrimitiveOffers'] = 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)
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
Routines for creating normalized 2D lattices and common photonic crystal
|
Routines for creating normalized 2D lattices and common photonic crystal
|
||||||
cavity designs.
|
cavity designs.
|
||||||
"""
|
"""
|
||||||
from collection.abc import Sequence
|
from collections.abc import Sequence
|
||||||
|
|
||||||
import numpy
|
import numpy
|
||||||
from numpy.typing import ArrayLike, NDArray
|
from numpy.typing import ArrayLike, NDArray
|
||||||
|
|
@ -50,7 +50,7 @@ def triangular_lattice(
|
||||||
elif origin == 'corner':
|
elif origin == 'corner':
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
raise Exception(f'Invalid value for `origin`: {origin}')
|
raise ValueError(f'Invalid value for `origin`: {origin}')
|
||||||
|
|
||||||
return xy[xy[:, 0].argsort(), :]
|
return xy[xy[:, 0].argsort(), :]
|
||||||
|
|
||||||
|
|
@ -197,12 +197,12 @@ def ln_defect(
|
||||||
`[[x0, y0], [x1, y1], ...]` for all the holes
|
`[[x0, y0], [x1, y1], ...]` for all the holes
|
||||||
"""
|
"""
|
||||||
if defect_length % 2 != 1:
|
if defect_length % 2 != 1:
|
||||||
raise Exception('defect_length must be odd!')
|
raise ValueError('defect_length must be odd!')
|
||||||
p = triangular_lattice([2 * d + 1 for d in mirror_dims])
|
pp = triangular_lattice([2 * dd + 1 for dd in mirror_dims])
|
||||||
half_length = numpy.floor(defect_length / 2)
|
half_length = numpy.floor(defect_length / 2)
|
||||||
hole_nums = numpy.arange(-half_length, half_length + 1)
|
hole_nums = numpy.arange(-half_length, half_length + 1)
|
||||||
holes_to_keep = numpy.in1d(p[:, 0], hole_nums, invert=True)
|
holes_to_keep = numpy.isin(pp[:, 0], hole_nums, invert=True)
|
||||||
return p[numpy.logical_or(holes_to_keep, p[:, 1] != 0), ]
|
return pp[numpy.logical_or(holes_to_keep, pp[:, 1] != 0), :]
|
||||||
|
|
||||||
|
|
||||||
def ln_shift_defect(
|
def ln_shift_defect(
|
||||||
|
|
@ -248,7 +248,7 @@ def ln_shift_defect(
|
||||||
for sign in (-1, 1):
|
for sign in (-1, 1):
|
||||||
x_val = sign * (x_removed + ind + 1)
|
x_val = sign * (x_removed + ind + 1)
|
||||||
which = numpy.logical_and(xyr[:, 0] == x_val, xyr[:, 1] == 0)
|
which = numpy.logical_and(xyr[:, 0] == x_val, xyr[:, 1] == 0)
|
||||||
xyr[which, ] = (x_val + numpy.sign(x_val) * shifts_a[ind], 0, shifts_r[ind])
|
xyr[which, :] = (x_val + numpy.sign(x_val) * shifts_a[ind], 0, shifts_r[ind])
|
||||||
|
|
||||||
return xyr
|
return xyr
|
||||||
|
|
||||||
|
|
@ -309,7 +309,7 @@ def l3_shift_perturbed_defect(
|
||||||
|
|
||||||
# which holes should be perturbed? (xs[[3, 7]], ys[1]) and (xs[[2, 6]], ys[2])
|
# which holes should be perturbed? (xs[[3, 7]], ys[1]) and (xs[[2, 6]], ys[2])
|
||||||
perturbed_holes = ((xs[a], ys[b]) for a, b in ((3, 1), (7, 1), (2, 2), (6, 2)))
|
perturbed_holes = ((xs[a], ys[b]) for a, b in ((3, 1), (7, 1), (2, 2), (6, 2)))
|
||||||
for row in xyr:
|
for xy in perturbed_holes:
|
||||||
if numpy.fabs(row) in perturbed_holes:
|
which = (numpy.fabs(xyr[:, :2]) == xy).all(axis=1)
|
||||||
row[2] = perturbed_radius
|
xyr[which, 2] = perturbed_radius
|
||||||
return xyr
|
return xyr
|
||||||
|
|
|
||||||
170
examples/tutorial/port_pather.py
Normal file
170
examples/tutorial/port_pather.py
Normal file
|
|
@ -0,0 +1,170 @@
|
||||||
|
"""
|
||||||
|
PortPather tutorial: Using .at() syntax
|
||||||
|
"""
|
||||||
|
from masque import Pather, Pattern, Port, R90
|
||||||
|
from masque.file.gdsii import writefile
|
||||||
|
|
||||||
|
from basic_shapes import GDS_OPTS
|
||||||
|
from pather import map_layer, prepare_tools
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
# Reuse the same patterns (pads, bends, vias) and tools as in pather.py
|
||||||
|
library, M1_tool, M2_tool = prepare_tools()
|
||||||
|
|
||||||
|
# Create a deferred Pather and place some initial pads (same as Pather tutorial)
|
||||||
|
rpather = Pather(library, tools=M2_tool, render='deferred')
|
||||||
|
|
||||||
|
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.pattern.label(layer='M2', string='VCC', offset=(18e3, 30e3))
|
||||||
|
rpather.pattern.label(layer='M2', string='GND', offset=(18e3, 60e3))
|
||||||
|
|
||||||
|
#
|
||||||
|
# Routing with .at() chaining
|
||||||
|
#
|
||||||
|
# The .at(port_name) method returns a PortPather object which wraps the Pather
|
||||||
|
# and remembers the selected port(s). This allows method chaining.
|
||||||
|
|
||||||
|
# Route VCC: 6um South, then West to x=0.
|
||||||
|
# (Note: since the port points North into the pad, trace() moves South by default)
|
||||||
|
(rpather.at('VCC')
|
||||||
|
.trace(False, length=6_000) # Move South, turn West (Clockwise)
|
||||||
|
.trace_to(None, x=0) # Continue West to x=0
|
||||||
|
)
|
||||||
|
|
||||||
|
# Route GND: 5um South, then West to match VCC's x-coordinate.
|
||||||
|
rpather.at('GND').trace(False, length=5_000).trace_to(None, x=rpather['VCC'].x)
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# Tool management and manual plugging
|
||||||
|
#
|
||||||
|
# We can use .retool() to change the tool for specific ports.
|
||||||
|
# We can also use .plug() directly on a PortPather.
|
||||||
|
|
||||||
|
# Manually add a via to GND and switch to M1_tool for subsequent segments
|
||||||
|
(rpather.at('GND')
|
||||||
|
.plug('v1_via', 'top')
|
||||||
|
.retool(M1_tool) # this only retools the 'GND' port
|
||||||
|
)
|
||||||
|
|
||||||
|
# We can also pass multiple ports to .at(), and then route them together.
|
||||||
|
# Here we bundle them, turn South, and retool both to M1 (VCC gets an auto-via).
|
||||||
|
(rpather.at(['GND', 'VCC'])
|
||||||
|
.trace(True, xmax=-10_000, spacing=5_000) # Move West to -10k, turn South
|
||||||
|
.retool(M1_tool) # Retools both GND and VCC
|
||||||
|
.set_spacing(1_200) # Default bundle spacing for later bends
|
||||||
|
.trace(True, emax=50_000) # Turn East, moves 50um extension
|
||||||
|
.trace(False, emin=1_000) # U-turn back South
|
||||||
|
.trace(False, emin=2_000, spacing=4_500) # U-turn back West, overriding the default spacing
|
||||||
|
)
|
||||||
|
|
||||||
|
# Retool VCC back to M2 and move both to x=-28k
|
||||||
|
rpather.at('VCC').retool(M2_tool)
|
||||||
|
rpather.at(['GND', 'VCC']).trace(None, xmin=-28_000)
|
||||||
|
|
||||||
|
# Final segments to -50k
|
||||||
|
rpather.at('VCC').trace_to(None, x=-50_000, out_ptype='m1wire')
|
||||||
|
with rpather.at('GND').toolctx(M2_tool):
|
||||||
|
rpather.at('GND').trace_to(None, x=-40_000)
|
||||||
|
rpather.at('GND').trace_to(None, x=-50_000)
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# Branching with mark and fork
|
||||||
|
#
|
||||||
|
# .mark(new_name) creates a port copy and keeps the original selected.
|
||||||
|
# .fork(new_name) creates a port copy and selects the new one.
|
||||||
|
|
||||||
|
# Create a tap on GND
|
||||||
|
(rpather.at('GND')
|
||||||
|
.trace(None, length=5_000) # Move GND further West
|
||||||
|
.mark('GND_TAP') # Mark this location for a later branch
|
||||||
|
.jog(offset=-10_000, length=10_000) # Continue GND with an S-bend
|
||||||
|
)
|
||||||
|
|
||||||
|
# Branch VCC and follow the new branch
|
||||||
|
(rpather.at('VCC')
|
||||||
|
.trace(None, length=5_000)
|
||||||
|
.fork('VCC_BRANCH') # We are now manipulating 'VCC_BRANCH'
|
||||||
|
.trace(True, length=5_000) # VCC_BRANCH turns South
|
||||||
|
)
|
||||||
|
# The original 'VCC' port remains at x=-55k, y=VCC.y
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# Port set management: add, drop, rename, delete
|
||||||
|
#
|
||||||
|
|
||||||
|
# Route the GND_TAP we saved earlier.
|
||||||
|
(rpather.at('GND_TAP')
|
||||||
|
.retool(M1_tool)
|
||||||
|
.trace(True, length=10_000) # Turn South
|
||||||
|
.rename('GND_FEED') # Give it a more descriptive name
|
||||||
|
.retool(M1_tool) # Re-apply tool to the new name
|
||||||
|
)
|
||||||
|
|
||||||
|
# We can manage the active set of ports in a PortPather
|
||||||
|
pp = rpather.at(['VCC_BRANCH', 'GND_FEED'])
|
||||||
|
pp.select('GND') # Now tracking 3 ports
|
||||||
|
pp.deselect('VCC_BRANCH') # Now tracking 2 ports: GND_FEED, GND
|
||||||
|
pp.trace(None, each=5_000) # Move both 5um forward (length > transition size)
|
||||||
|
|
||||||
|
# We can also delete ports from the pather entirely
|
||||||
|
rpather.at('VCC').delete() # VCC is gone (we have VCC_BRANCH instead)
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# Advanced Connections: trace_into
|
||||||
|
#
|
||||||
|
# trace_into routes FROM the selected port TO a target port.
|
||||||
|
|
||||||
|
# Create a destination component
|
||||||
|
dest_ports = {
|
||||||
|
'in_A': Port((0, 0), rotation=R90, ptype='m2wire'),
|
||||||
|
'in_B': Port((5_000, 0), rotation=R90, ptype='m2wire')
|
||||||
|
}
|
||||||
|
library['dest'] = Pattern(ports=dest_ports)
|
||||||
|
# Place dest so that its ports are to the West and South of our current wires.
|
||||||
|
# Rotating by pi/2 makes the ports face West (pointing East).
|
||||||
|
rpather.place('dest', offset=(-100_000, -100_000), rotation=R90, port_map={'in_A': 'DEST_A', 'in_B': 'DEST_B'})
|
||||||
|
|
||||||
|
# Connect GND_FEED to DEST_A
|
||||||
|
# Since GND_FEED is moving South and DEST_A faces West, a single bend will suffice.
|
||||||
|
rpather.at('GND_FEED').trace_into('DEST_A')
|
||||||
|
|
||||||
|
# Connect VCC_BRANCH to DEST_B
|
||||||
|
rpather.at('VCC_BRANCH').trace_into('DEST_B')
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# Direct Port Transformations and Metadata
|
||||||
|
#
|
||||||
|
(rpather.at('GND')
|
||||||
|
.set_ptype('m1wire') # Change metadata
|
||||||
|
.translate((1000, 0)) # Shift the port 1um East
|
||||||
|
.rotate(R90 / 2) # Rotate it 45 degrees
|
||||||
|
.set_rotation(R90) # Force it to face West
|
||||||
|
)
|
||||||
|
|
||||||
|
# Demonstrate .plugged() to acknowledge a manual connection
|
||||||
|
# (Normally used when you place components so their ports perfectly overlap)
|
||||||
|
rpather.add_port_pair(offset=(0, 0), names=('TMP1', 'TMP2'))
|
||||||
|
rpather.at('TMP1').plugged('TMP2') # Removes both ports
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# Rendering and Saving
|
||||||
|
#
|
||||||
|
# Since routing is deferred, we must call .render() to generate the geometry.
|
||||||
|
rpather.render()
|
||||||
|
|
||||||
|
library['PortPather_Tutorial'] = rpather.pattern
|
||||||
|
library.map_layers(map_layer)
|
||||||
|
writefile(library, 'port_pather.gds', **GDS_OPTS)
|
||||||
|
print("Tutorial complete. Output written to port_pather.gds")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -1,9 +1,8 @@
|
||||||
"""
|
"""
|
||||||
Manual wire routing tutorial: RenderPather an PathTool
|
Manual wire routing tutorial: deferred Pather and PathTool
|
||||||
"""
|
"""
|
||||||
from collections.abc import Callable
|
from masque import Pather, Library
|
||||||
from masque import RenderPather, Library, Pattern, Port, layer_t, map_layers
|
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
|
||||||
|
|
@ -12,9 +11,9 @@ from pather import M1_WIDTH, V1_WIDTH, M2_WIDTH, map_layer, make_pad, make_via
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
#
|
#
|
||||||
# To illustrate the advantages of using `RenderPather`, we use `PathTool` instead
|
# To illustrate deferred routing with `Pather`, we use `PathTool` instead
|
||||||
# of `BasicTool`. `PathTool` lacks some sophistication (e.g. no automatic transitions)
|
# of `AutoTool`. `PathTool` lacks some sophistication (e.g. no automatic transitions)
|
||||||
# but when used with `RenderPather`, it can consolidate multiple routing steps into
|
# but when used with `Pather(render='deferred')`, 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`
|
||||||
|
|
@ -25,66 +24,68 @@ def main() -> None:
|
||||||
library = Library()
|
library = Library()
|
||||||
library['pad'] = make_pad()
|
library['pad'] = make_pad()
|
||||||
library['v1_via'] = make_via(
|
library['v1_via'] = make_via(
|
||||||
layer_top='M2',
|
layer_top = 'M2',
|
||||||
layer_via='V1',
|
layer_via = 'V1',
|
||||||
layer_bot='M1',
|
layer_bot = 'M1',
|
||||||
width_top=M2_WIDTH,
|
width_top = M2_WIDTH,
|
||||||
width_via=V1_WIDTH,
|
width_via = V1_WIDTH,
|
||||||
width_bot=M1_WIDTH,
|
width_bot = M1_WIDTH,
|
||||||
ptype_bot='m1wire',
|
ptype_bot = 'm1wire',
|
||||||
ptype_top='m2wire',
|
ptype_top = 'm2wire',
|
||||||
)
|
)
|
||||||
|
|
||||||
# `PathTool` is more limited than `BasicTool`. It only generates one type of shape
|
# `PathTool` is more limited than `AutoTool`. It only generates one type of shape
|
||||||
# (`Path`), so it only needs to know what layer to draw on, what width to draw with,
|
# (`Path`), so it only needs to know what layer to draw on, what width to draw with,
|
||||||
# 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 = RenderPather(tools=M2_ptool, library=library)
|
rpather = Pather(tools=M2_ptool, library=library, render='deferred')
|
||||||
|
|
||||||
# As in the pather tutorial, we make soem 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'})
|
||||||
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'})
|
||||||
rpather.pattern.label(layer='M2', string='VCC', offset=(18e3, 30e3))
|
rpather.pattern.label(layer='M2', string='VCC', offset=(18e3, 30e3))
|
||||||
rpather.pattern.label(layer='M2', string='GND', offset=(18e3, 60e3))
|
rpather.pattern.label(layer='M2', string='GND', offset=(18e3, 60e3))
|
||||||
|
|
||||||
# ...and start routing the signals.
|
# ...and start routing the signals.
|
||||||
rpather.path('VCC', ccw=False, length=6_000)
|
rpather.cw('VCC', 6_000)
|
||||||
rpather.path_to('VCC', ccw=None, x=0)
|
rpather.straight('VCC', x=0)
|
||||||
rpather.path('GND', 0, 5_000)
|
rpather.cw('GND', 5_000)
|
||||||
rpather.path_to('GND', None, x=rpather['VCC'].offset[0])
|
rpather.straight('GND', x=rpather.pattern['VCC'].x)
|
||||||
|
|
||||||
# `PathTool` doesn't know how to transition betwen metal layers, so we have to
|
# `PathTool` doesn't know how to transition betwen metal layers, so we have to
|
||||||
# `plug` the via into the GND wire ourselves.
|
# `plug` the via into the GND wire ourselves.
|
||||||
rpather.plug('v1_via', {'GND': 'top'})
|
rpather.plug('v1_via', {'GND': 'top'})
|
||||||
rpather.retool(M1_ptool, keys=['GND'])
|
rpather.retool(M1_ptool, keys='GND')
|
||||||
rpather.mpath(['GND', 'VCC'], ccw=True, xmax=-10_000, spacing=5_000)
|
rpather.ccw(['GND', 'VCC'], xmax=-10_000, spacing=5_000)
|
||||||
|
|
||||||
# Same thing on the VCC wire when it goes down to M1.
|
# Same thing on the VCC wire when it goes down to M1.
|
||||||
rpather.plug('v1_via', {'VCC': 'top'})
|
rpather.plug('v1_via', {'VCC': 'top'})
|
||||||
rpather.retool(M1_ptool)
|
rpather.retool(M1_ptool)
|
||||||
rpather.mpath(['GND', 'VCC'], ccw=True, emax=50_000, spacing=1_200)
|
rpather.ccw(['GND', 'VCC'], emax=50_000, spacing=1_200)
|
||||||
rpather.mpath(['GND', 'VCC'], ccw=False, emin=1_000, spacing=1_200)
|
rpather.cw(['GND', 'VCC'], emin=1_000, spacing=1_200)
|
||||||
rpather.mpath(['GND', 'VCC'], ccw=False, emin=2_000, spacing=4_500)
|
rpather.cw(['GND', 'VCC'], emin=2_000, spacing=4_500)
|
||||||
|
|
||||||
# And again when VCC goes back up to M2.
|
# And again when VCC goes back up to M2.
|
||||||
rpather.plug('v1_via', {'VCC': 'bottom'})
|
rpather.plug('v1_via', {'VCC': 'bottom'})
|
||||||
rpather.retool(M2_ptool)
|
rpather.retool(M2_ptool)
|
||||||
rpather.mpath(['GND', 'VCC'], None, xmin=-28_000)
|
rpather.straight(['GND', 'VCC'], xmin=-28_000)
|
||||||
|
|
||||||
# Finally, since PathTool has no conception of transitions, we can't
|
# Finally, since PathTool has no conception of transitions, we can't
|
||||||
# just ask it to transition to an 'm1wire' port at the end of the final VCC segment.
|
# just ask it to transition to an 'm1wire' port at the end of the final VCC segment.
|
||||||
# Instead, we have to calculate the via size ourselves, and adjust the final position
|
# Instead, we have to calculate the via size ourselves, and adjust the final position
|
||||||
# to account for it.
|
# to account for it.
|
||||||
via_size = abs(
|
v1pat = library['v1_via']
|
||||||
library['v1_via'].ports['top'].offset[0]
|
via_size = abs(v1pat.ports['top'].x - v1pat.ports['bottom'].x)
|
||||||
- library['v1_via'].ports['bottom'].offset[0]
|
|
||||||
)
|
# alternatively, via_size = v1pat.ports['top'].measure_travel(v1pat.ports['bottom'])[0][0]
|
||||||
rpather.path_to('VCC', None, -50_000 + via_size)
|
# would take into account the port orientations if we didn't already know they're along x
|
||||||
|
rpather.straight('VCC', x=-50_000 + via_size)
|
||||||
rpather.plug('v1_via', {'VCC': 'top'})
|
rpather.plug('v1_via', {'VCC': 'top'})
|
||||||
|
|
||||||
|
# Render the path we defined
|
||||||
rpather.render()
|
rpather.render()
|
||||||
library['RenderPather_and_PathTool'] = rpather.pattern
|
library['Deferred_Pather_and_PathTool'] = rpather.pattern
|
||||||
|
|
||||||
|
|
||||||
# Convert from text-based layers to numeric layers for GDS, and output the file
|
# Convert from text-based layers to numeric layers for GDS, and output the file
|
||||||
|
|
|
||||||
|
|
@ -42,6 +42,7 @@ 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,
|
||||||
|
|
@ -55,16 +56,27 @@ from .pattern import (
|
||||||
map_targets as map_targets,
|
map_targets as map_targets,
|
||||||
chain_elements as chain_elements,
|
chain_elements as chain_elements,
|
||||||
)
|
)
|
||||||
|
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,
|
||||||
|
|
@ -72,13 +84,17 @@ from .ports import (
|
||||||
)
|
)
|
||||||
from .abstract import Abstract as Abstract
|
from .abstract import Abstract as Abstract
|
||||||
from .builder import (
|
from .builder import (
|
||||||
Builder as Builder,
|
|
||||||
Tool as Tool,
|
Tool as Tool,
|
||||||
|
ToolContractError as ToolContractError,
|
||||||
Pather as Pather,
|
Pather as Pather,
|
||||||
RenderPather as RenderPather,
|
RouteError as RouteError,
|
||||||
|
RouteFailureDetails as RouteFailureDetails,
|
||||||
|
RouteFailurePolicy as RouteFailurePolicy,
|
||||||
|
MinimumStatus as MinimumStatus,
|
||||||
RenderStep as RenderStep,
|
RenderStep as RenderStep,
|
||||||
BasicTool as BasicTool,
|
AutoTool as AutoTool,
|
||||||
PathTool as PathTool,
|
PathTool as PathTool,
|
||||||
|
PortPather as PortPather,
|
||||||
)
|
)
|
||||||
from .utils import (
|
from .utils import (
|
||||||
ports2data as ports2data,
|
ports2data as ports2data,
|
||||||
|
|
@ -90,5 +106,5 @@ from .utils import (
|
||||||
|
|
||||||
__author__ = 'Jan Petykiewicz'
|
__author__ = 'Jan Petykiewicz'
|
||||||
|
|
||||||
__version__ = '3.3'
|
__version__ = '4.0a2'
|
||||||
version = __version__ # legacy
|
version = __version__ # legacy
|
||||||
|
|
|
||||||
|
|
@ -8,22 +8,20 @@ from numpy.typing import ArrayLike
|
||||||
from .ref import Ref
|
from .ref import Ref
|
||||||
from .ports import PortList, Port
|
from .ports import PortList, Port
|
||||||
from .utils import rotation_matrix_2d
|
from .utils import rotation_matrix_2d
|
||||||
|
from .traits import Mirrorable
|
||||||
#if TYPE_CHECKING:
|
|
||||||
# from .builder import Builder, Tool
|
|
||||||
# from .library import ILibrary
|
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class Abstract(PortList):
|
class Abstract(PortList, Mirrorable):
|
||||||
"""
|
"""
|
||||||
An `Abstract` is a container for a name and associated ports.
|
An `Abstract` is a container for a name and associated ports.
|
||||||
|
|
||||||
When snapping a sub-component to an existing pattern, only the name (not contained
|
When snapping a sub-component to an existing pattern, only the name (not contained
|
||||||
in a `Pattern` object) and port info is needed, and not the geometry itself.
|
in a `Pattern` object) and port info is needed, and not the geometry itself.
|
||||||
"""
|
"""
|
||||||
|
# Alternate design option: do we want to store a Ref instead of just a name? then we can translate/rotate/mirror...
|
||||||
__slots__ = ('name', '_ports')
|
__slots__ = ('name', '_ports')
|
||||||
|
|
||||||
name: str
|
name: str
|
||||||
|
|
@ -48,8 +46,6 @@ class Abstract(PortList):
|
||||||
self.name = name
|
self.name = name
|
||||||
self.ports = copy.deepcopy(ports)
|
self.ports = copy.deepcopy(ports)
|
||||||
|
|
||||||
# TODO do we want to store a Ref instead of just a name? then we can translate/rotate/mirror...
|
|
||||||
|
|
||||||
def __repr__(self) -> str:
|
def __repr__(self) -> str:
|
||||||
s = f'<Abstract {self.name} ['
|
s = f'<Abstract {self.name} ['
|
||||||
for name, port in self.ports.items():
|
for name, port in self.ports.items():
|
||||||
|
|
@ -88,7 +84,7 @@ class Abstract(PortList):
|
||||||
|
|
||||||
def rotate_around(self, pivot: ArrayLike, rotation: float) -> Self:
|
def rotate_around(self, pivot: ArrayLike, rotation: float) -> Self:
|
||||||
"""
|
"""
|
||||||
Rotate the Abstract around the a location.
|
Rotate the Abstract around a pivot point.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
pivot: (x, y) location to rotate around
|
pivot: (x, y) location to rotate around
|
||||||
|
|
@ -132,50 +128,18 @@ class Abstract(PortList):
|
||||||
port.rotate(rotation)
|
port.rotate(rotation)
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def mirror_port_offsets(self, across_axis: int = 0) -> Self:
|
def mirror(self, axis: int = 0) -> Self:
|
||||||
"""
|
"""
|
||||||
Mirror the offsets of all shapes, labels, and refs across an axis
|
Mirror the Abstract across an axis through its origin.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
across_axis: Axis to mirror across
|
axis: Axis to mirror across (0: x-axis, 1: y-axis).
|
||||||
(0: mirror across x axis, 1: mirror across y axis)
|
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
self
|
self
|
||||||
"""
|
"""
|
||||||
for port in self.ports.values():
|
for port in self.ports.values():
|
||||||
port.offset[across_axis - 1] *= -1
|
port.flip_across(axis=axis)
|
||||||
return self
|
|
||||||
|
|
||||||
def mirror_ports(self, across_axis: int = 0) -> Self:
|
|
||||||
"""
|
|
||||||
Mirror each port's rotation across an axis, relative to its
|
|
||||||
offset
|
|
||||||
|
|
||||||
Args:
|
|
||||||
across_axis: Axis to mirror across
|
|
||||||
(0: mirror across x axis, 1: mirror across y axis)
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
self
|
|
||||||
"""
|
|
||||||
for port in self.ports.values():
|
|
||||||
port.mirror(across_axis)
|
|
||||||
return self
|
|
||||||
|
|
||||||
def mirror(self, across_axis: int = 0) -> Self:
|
|
||||||
"""
|
|
||||||
Mirror the Pattern across an axis
|
|
||||||
|
|
||||||
Args:
|
|
||||||
axis: Axis to mirror across
|
|
||||||
(0: mirror across x axis, 1: mirror across y axis)
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
self
|
|
||||||
"""
|
|
||||||
self.mirror_ports(across_axis)
|
|
||||||
self.mirror_port_offsets(across_axis)
|
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def apply_ref_transform(self, ref: Ref) -> Self:
|
def apply_ref_transform(self, ref: Ref) -> Self:
|
||||||
|
|
@ -193,6 +157,8 @@ class Abstract(PortList):
|
||||||
self.mirror()
|
self.mirror()
|
||||||
self.rotate_ports(ref.rotation)
|
self.rotate_ports(ref.rotation)
|
||||||
self.rotate_port_offsets(ref.rotation)
|
self.rotate_port_offsets(ref.rotation)
|
||||||
|
if ref.scale != 1:
|
||||||
|
self.scale_by(ref.scale)
|
||||||
self.translate_ports(ref.offset)
|
self.translate_ports(ref.offset)
|
||||||
return self
|
return self
|
||||||
|
|
||||||
|
|
@ -210,6 +176,8 @@ class Abstract(PortList):
|
||||||
# TODO test undo_ref_transform
|
# TODO test undo_ref_transform
|
||||||
"""
|
"""
|
||||||
self.translate_ports(-ref.offset)
|
self.translate_ports(-ref.offset)
|
||||||
|
if ref.scale != 1:
|
||||||
|
self.scale_by(1 / ref.scale)
|
||||||
self.rotate_port_offsets(-ref.rotation)
|
self.rotate_port_offsets(-ref.rotation)
|
||||||
self.rotate_ports(-ref.rotation)
|
self.rotate_ports(-ref.rotation)
|
||||||
if ref.mirrored:
|
if ref.mirrored:
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,90 @@
|
||||||
from .builder import Builder as Builder
|
"""
|
||||||
from .pather import Pather as Pather
|
Builder helpers for port-based assembly and primitive-offer routing.
|
||||||
from .renderpather import RenderPather as RenderPather
|
|
||||||
|
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 (
|
||||||
|
Pather as Pather,
|
||||||
|
PortPather as PortPather,
|
||||||
|
RouteCompletionCallback as RouteCompletionCallback,
|
||||||
|
)
|
||||||
|
from .error import (
|
||||||
|
ToolContractError as ToolContractError,
|
||||||
|
RouteError as RouteError,
|
||||||
|
RouteFailureDetails as RouteFailureDetails,
|
||||||
|
RouteOperation as RouteOperation,
|
||||||
|
RouteFailurePolicy as RouteFailurePolicy,
|
||||||
|
MinimumStatus as MinimumStatus,
|
||||||
|
)
|
||||||
from .utils import ell as ell
|
from .utils import ell as ell
|
||||||
|
from .tool_testing import (
|
||||||
|
ToolContractCase as ToolContractCase,
|
||||||
|
validate_tool_contract as validate_tool_contract,
|
||||||
|
)
|
||||||
from .tools import (
|
from .tools import (
|
||||||
Tool as Tool,
|
Tool as Tool,
|
||||||
RenderStep as RenderStep,
|
AutoTool as AutoTool,
|
||||||
BasicTool as BasicTool,
|
|
||||||
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,
|
||||||
|
)
|
||||||
|
|
|
||||||
48
masque/builder/_tolerances.py
Normal file
48
masque/builder/_tolerances.py
Normal file
|
|
@ -0,0 +1,48 @@
|
||||||
|
"""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,443 +0,0 @@
|
||||||
"""
|
|
||||||
Simplified Pattern assembly (`Builder`)
|
|
||||||
"""
|
|
||||||
from typing import Self
|
|
||||||
from collections.abc import Iterable, Sequence, Mapping
|
|
||||||
import copy
|
|
||||||
import logging
|
|
||||||
from functools import wraps
|
|
||||||
|
|
||||||
from numpy.typing import ArrayLike
|
|
||||||
|
|
||||||
from ..pattern import Pattern
|
|
||||||
from ..library import ILibrary, TreeView
|
|
||||||
from ..error import BuildError
|
|
||||||
from ..ports import PortList, Port
|
|
||||||
from ..abstract import Abstract
|
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class Builder(PortList):
|
|
||||||
"""
|
|
||||||
A `Builder` is a helper object used for snapping together multiple
|
|
||||||
lower-level patterns at their `Port`s.
|
|
||||||
|
|
||||||
The `Builder` mostly just holds context, in the form of a `Library`,
|
|
||||||
in addition to its underlying pattern. This simplifies some calls
|
|
||||||
to `plug` and `place`, by making the library implicit.
|
|
||||||
|
|
||||||
`Builder` can also be `set_dead()`, at which point further calls to `plug()`
|
|
||||||
and `place()` are ignored (intended for debugging).
|
|
||||||
|
|
||||||
|
|
||||||
Examples: Creating a Builder
|
|
||||||
===========================
|
|
||||||
- `Builder(library, ports={'A': port_a, 'C': port_c}, name='mypat')` makes
|
|
||||||
an empty pattern, adds the given ports, and places it into `library`
|
|
||||||
under the name `'mypat'`.
|
|
||||||
|
|
||||||
- `Builder(library)` makes an empty pattern with no ports. The pattern
|
|
||||||
is not added into `library` and must later be added with e.g.
|
|
||||||
`library['mypat'] = builder.pattern`
|
|
||||||
|
|
||||||
- `Builder(library, pattern=pattern, name='mypat')` uses an existing
|
|
||||||
pattern (including its ports) and sets `library['mypat'] = pattern`.
|
|
||||||
|
|
||||||
- `Builder.interface(other_pat, port_map=['A', 'B'], library=library)`
|
|
||||||
makes a new (empty) pattern, copies over ports 'A' and 'B' from
|
|
||||||
`other_pat`, and creates additional ports 'in_A' and 'in_B' facing
|
|
||||||
in the opposite directions. This can be used to build a device which
|
|
||||||
can plug into `other_pat` (using the 'in_*' ports) but which does not
|
|
||||||
itself include `other_pat` as a subcomponent.
|
|
||||||
|
|
||||||
- `Builder.interface(other_builder, ...)` does the same thing as
|
|
||||||
`Builder.interface(other_builder.pattern, ...)` but also uses
|
|
||||||
`other_builder.library` as its library by default.
|
|
||||||
|
|
||||||
|
|
||||||
Examples: Adding to a pattern
|
|
||||||
=============================
|
|
||||||
- `my_device.plug(subdevice, {'A': 'C', 'B': 'B'}, map_out={'D': 'myport'})`
|
|
||||||
instantiates `subdevice` into `my_device`, plugging ports 'A' and 'B'
|
|
||||||
of `my_device` into ports 'C' and 'B' of `subdevice`. The connected ports
|
|
||||||
are removed and any unconnected ports from `subdevice` are added to
|
|
||||||
`my_device`. Port 'D' of `subdevice` (unconnected) is renamed to 'myport'.
|
|
||||||
|
|
||||||
- `my_device.plug(wire, {'myport': 'A'})` places port 'A' of `wire` at 'myport'
|
|
||||||
of `my_device`. If `wire` has only two ports (e.g. 'A' and 'B'), no `map_out`,
|
|
||||||
argument is provided, and the `inherit_name` argument is not explicitly
|
|
||||||
set to `False`, the unconnected port of `wire` is automatically renamed to
|
|
||||||
'myport'. This allows easy extension of existing ports without changing
|
|
||||||
their names or having to provide `map_out` each time `plug` is called.
|
|
||||||
|
|
||||||
- `my_device.place(pad, offset=(10, 10), rotation=pi / 2, port_map={'A': 'gnd'})`
|
|
||||||
instantiates `pad` at the specified (x, y) offset and with the specified
|
|
||||||
rotation, adding its ports to those of `my_device`. Port 'A' of `pad` is
|
|
||||||
renamed to 'gnd' so that further routing can use this signal or net name
|
|
||||||
rather than the port name on the original `pad` device.
|
|
||||||
"""
|
|
||||||
__slots__ = ('pattern', 'library', '_dead')
|
|
||||||
|
|
||||||
pattern: Pattern
|
|
||||||
""" Layout of this device """
|
|
||||||
|
|
||||||
library: ILibrary
|
|
||||||
"""
|
|
||||||
Library from which patterns should be referenced
|
|
||||||
"""
|
|
||||||
|
|
||||||
_dead: bool
|
|
||||||
""" If True, plug()/place() are skipped (for debugging)"""
|
|
||||||
|
|
||||||
@property
|
|
||||||
def ports(self) -> dict[str, Port]:
|
|
||||||
return self.pattern.ports
|
|
||||||
|
|
||||||
@ports.setter
|
|
||||||
def ports(self, value: dict[str, Port]) -> None:
|
|
||||||
self.pattern.ports = value
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
library: ILibrary,
|
|
||||||
*,
|
|
||||||
pattern: Pattern | None = None,
|
|
||||||
ports: str | Mapping[str, Port] | None = None,
|
|
||||||
name: str | None = None,
|
|
||||||
) -> None:
|
|
||||||
"""
|
|
||||||
Args:
|
|
||||||
library: The library from which referenced patterns will be taken
|
|
||||||
pattern: The pattern which will be modified by subsequent operations.
|
|
||||||
If `None` (default), a new pattern is created.
|
|
||||||
ports: Allows specifying the initial set of ports, if `pattern` does
|
|
||||||
not already have any ports (or is not provided). May be a string,
|
|
||||||
in which case it is interpreted as a name in `library`.
|
|
||||||
Default `None` (no ports).
|
|
||||||
name: If specified, `library[name]` is set to `self.pattern`.
|
|
||||||
"""
|
|
||||||
self._dead = False
|
|
||||||
self.library = library
|
|
||||||
if pattern is not None:
|
|
||||||
self.pattern = pattern
|
|
||||||
else:
|
|
||||||
self.pattern = Pattern()
|
|
||||||
|
|
||||||
if ports is not None:
|
|
||||||
if self.pattern.ports:
|
|
||||||
raise BuildError('Ports supplied for pattern with pre-existing ports!')
|
|
||||||
if isinstance(ports, str):
|
|
||||||
ports = library.abstract(ports).ports
|
|
||||||
|
|
||||||
self.pattern.ports.update(copy.deepcopy(dict(ports)))
|
|
||||||
|
|
||||||
if name is not None:
|
|
||||||
library[name] = self.pattern
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def interface(
|
|
||||||
cls: type['Builder'],
|
|
||||||
source: PortList | Mapping[str, Port] | str,
|
|
||||||
*,
|
|
||||||
library: ILibrary | None = None,
|
|
||||||
in_prefix: str = 'in_',
|
|
||||||
out_prefix: str = '',
|
|
||||||
port_map: dict[str, str] | Sequence[str] | None = None,
|
|
||||||
name: str | None = None,
|
|
||||||
) -> 'Builder':
|
|
||||||
"""
|
|
||||||
Wrapper for `Pattern.interface()`, which returns a Builder instead.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
source: A collection of ports (e.g. Pattern, Builder, or dict)
|
|
||||||
from which to create the interface. May be a pattern name if
|
|
||||||
`library` is provided.
|
|
||||||
library: Library from which existing patterns should be referenced,
|
|
||||||
and to which the new one should be added (if named). If not provided,
|
|
||||||
`source.library` must exist and will be used.
|
|
||||||
in_prefix: Prepended to port names for newly-created ports with
|
|
||||||
reversed directions compared to the current device.
|
|
||||||
out_prefix: Prepended to port names for ports which are directly
|
|
||||||
copied from the current device.
|
|
||||||
port_map: Specification for ports to copy into the new device:
|
|
||||||
- If `None`, all ports are copied.
|
|
||||||
- If a sequence, only the listed ports are copied
|
|
||||||
- If a mapping, the listed ports (keys) are copied and
|
|
||||||
renamed (to the values).
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
The new builder, with an empty pattern and 2x as many ports as
|
|
||||||
listed in port_map.
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
`PortError` if `port_map` contains port names not present in the
|
|
||||||
current device.
|
|
||||||
`PortError` if applying the prefixes results in duplicate port
|
|
||||||
names.
|
|
||||||
"""
|
|
||||||
if library is None:
|
|
||||||
if hasattr(source, 'library') and isinstance(source.library, ILibrary):
|
|
||||||
library = source.library
|
|
||||||
else:
|
|
||||||
raise BuildError('No library was given, and `source.library` does not have one either.')
|
|
||||||
|
|
||||||
if isinstance(source, str):
|
|
||||||
source = library.abstract(source).ports
|
|
||||||
|
|
||||||
pat = Pattern.interface(source, in_prefix=in_prefix, out_prefix=out_prefix, port_map=port_map)
|
|
||||||
new = Builder(library=library, pattern=pat, name=name)
|
|
||||||
return new
|
|
||||||
|
|
||||||
@wraps(Pattern.label)
|
|
||||||
def label(self, *args, **kwargs) -> Self:
|
|
||||||
self.pattern.label(*args, **kwargs)
|
|
||||||
return self
|
|
||||||
|
|
||||||
@wraps(Pattern.ref)
|
|
||||||
def ref(self, *args, **kwargs) -> Self:
|
|
||||||
self.pattern.ref(*args, **kwargs)
|
|
||||||
return self
|
|
||||||
|
|
||||||
@wraps(Pattern.polygon)
|
|
||||||
def polygon(self, *args, **kwargs) -> Self:
|
|
||||||
self.pattern.polygon(*args, **kwargs)
|
|
||||||
return self
|
|
||||||
|
|
||||||
@wraps(Pattern.rect)
|
|
||||||
def rect(self, *args, **kwargs) -> Self:
|
|
||||||
self.pattern.rect(*args, **kwargs)
|
|
||||||
return self
|
|
||||||
|
|
||||||
# Note: We're a superclass of `Pather`, where path() means something different...
|
|
||||||
#@wraps(Pattern.path)
|
|
||||||
#def path(self, *args, **kwargs) -> Self:
|
|
||||||
# self.pattern.path(*args, **kwargs)
|
|
||||||
# return self
|
|
||||||
|
|
||||||
def plug(
|
|
||||||
self,
|
|
||||||
other: Abstract | str | Pattern | TreeView,
|
|
||||||
map_in: dict[str, str],
|
|
||||||
map_out: dict[str, str | None] | None = None,
|
|
||||||
*,
|
|
||||||
mirrored: bool = False,
|
|
||||||
inherit_name: bool = True,
|
|
||||||
set_rotation: bool | None = None,
|
|
||||||
append: bool = False,
|
|
||||||
ok_connections: Iterable[tuple[str, str]] = (),
|
|
||||||
) -> Self:
|
|
||||||
"""
|
|
||||||
Wrapper around `Pattern.plug` which allows a string for `other`.
|
|
||||||
|
|
||||||
The `Builder`'s library is used to dereference the string (or `Abstract`, if
|
|
||||||
one is passed with `append=True`). If a `TreeView` is passed, it is first
|
|
||||||
added into `self.library`.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
other: An `Abstract`, string, `Pattern`, or `TreeView` describing the
|
|
||||||
device to be instatiated. If it is a `TreeView`, it is first
|
|
||||||
added into `self.library`, after which the topcell is plugged;
|
|
||||||
an equivalent statement is `self.plug(self.library << other, ...)`.
|
|
||||||
map_in: dict of `{'self_port': 'other_port'}` mappings, specifying
|
|
||||||
port connections between the two devices.
|
|
||||||
map_out: dict of `{'old_name': 'new_name'}` mappings, specifying
|
|
||||||
new names for ports in `other`.
|
|
||||||
mirrored: Enables mirroring `other` across the x axis prior to
|
|
||||||
connecting any ports.
|
|
||||||
inherit_name: If `True`, and `map_in` specifies only a single port,
|
|
||||||
and `map_out` is `None`, and `other` has only two ports total,
|
|
||||||
then automatically renames the output port of `other` to the
|
|
||||||
name of the port from `self` that appears in `map_in`. This
|
|
||||||
makes it easy to extend a device with simple 2-port devices
|
|
||||||
(e.g. wires) without providing `map_out` each time `plug` is
|
|
||||||
called. See "Examples" above for more info. Default `True`.
|
|
||||||
set_rotation: If the necessary rotation cannot be determined from
|
|
||||||
the ports being connected (i.e. all pairs have at least one
|
|
||||||
port with `rotation=None`), `set_rotation` must be provided
|
|
||||||
to indicate how much `other` should be rotated. Otherwise,
|
|
||||||
`set_rotation` must remain `None`.
|
|
||||||
append: If `True`, `other` is appended instead of being referenced.
|
|
||||||
Note that this does not flatten `other`, so its refs will still
|
|
||||||
be refs (now inside `self`).
|
|
||||||
ok_connections: Set of "allowed" ptype combinations. Identical
|
|
||||||
ptypes are always allowed to connect, as is `'unk'` with
|
|
||||||
any other ptypte. Non-allowed ptype connections will emit a
|
|
||||||
warning. Order is ignored, i.e. `(a, b)` is equivalent to
|
|
||||||
`(b, a)`.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
self
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
`PortError` if any ports specified in `map_in` or `map_out` do not
|
|
||||||
exist in `self.ports` or `other_names`.
|
|
||||||
`PortError` if there are any duplicate names after `map_in` and `map_out`
|
|
||||||
are applied.
|
|
||||||
`PortError` if the specified port mapping is not achieveable (the ports
|
|
||||||
do not line up)
|
|
||||||
"""
|
|
||||||
if self._dead:
|
|
||||||
logger.error('Skipping plug() since device is dead')
|
|
||||||
return self
|
|
||||||
|
|
||||||
if not isinstance(other, str | Abstract | Pattern):
|
|
||||||
# We got a Tree; add it into self.library and grab an Abstract for it
|
|
||||||
other = self.library << other
|
|
||||||
|
|
||||||
if isinstance(other, str):
|
|
||||||
other = self.library.abstract(other)
|
|
||||||
if append and isinstance(other, Abstract):
|
|
||||||
other = self.library[other.name]
|
|
||||||
|
|
||||||
self.pattern.plug(
|
|
||||||
other=other,
|
|
||||||
map_in=map_in,
|
|
||||||
map_out=map_out,
|
|
||||||
mirrored=mirrored,
|
|
||||||
inherit_name=inherit_name,
|
|
||||||
set_rotation=set_rotation,
|
|
||||||
append=append,
|
|
||||||
ok_connections=ok_connections,
|
|
||||||
)
|
|
||||||
return self
|
|
||||||
|
|
||||||
def place(
|
|
||||||
self,
|
|
||||||
other: Abstract | str | Pattern | TreeView,
|
|
||||||
*,
|
|
||||||
offset: ArrayLike = (0, 0),
|
|
||||||
rotation: float = 0,
|
|
||||||
pivot: ArrayLike = (0, 0),
|
|
||||||
mirrored: bool = False,
|
|
||||||
port_map: dict[str, str | None] | None = None,
|
|
||||||
skip_port_check: bool = False,
|
|
||||||
append: bool = False,
|
|
||||||
) -> Self:
|
|
||||||
"""
|
|
||||||
Wrapper around `Pattern.place` which allows a string or `TreeView` for `other`.
|
|
||||||
|
|
||||||
The `Builder`'s library is used to dereference the string (or `Abstract`, if
|
|
||||||
one is passed with `append=True`). If a `TreeView` is passed, it is first
|
|
||||||
added into `self.library`.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
other: An `Abstract`, string, `Pattern`, or `TreeView` describing the
|
|
||||||
device to be instatiated. If it is a `TreeView`, it is first
|
|
||||||
added into `self.library`, after which the topcell is plugged;
|
|
||||||
an equivalent statement is `self.plug(self.library << other, ...)`.
|
|
||||||
offset: Offset at which to place the instance. Default (0, 0).
|
|
||||||
rotation: Rotation applied to the instance before placement. Default 0.
|
|
||||||
pivot: Rotation is applied around this pivot point (default (0, 0)).
|
|
||||||
Rotation is applied prior to translation (`offset`).
|
|
||||||
mirrored: Whether theinstance should be mirrored across the x axis.
|
|
||||||
Mirroring is applied before translation and rotation.
|
|
||||||
port_map: dict of `{'old_name': 'new_name'}` mappings, specifying
|
|
||||||
new names for ports in the instantiated device. New names can be
|
|
||||||
`None`, which will delete those ports.
|
|
||||||
skip_port_check: Can be used to skip the internal call to `check_ports`,
|
|
||||||
in case it has already been performed elsewhere.
|
|
||||||
append: If `True`, `other` is appended instead of being referenced.
|
|
||||||
Note that this does not flatten `other`, so its refs will still
|
|
||||||
be refs (now inside `self`).
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
self
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
`PortError` if any ports specified in `map_in` or `map_out` do not
|
|
||||||
exist in `self.ports` or `other.ports`.
|
|
||||||
`PortError` if there are any duplicate names after `map_in` and `map_out`
|
|
||||||
are applied.
|
|
||||||
"""
|
|
||||||
if self._dead:
|
|
||||||
logger.error('Skipping place() since device is dead')
|
|
||||||
return self
|
|
||||||
|
|
||||||
if not isinstance(other, str | Abstract | Pattern):
|
|
||||||
# We got a Tree; add it into self.library and grab an Abstract for it
|
|
||||||
other = self.library << other
|
|
||||||
|
|
||||||
if isinstance(other, str):
|
|
||||||
other = self.library.abstract(other)
|
|
||||||
if append and isinstance(other, Abstract):
|
|
||||||
other = self.library[other.name]
|
|
||||||
|
|
||||||
self.pattern.place(
|
|
||||||
other=other,
|
|
||||||
offset=offset,
|
|
||||||
rotation=rotation,
|
|
||||||
pivot=pivot,
|
|
||||||
mirrored=mirrored,
|
|
||||||
port_map=port_map,
|
|
||||||
skip_port_check=skip_port_check,
|
|
||||||
append=append,
|
|
||||||
)
|
|
||||||
return self
|
|
||||||
|
|
||||||
def translate(self, offset: ArrayLike) -> Self:
|
|
||||||
"""
|
|
||||||
Translate the pattern and all ports.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
offset: (x, y) distance to translate by
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
self
|
|
||||||
"""
|
|
||||||
self.pattern.translate_elements(offset)
|
|
||||||
return self
|
|
||||||
|
|
||||||
def rotate_around(self, pivot: ArrayLike, angle: float) -> Self:
|
|
||||||
"""
|
|
||||||
Rotate the pattern and all ports.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
angle: angle (radians, counterclockwise) to rotate by
|
|
||||||
pivot: location to rotate around
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
self
|
|
||||||
"""
|
|
||||||
self.pattern.rotate_around(pivot, angle)
|
|
||||||
for port in self.ports.values():
|
|
||||||
port.rotate_around(pivot, angle)
|
|
||||||
return self
|
|
||||||
|
|
||||||
def mirror(self, axis: int = 0) -> Self:
|
|
||||||
"""
|
|
||||||
Mirror the pattern and all ports across the specified axis.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
axis: Axis to mirror across (x=0, y=1)
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
self
|
|
||||||
"""
|
|
||||||
self.pattern.mirror(axis)
|
|
||||||
return self
|
|
||||||
|
|
||||||
def set_dead(self) -> Self:
|
|
||||||
"""
|
|
||||||
Disallows further changes through `plug()` or `place()`.
|
|
||||||
This is meant for debugging:
|
|
||||||
```
|
|
||||||
dev.plug(a, ...)
|
|
||||||
dev.set_dead() # added for debug purposes
|
|
||||||
dev.plug(b, ...) # usually raises an error, but now skipped
|
|
||||||
dev.plug(c, ...) # also skipped
|
|
||||||
dev.pattern.visualize() # shows the device as of the set_dead() call
|
|
||||||
```
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
self
|
|
||||||
"""
|
|
||||||
self._dead = True
|
|
||||||
return self
|
|
||||||
|
|
||||||
def __repr__(self) -> str:
|
|
||||||
s = f'<Builder {self.pattern} L({len(self.library)})>'
|
|
||||||
return s
|
|
||||||
|
|
||||||
|
|
||||||
109
masque/builder/error.py
Normal file
109
masque/builder/error.py
Normal file
|
|
@ -0,0 +1,109 @@
|
||||||
|
"""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))
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue