-
Notifications
You must be signed in to change notification settings - Fork 186
/
typings.py
380 lines (296 loc) · 8.41 KB
/
typings.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
"""In programming, a factory is a function that returns an object.
Functions are easy to understand because they have clear inputs and outputs.
Most gdsfactory functions take some inputs and return a Component object.
Some of these inputs parameters are also functions.
- Component: Object with.
- name.
- references: to other components (x, y, rotation).
- polygons in different layers.
- ports dict.
Specs:
- ComponentSpec: Component, function, string or dict
(component=mzi, settings=dict(delta_length=20)).
- LayerSpec: (3, 0), 3 (assumes 0 as datatype) or string.
"""
from __future__ import annotations
import dataclasses
import json
import pathlib
from collections.abc import Callable
from typing import Any, Dict, List, Literal, Optional, Tuple, Union
import numpy as np
from kfactory.kcell import LayerEnum
from omegaconf import OmegaConf
from pydantic import BaseModel
from gdsfactory.component import Component, ComponentReference
from gdsfactory.cross_section import CrossSection, Section, Transition, WidthTypes
from gdsfactory.port import Port
from gdsfactory.technology import LayerLevel, LayerMap, LayerStack
STEP_DIRECTIVES = {
"x",
"y",
"dx",
"dy",
}
STEP_DIRECTIVES_ALL_ANGLE = {
"x",
"y",
"dx",
"dy",
"ds",
"exit_angle",
"cross_section",
"connector",
"separation",
}
@dataclasses.dataclass
class Step:
"""Manhattan Step.
Parameters:
x: absolute.
y: absolute.
dx: x-displacement.
dy: y-displacement.
"""
x: float | None = None
y: float | None = None
dx: float | None = None
dy: float | None = None
@dataclasses.dataclass
class StepAllAngle:
x: float | None = None
y: float | None = None
dx: float | None = None
dy: float | None = None
ds: float | None = None
exit_angle: float | None = None
cross_section: CrossSectionSpec | None = None
connector: ComponentSpec | None = None
separation: float | None = None
"""All angle Ste.
Parameters:
x: absolute.
y: absolute.
dx: x-displacement.
dy: y-displacement.
exit_angle: in degrees.
cross_section: spec.
connector: define transition.
separation: in um.
"""
model_config = {"extra": "forbid", "frozen": True}
Anchor = Literal[
"ce",
"cw",
"nc",
"ne",
"nw",
"sc",
"se",
"sw",
"center",
"cc",
]
Axis = Literal["x", "y"]
NSEW = Literal["N", "S", "E", "W"]
Float2 = tuple[float, float]
Float3 = tuple[float, float, float]
Floats = tuple[float, ...]
Strs = tuple[str, ...]
Int2 = tuple[int, int]
Int3 = tuple[int, int, int]
Ints = tuple[int, ...]
Layer = LayerEnum
Layers = tuple[Layer, ...]
LayerSpec = LayerEnum | str
LayerSpecs = list[LayerSpec] | tuple[LayerSpec, ...] | None
ComponentFactory = Callable[..., Component]
ComponentFactoryDict = dict[str, ComponentFactory]
PathType = str | pathlib.Path
PathTypes = tuple[PathType, ...]
MaterialSpec = str | float | tuple[float, float] | Callable
ComponentOrPath = PathType | Component
ComponentOrReference = Component | ComponentReference
NameToFunctionDict = dict[str, ComponentFactory]
Number = float | int
Coordinate = tuple[float, float]
Coordinates = tuple[Coordinate, ...] | list[Coordinate]
ComponentOrPath = Component | PathType
CrossSectionFactory = Callable[..., CrossSection]
TransitionFactory = Callable[..., Transition]
CrossSectionOrFactory = CrossSection | Callable[..., CrossSection]
PortSymmetries = dict[str, list[str]]
PortsDict = dict[str, Port]
PortsList = dict[str, Port]
Sparameters = dict[str, np.ndarray]
ComponentSpec = (
str | ComponentFactory | dict[str, Any]
) # PCell function, function name, dict or Component
ComponentSpecs = tuple[ComponentSpec, ...]
ComponentFactories = tuple[ComponentFactory, ...]
ComponentSpecOrList = ComponentSpec | list[ComponentSpec]
CellSpec = (
str | ComponentFactory | dict[str, Any]
) # PCell function, function name or dict
ComponentSpecDict = dict[str, ComponentSpec]
CrossSectionSpec = (
CrossSectionFactory | CrossSection | dict[str, Any] | str | Transition
)
CrossSectionSpecs = tuple[CrossSectionSpec, ...]
MultiCrossSectionAngleSpec = list[tuple[CrossSectionSpec, tuple[int, ...]]]
class ComponentModel(BaseModel):
component: str | dict[str, Any]
settings: dict[str, Any] | None
model_config = {"extra": "forbid"}
class PlacementModel(BaseModel):
x: str | float = 0
y: str | float = 0
xmin: str | float | None = None
ymin: str | float | None = None
xmax: str | float | None = None
ymax: str | float | None = None
dx: float = 0
dy: float = 0
port: str | Anchor | None = None
rotation: int = 0
mirror: bool = False
model_config = {"extra": "forbid"}
class RouteModel(BaseModel):
links: dict[str, str]
settings: dict[str, Any] | None = None
routing_strategy: str | None = None
model_config = {"extra": "forbid"}
class NetlistModel(BaseModel):
"""Netlist defined component.
Parameters:
instances: dict of instances (name, settings, component).
placements: dict of placements.
connections: dict of connections.
routes: dict of routes.
name: component name.
info: information (polarization, wavelength ...).
settings: input variables.
ports: exposed component ports.
"""
instances: dict[str, ComponentModel] | None = None
placements: dict[str, PlacementModel] | None = None
connections: dict[str, str] | None = None
routes: dict[str, RouteModel] | None = None
name: str | None = None
info: dict[str, Any] | None = None
settings: dict[str, Any] | None = None
ports: dict[str, str] | None = None
model_config = {"extra": "forbid"}
class TypedArray(np.ndarray):
"""based on https://github.com/samuelcolvin/pydantic/issues/380."""
@classmethod
def __get_validators__(cls):
yield cls.validate_type
@classmethod
def validate_type(cls, val, _info):
return np.array(val, dtype=cls.inner_type)
class ArrayMeta(type):
def __getitem__(self, t):
return type("Array", (TypedArray,), {"inner_type": t})
class Array(np.ndarray, metaclass=ArrayMeta):
pass
__all__ = (
"Any",
"Callable",
"Component",
"ComponentFactory",
"ComponentFactoryDict",
"ComponentOrPath",
"ComponentOrReference",
"ComponentSpec",
"Coordinate",
"Coordinates",
"CrossSection",
"CrossSectionFactory",
"CrossSectionOrFactory",
"CrossSectionSpec",
"Float2",
"Float3",
"Floats",
"Int2",
"Int3",
"Ints",
"Layer",
"LayerMap",
"LayerLevel",
"LayerSpec",
"LayerSpecs",
"LayerStack",
"Layers",
"MultiCrossSectionAngleSpec",
"NameToFunctionDict",
"Number",
"Optional",
"PathType",
"PathTypes",
"Section",
"Strs",
"WidthTypes",
"Union",
"List",
"Tuple",
"Dict",
)
def write_schema(model: BaseModel = NetlistModel) -> None:
from gdsfactory.config import PATH
s = model.schema_json()
d = OmegaConf.create(s)
schema_path_json = PATH.schema_netlist
schema_path_yaml = schema_path_json.with_suffix(".yaml")
schema_path_yaml.write_text(OmegaConf.to_yaml(d))
schema_path_json.write_text(json.dumps(OmegaConf.to_container(d)))
def _demo() -> None:
write_schema()
import jsonschema
import yaml
from gdsfactory.config import PATH
schema_path_json = PATH.schema_netlist
schema_dict = json.loads(schema_path_json.read_text())
yaml_text = """
name: mzi
pdk: ubcpdk
settings:
dy: -90
info:
polarization: te
wavelength: 1.55
description: mzi for ubcpdk
instances:
yr:
component: y_splitter
yl:
component: y_splitter
placements:
yr:
rotation: 180
x: 100
y: 0
routes:
route_top:
links:
yl,opt2: yr,opt3
settings:
cross_section: strip
route_bot:
links:
yl,opt3: yr,opt2
routing_strategy: route_bundle_from_steps
settings:
steps: [dx: 30, dy: '${settings.dy}', dx: 20]
cross_section: strip
ports:
o1: yl,opt1
o2: yr,opt1
"""
yaml_dict = yaml.safe_load(yaml_text)
jsonschema.validate(yaml_dict, schema_dict)
# from gdsfactory.components import factory
# c = NetlistModel(factory=factory)
# c.add_instance("mmi1", "mmi1x2", length=13.3)
if __name__ == "__main__":
s = Step()