maskyard 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. maskyard/__init__.py +42 -0
  2. maskyard/config.py +154 -0
  3. maskyard/engine.py +232 -0
  4. maskyard/models/__init__.py +27 -0
  5. maskyard/models/box.py +29 -0
  6. maskyard/models/cell.py +790 -0
  7. maskyard/models/config.py +12 -0
  8. maskyard/models/cross_section.py +25 -0
  9. maskyard/models/dependency.py +23 -0
  10. maskyard/models/enclosure.py +247 -0
  11. maskyard/models/factory.py +38 -0
  12. maskyard/models/geometry.py +87 -0
  13. maskyard/models/info.py +8 -0
  14. maskyard/models/instance.py +245 -0
  15. maskyard/models/layer.py +13 -0
  16. maskyard/models/path.py +15 -0
  17. maskyard/models/pdk.py +445 -0
  18. maskyard/models/port.py +401 -0
  19. maskyard/models/trans.py +62 -0
  20. maskyard/models/vector.py +23 -0
  21. maskyard/pcell_cache.py +48 -0
  22. maskyard/serialization.py +424 -0
  23. maskyard/typing.py +85 -0
  24. maskyard/web/__init__.py +5 -0
  25. maskyard/web/app.py +262 -0
  26. maskyard/web/layer_styles.py +123 -0
  27. maskyard/web/layout.py +162 -0
  28. maskyard/web/render_cache.py +334 -0
  29. maskyard/web/static/BOOTSTRAP_LICENSE.txt +21 -0
  30. maskyard/web/static/CYTOSCAPE_LICENSE.txt +19 -0
  31. maskyard/web/static/PIXI_LICENSE.txt +21 -0
  32. maskyard/web/static/POPPER_LICENSE.txt +20 -0
  33. maskyard/web/static/bootstrap.bundle.min.js +7 -0
  34. maskyard/web/static/bootstrap.min.css +6 -0
  35. maskyard/web/static/cell_graph.js +169 -0
  36. maskyard/web/static/cell_layout.js +838 -0
  37. maskyard/web/static/cytoscape.min.js +31 -0
  38. maskyard/web/static/pixi.min.js +3256 -0
  39. maskyard/web/templates/cell.html +136 -0
  40. maskyard/web/templates/cell_layout.html +26 -0
  41. maskyard/web/templates/index.html +66 -0
  42. maskyard/writer.py +338 -0
  43. maskyard-0.0.1.dist-info/METADATA +84 -0
  44. maskyard-0.0.1.dist-info/RECORD +47 -0
  45. maskyard-0.0.1.dist-info/WHEEL +4 -0
  46. maskyard-0.0.1.dist-info/entry_points.txt +3 -0
  47. maskyard-0.0.1.dist-info/licenses/LICENSE +661 -0
maskyard/__init__.py ADDED
@@ -0,0 +1,42 @@
1
+ import klayout.db as kdb
2
+ from klayout import lay
3
+
4
+ from . import models
5
+ from .config import settings
6
+ from .models.cell import Cell
7
+ from .models.cross_section import SymmetricCrossSection
8
+ from .models.enclosure import Enclosure
9
+ from .models.instance import Instance
10
+ from .models.layer import Layer
11
+ from .models.pdk import Pdk, get_or_create_pdk
12
+ from .models.port import CellPort, InstancePort
13
+ from .writer import (
14
+ CellWrite,
15
+ CellWriter,
16
+ InstanceWrite,
17
+ PortWrite,
18
+ shutdown_writer,
19
+ submit_cell,
20
+ )
21
+
22
+ __all__ = [
23
+ "Cell",
24
+ "CellPort",
25
+ "CellWrite",
26
+ "CellWriter",
27
+ "Enclosure",
28
+ "Instance",
29
+ "InstancePort",
30
+ "InstanceWrite",
31
+ "Layer",
32
+ "Pdk",
33
+ "PortWrite",
34
+ "SymmetricCrossSection",
35
+ "get_or_create_pdk",
36
+ "kdb",
37
+ "lay",
38
+ "models",
39
+ "settings",
40
+ "shutdown_writer",
41
+ "submit_cell",
42
+ ]
maskyard/config.py ADDED
@@ -0,0 +1,154 @@
1
+ from functools import cached_property
2
+ from pathlib import Path
3
+ from typing import overload
4
+
5
+ from pydantic_settings import BaseSettings, SettingsConfigDict
6
+ from sqlalchemy import select
7
+
8
+ from . import kdb
9
+
10
+
11
+ class Settings(BaseSettings):
12
+ model_config = SettingsConfigDict(
13
+ env_prefix="MASKYARD_",
14
+ env_file=".env",
15
+ env_file_encoding="utf-8",
16
+ env_file_depth=3,
17
+ extra="ignore",
18
+ frozen=True,
19
+ )
20
+
21
+ database_url: str = "sqlite:///maskyard.db"
22
+ layout_cache_dir: Path | None = None
23
+ layout_layer_properties: Path | None = None
24
+ log_level: str = "INFO"
25
+
26
+ allow_width_mismatch: bool = False
27
+ allow_layer_mismatch: bool = False
28
+ allow_type_mismatch: bool = False
29
+ allow_cross_section_mismatch: bool = True
30
+ connect_use_mirror: bool = False
31
+ connect_use_angle: bool = True
32
+ max_cellname_length: int = 99
33
+
34
+ @cached_property
35
+ def dbu(self) -> float:
36
+ from .engine import _config_table, engine
37
+
38
+ with engine.connect() as connection:
39
+ value = connection.scalar(
40
+ select(_config_table.c.dbu).where(_config_table.c.id == 1)
41
+ )
42
+ if value is None:
43
+ raise RuntimeError("Database configuration is missing")
44
+ return value
45
+
46
+
47
+ def get_settings() -> Settings:
48
+ return Settings.settings_cached()
49
+
50
+
51
+ settings = get_settings()
52
+
53
+
54
+ @overload
55
+ def to_um(other: None) -> None: ...
56
+
57
+
58
+ @overload
59
+ def to_um(other: int) -> float: ...
60
+
61
+
62
+ @overload
63
+ def to_um(other: kdb.Point) -> kdb.DPoint: ...
64
+
65
+
66
+ @overload
67
+ def to_um(other: kdb.Vector) -> kdb.DVector: ...
68
+
69
+
70
+ @overload
71
+ def to_um(other: kdb.Box) -> kdb.DBox: ...
72
+
73
+
74
+ @overload
75
+ def to_um(other: kdb.Polygon) -> kdb.DPolygon: ...
76
+
77
+
78
+ @overload
79
+ def to_um(other: kdb.Path) -> kdb.DPath: ...
80
+
81
+
82
+ @overload
83
+ def to_um(other: kdb.Text) -> kdb.DText: ...
84
+
85
+
86
+ def to_um(
87
+ other: int
88
+ | kdb.Point
89
+ | kdb.Vector
90
+ | kdb.Box
91
+ | kdb.Polygon
92
+ | kdb.Path
93
+ | kdb.Text
94
+ | None,
95
+ ) -> (
96
+ float
97
+ | kdb.DPoint
98
+ | kdb.DVector
99
+ | kdb.DBox
100
+ | kdb.DPolygon
101
+ | kdb.DPath
102
+ | kdb.DText
103
+ | None
104
+ ):
105
+ """Convert Shapes or values in dbu to DShapes or floats in um."""
106
+ if other is None:
107
+ return None
108
+ return kdb.CplxTrans(settings.dbu) * other
109
+
110
+
111
+ @overload
112
+ def to_dbu(other: None) -> None: ...
113
+ @overload
114
+ def to_dbu(other: float) -> int: ...
115
+
116
+
117
+ @overload
118
+ def to_dbu(other: kdb.DPoint) -> kdb.Point: ...
119
+
120
+
121
+ @overload
122
+ def to_dbu(other: kdb.DVector) -> kdb.Vector: ...
123
+
124
+
125
+ @overload
126
+ def to_dbu(other: kdb.DBox) -> kdb.Box: ...
127
+
128
+
129
+ @overload
130
+ def to_dbu(other: kdb.DPolygon) -> kdb.Polygon: ...
131
+
132
+
133
+ @overload
134
+ def to_dbu(other: kdb.DPath) -> kdb.Path: ...
135
+
136
+
137
+ @overload
138
+ def to_dbu(other: kdb.DText) -> kdb.Text: ...
139
+
140
+
141
+ def to_dbu(
142
+ other: float
143
+ | kdb.DPoint
144
+ | kdb.DVector
145
+ | kdb.DBox
146
+ | kdb.DPolygon
147
+ | kdb.DPath
148
+ | kdb.DText
149
+ | None,
150
+ ) -> int | kdb.Point | kdb.Vector | kdb.Box | kdb.Polygon | kdb.Path | kdb.Text | None:
151
+ """Convert Shapes or values in dbu to DShapes or floats in um."""
152
+ if other is None:
153
+ return None
154
+ return kdb.CplxTrans(settings.dbu).inverted() * other
maskyard/engine.py ADDED
@@ -0,0 +1,232 @@
1
+ """Database engine and schema setup."""
2
+
3
+ from collections.abc import Generator
4
+ from contextlib import contextmanager, suppress
5
+ from contextvars import ContextVar
6
+ from threading import Event, Lock, get_ident
7
+ from warnings import warn
8
+
9
+ from sqlalchemy import MetaData, event, inspect, select
10
+ from sqlalchemy.engine import Connection, Engine
11
+ from sqlalchemy.orm import Session as SASession
12
+ from sqlalchemy.orm import object_session
13
+ from sqlmodel import Session, SQLModel, create_engine
14
+
15
+ from . import models # noqa: F401
16
+ from .config import settings
17
+ from .models.config import CURRENT_SCHEMA_VERSION
18
+
19
+ engine = create_engine(settings.database_url)
20
+ DEFAULT_DBU = 0.001
21
+ _schema_lock = Lock()
22
+ _registration_lock = Lock()
23
+ _session_lock = Lock()
24
+ _initialized = Event()
25
+ _engine_generation = 0
26
+ _cached_sessions: dict[int, set[Session]] = {}
27
+ _config_table = SQLModel.metadata.tables["databaseconfig"]
28
+ _initial_dbu: ContextVar[float] = ContextVar("initial_dbu", default=DEFAULT_DBU)
29
+
30
+
31
+ def create_db_and_tables(*, dbu: float = DEFAULT_DBU) -> None:
32
+ """Initialize the cache and purge it if its schema version is outdated."""
33
+ if _initialized.is_set() and settings.dbu == dbu:
34
+ return
35
+ with _schema_lock:
36
+ _initialized.clear()
37
+ token = _initial_dbu.set(dbu)
38
+ try:
39
+ with engine.connect():
40
+ pass
41
+ finally:
42
+ _initial_dbu.reset(token)
43
+
44
+
45
+ def _register_engine(cache_engine: Engine) -> None:
46
+ with _registration_lock:
47
+ if not event.contains(cache_engine, "engine_connect", _on_engine_connect):
48
+ event.listen(cache_engine, "engine_connect", _on_engine_connect)
49
+ event.listen(cache_engine, "engine_disposed", _on_engine_disposed)
50
+
51
+
52
+ def _on_engine_connect(connection: Connection) -> None:
53
+ with _schema_lock:
54
+ if _initialized.is_set():
55
+ return
56
+ _initialize_schema(connection, dbu=_initial_dbu.get())
57
+ connection.commit()
58
+ with suppress(AttributeError):
59
+ del settings.dbu
60
+ _initialized.set()
61
+
62
+
63
+ def _on_engine_disposed(_engine: Engine) -> None:
64
+ global _engine_generation # noqa: PLW0603
65
+ with _schema_lock:
66
+ with suppress(AttributeError):
67
+ del settings.dbu
68
+ _initialized.clear()
69
+ _engine_generation += 1
70
+ with _session_lock:
71
+ sessions = [session for group in _cached_sessions.values() for session in group]
72
+ _cached_sessions.clear()
73
+ for session in sessions:
74
+ session.close()
75
+
76
+
77
+ def _stored_schema_version(connection: Connection, tables: set[str]) -> int | None:
78
+ if _config_table.name not in tables:
79
+ return None
80
+ columns = {
81
+ column["name"] for column in inspect(connection).get_columns(_config_table.name)
82
+ }
83
+ if "schema_version" not in columns:
84
+ return None
85
+ return connection.scalar(
86
+ select(_config_table.c.schema_version).where(_config_table.c.id == 1)
87
+ )
88
+
89
+
90
+ def _initialize_schema(connection: Connection, *, dbu: float) -> None:
91
+ if dbu <= 0:
92
+ raise ValueError("DBU must be positive")
93
+ tables = set(inspect(connection).get_table_names())
94
+ expected_tables = set(SQLModel.metadata.tables)
95
+
96
+ if tables:
97
+ stored_version = _stored_schema_version(connection, tables)
98
+ stored_dbu = (
99
+ connection.scalar(
100
+ select(_config_table.c.dbu).where(_config_table.c.id == 1)
101
+ )
102
+ if stored_version in (1, CURRENT_SCHEMA_VERSION)
103
+ else None
104
+ )
105
+ if stored_version == 1 and stored_dbu == dbu and expected_tables <= tables:
106
+ columns = {
107
+ column["name"] for column in inspect(connection).get_columns("cell")
108
+ }
109
+ if "bbox" in columns:
110
+ connection.exec_driver_sql("ALTER TABLE cell DROP COLUMN bbox")
111
+ connection.execute(
112
+ _config_table.update()
113
+ .where(_config_table.c.id == 1)
114
+ .values(schema_version=CURRENT_SCHEMA_VERSION)
115
+ )
116
+ stored_version = CURRENT_SCHEMA_VERSION
117
+ if (
118
+ stored_version != CURRENT_SCHEMA_VERSION
119
+ or stored_dbu != dbu
120
+ or not expected_tables <= tables
121
+ ):
122
+ warn(
123
+ "Incompatible database cache configuration "
124
+ f"(stored schema {stored_version}, DBU {stored_dbu}; "
125
+ f"requested schema {CURRENT_SCHEMA_VERSION}, DBU {dbu}); "
126
+ "purging the cache",
127
+ RuntimeWarning,
128
+ stacklevel=2,
129
+ )
130
+ old_schema = MetaData()
131
+ old_schema.reflect(bind=connection)
132
+ old_schema.drop_all(bind=connection)
133
+ else:
134
+ _protect_dbu(connection)
135
+ return
136
+
137
+ SQLModel.metadata.create_all(connection)
138
+ connection.execute(
139
+ _config_table.insert().values(
140
+ id=1,
141
+ dbu=dbu,
142
+ schema_version=CURRENT_SCHEMA_VERSION,
143
+ )
144
+ )
145
+ _protect_dbu(connection)
146
+
147
+
148
+ def _protect_dbu(connection: Connection) -> None:
149
+ if connection.dialect.name == "sqlite":
150
+ connection.exec_driver_sql(
151
+ "CREATE TRIGGER IF NOT EXISTS databaseconfig_dbu_readonly "
152
+ "BEFORE UPDATE OF dbu ON databaseconfig "
153
+ "BEGIN SELECT RAISE(ABORT, 'database DBU is read-only'); END"
154
+ )
155
+ connection.exec_driver_sql(
156
+ "CREATE TRIGGER IF NOT EXISTS databaseconfig_delete_readonly "
157
+ "BEFORE DELETE ON databaseconfig "
158
+ "BEGIN SELECT RAISE(ABORT, 'database configuration is read-only'); END"
159
+ )
160
+
161
+
162
+ _current_session: ContextVar[tuple[int, Engine, int, Session] | None] = ContextVar(
163
+ "current_session",
164
+ default=None,
165
+ )
166
+
167
+
168
+ def get_session() -> Session:
169
+ current = _current_session.get()
170
+ thread_id = get_ident()
171
+ if current is not None and current[0] == thread_id:
172
+ if current[1] is engine and current[2] == _engine_generation:
173
+ return current[3]
174
+ close_session()
175
+
176
+ if not _initialized.is_set():
177
+ create_db_and_tables()
178
+ session = Session(engine, expire_on_commit=False)
179
+ _current_session.set((thread_id, engine, _engine_generation, session))
180
+ with _session_lock:
181
+ _cached_sessions.setdefault(thread_id, set()).add(session)
182
+ return session
183
+
184
+
185
+ def close_session() -> None:
186
+ """Close the session cached in the current thread, if any."""
187
+ current = _current_session.get()
188
+ if current is None or current[0] != get_ident():
189
+ return
190
+ _current_session.set(None)
191
+ with _session_lock:
192
+ sessions = _cached_sessions.get(current[0])
193
+ if sessions is not None:
194
+ sessions.discard(current[3])
195
+ if not sessions:
196
+ del _cached_sessions[current[0]]
197
+ current[3].close()
198
+
199
+
200
+ def _close_thread_sessions(thread_ids: set[int]) -> None:
201
+ """Close cached sessions after their worker threads have stopped."""
202
+ with _session_lock:
203
+ sessions = [
204
+ session
205
+ for thread_id in thread_ids
206
+ for session in _cached_sessions.pop(thread_id, ())
207
+ ]
208
+ for session in sessions:
209
+ session.close()
210
+
211
+
212
+ def get_context_session(model: SQLModel) -> SASession:
213
+ session = object_session(model)
214
+ if session is None:
215
+ raise RuntimeError(f"{model.__class__} is not attached to a session")
216
+
217
+ return session
218
+
219
+
220
+ @contextmanager
221
+ def session_context(*, expire_on_commit: bool = True) -> Generator[Session]:
222
+ if not _initialized.is_set():
223
+ create_db_and_tables()
224
+ with Session(engine, expire_on_commit=expire_on_commit) as session:
225
+ token = _current_session.set((get_ident(), engine, _engine_generation, session))
226
+ try:
227
+ yield session
228
+ finally:
229
+ _current_session.reset(token)
230
+
231
+
232
+ _register_engine(engine)
@@ -0,0 +1,27 @@
1
+ from . import (
2
+ cell,
3
+ config,
4
+ cross_section,
5
+ dependency,
6
+ enclosure,
7
+ factory,
8
+ geometry,
9
+ instance,
10
+ layer,
11
+ pdk,
12
+ port,
13
+ )
14
+
15
+ __all__ = [
16
+ "cell",
17
+ "config",
18
+ "cross_section",
19
+ "dependency",
20
+ "enclosure",
21
+ "factory",
22
+ "geometry",
23
+ "instance",
24
+ "layer",
25
+ "pdk",
26
+ "port",
27
+ ]
maskyard/models/box.py ADDED
@@ -0,0 +1,29 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from sqlmodel import LargeBinary, TypeDecorator
6
+
7
+ from .. import kdb
8
+
9
+ if TYPE_CHECKING:
10
+ from sqlalchemy import Dialect
11
+
12
+
13
+ class Box(TypeDecorator[kdb.Box]):
14
+ impl = LargeBinary
15
+ cache_ok = True
16
+
17
+ def process_bind_param(
18
+ self, value: kdb.Box | None, dialect: Dialect
19
+ ) -> bytes | None:
20
+ if value is None:
21
+ return None
22
+ return value.to_bytes()
23
+
24
+ def process_result_value(
25
+ self, value: bytes | None, dialect: Dialect
26
+ ) -> kdb.Box | None:
27
+ if value is None:
28
+ return None
29
+ return kdb.Box.from_bytes(value)