2016-03-15 19:12:39 -07:00
|
|
|
"""
|
2021-03-26 10:33:00 -07:00
|
|
|
GDSII file format readers and writers using the `klamath` library.
|
2020-05-17 22:59:54 -07:00
|
|
|
|
|
|
|
Note that GDSII references follow the same convention as `masque`,
|
|
|
|
with this order of operations:
|
|
|
|
1. Mirroring
|
|
|
|
2. Rotation
|
|
|
|
3. Scaling
|
|
|
|
4. Offset and array expansion (no mirroring/rotation/scaling applied to offsets)
|
|
|
|
|
|
|
|
Scaling, rotation, and mirroring apply to individual instances, not grid
|
|
|
|
vectors or offsets.
|
2020-09-26 17:33:46 -07:00
|
|
|
|
|
|
|
Notes:
|
|
|
|
* absolute positioning is not supported
|
|
|
|
* PLEX is not supported
|
|
|
|
* ELFLAGS are not supported
|
|
|
|
* GDS does not support library- or structure-level annotations
|
2021-03-26 10:33:00 -07:00
|
|
|
* Creation/modification/access times are set to 1900-01-01 for reproducibility.
|
2016-03-15 19:12:39 -07:00
|
|
|
"""
|
2020-10-16 19:00:50 -07:00
|
|
|
from typing import List, Any, Dict, Tuple, Callable, Union, Iterable, Optional
|
2023-01-13 20:33:14 -08:00
|
|
|
from typing import Sequence, BinaryIO, Mapping
|
2017-08-29 16:55:58 -07:00
|
|
|
import re
|
2019-04-20 15:29:56 -07:00
|
|
|
import io
|
2021-03-26 10:33:00 -07:00
|
|
|
import mmap
|
2019-04-20 15:26:27 -07:00
|
|
|
import copy
|
2019-04-13 21:10:08 -07:00
|
|
|
import base64
|
|
|
|
import struct
|
|
|
|
import logging
|
2019-04-20 15:29:56 -07:00
|
|
|
import pathlib
|
|
|
|
import gzip
|
2016-03-15 19:12:39 -07:00
|
|
|
|
2022-02-23 15:47:38 -08:00
|
|
|
import numpy
|
2022-07-07 16:06:06 -07:00
|
|
|
from numpy.typing import NDArray, ArrayLike
|
2021-03-26 10:33:00 -07:00
|
|
|
import klamath
|
|
|
|
from klamath import records
|
2020-05-17 17:22:50 -07:00
|
|
|
|
2021-03-26 10:33:00 -07:00
|
|
|
from .utils import is_gzipped
|
2020-07-22 02:45:16 -07:00
|
|
|
from .. import Pattern, SubPattern, PatternError, Label, Shape
|
2019-04-20 15:25:19 -07:00
|
|
|
from ..shapes import Polygon, Path
|
2020-07-22 02:45:16 -07:00
|
|
|
from ..repetition import Grid
|
2021-03-26 10:33:00 -07:00
|
|
|
from ..utils import layer_t, normalize_mirror, annotations_t
|
2023-01-13 20:33:14 -08:00
|
|
|
from ..library import LazyLibrary, WrapLibrary, MutableLibrary
|
|
|
|
|
2016-03-15 19:12:39 -07:00
|
|
|
|
2019-04-13 21:10:08 -07:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2019-04-20 15:42:42 -07:00
|
|
|
path_cap_map = {
|
2020-10-16 19:00:50 -07:00
|
|
|
0: Path.Cap.Flush,
|
|
|
|
1: Path.Cap.Circle,
|
|
|
|
2: Path.Cap.Square,
|
|
|
|
4: Path.Cap.SquareCustom,
|
|
|
|
}
|
2019-04-20 15:25:19 -07:00
|
|
|
|
|
|
|
|
2022-07-07 11:27:29 -07:00
|
|
|
def rint_cast(val: ArrayLike) -> NDArray[numpy.int32]:
|
|
|
|
return numpy.rint(val, dtype=numpy.int32, casting='unsafe')
|
|
|
|
|
|
|
|
|
2022-02-23 11:27:11 -08:00
|
|
|
def write(
|
2022-07-07 11:27:29 -07:00
|
|
|
library: Mapping[str, Pattern],
|
2022-02-23 11:27:11 -08:00
|
|
|
stream: BinaryIO,
|
|
|
|
meters_per_unit: float,
|
|
|
|
logical_units_per_unit: float = 1,
|
|
|
|
library_name: str = 'masque-klamath',
|
|
|
|
*,
|
|
|
|
modify_originals: bool = False,
|
|
|
|
) -> None:
|
2017-08-29 15:45:00 -07:00
|
|
|
"""
|
2022-07-07 11:27:29 -07:00
|
|
|
Convert a library to a GDSII stream, mapping data as follows:
|
2021-03-26 10:33:00 -07:00
|
|
|
Pattern -> GDSII structure
|
|
|
|
SubPattern -> GDSII SREF or AREF
|
|
|
|
Path -> GSDII path
|
|
|
|
Shape (other than path) -> GDSII boundary/ies
|
|
|
|
Label -> GDSII text
|
|
|
|
annnotations -> properties, where possible
|
2017-08-29 15:45:00 -07:00
|
|
|
|
|
|
|
For each shape,
|
2020-02-17 21:02:53 -08:00
|
|
|
layer is chosen to be equal to `shape.layer` if it is an int,
|
|
|
|
or `shape.layer[0]` if it is a tuple
|
|
|
|
datatype is chosen to be `shape.layer[1]` if available,
|
|
|
|
otherwise `0`
|
2017-08-29 15:45:00 -07:00
|
|
|
|
2020-02-17 21:02:53 -08:00
|
|
|
It is often a good idea to run `pattern.subpatternize()` prior to calling this function,
|
|
|
|
especially if calling `.polygonize()` will result in very many vertices.
|
2017-08-29 15:45:00 -07:00
|
|
|
|
2020-02-17 21:02:53 -08:00
|
|
|
If you want pattern polygonized with non-default arguments, just call `pattern.polygonize()`
|
2017-08-29 15:45:00 -07:00
|
|
|
prior to calling this function.
|
|
|
|
|
2020-02-17 21:02:53 -08:00
|
|
|
Args:
|
2022-07-07 11:27:29 -07:00
|
|
|
library: A {name: Pattern} mapping of patterns to write.
|
2020-02-17 21:02:53 -08:00
|
|
|
meters_per_unit: Written into the GDSII file, meters per (database) length unit.
|
|
|
|
All distances are assumed to be an integer multiple of this unit, and are stored as such.
|
|
|
|
logical_units_per_unit: Written into the GDSII file. Allows the GDSII to specify a
|
|
|
|
"logical" unit which is different from the "database" unit, for display purposes.
|
|
|
|
Default `1`.
|
|
|
|
library_name: Library name written into the GDSII file.
|
2021-03-26 10:33:00 -07:00
|
|
|
Default 'masque-klamath'.
|
2020-02-17 21:02:53 -08:00
|
|
|
modify_originals: If `True`, the original pattern is modified as part of the writing
|
2022-07-07 11:27:29 -07:00
|
|
|
process. Otherwise, a copy is made.
|
2020-02-17 21:02:53 -08:00
|
|
|
Default `False`.
|
2017-08-29 15:45:00 -07:00
|
|
|
"""
|
2023-01-13 20:33:14 -08:00
|
|
|
# TODO check name errors
|
|
|
|
bad_keys = check_valid_names(library.keys())
|
|
|
|
|
|
|
|
# TODO check all hierarchy present
|
2019-12-12 01:19:07 -08:00
|
|
|
|
|
|
|
if not modify_originals:
|
2023-01-13 20:33:14 -08:00
|
|
|
library = library.deepcopy() #TODO figure out best approach e.g. if lazy
|
2019-12-12 01:19:07 -08:00
|
|
|
|
2023-01-13 20:33:14 -08:00
|
|
|
if not isinstance(library, MutableLibrary):
|
|
|
|
if isinstance(library, dict):
|
|
|
|
library = WrapLibrary(library)
|
|
|
|
else:
|
|
|
|
library = WrapLibrary(dict(library))
|
2022-07-07 11:27:29 -07:00
|
|
|
|
2023-01-13 20:33:14 -08:00
|
|
|
library.wrap_repeated_shapes()
|
2020-07-27 01:32:34 -07:00
|
|
|
|
2017-08-29 15:45:00 -07:00
|
|
|
# Create library
|
2022-07-07 11:27:29 -07:00
|
|
|
header = klamath.library.FileHeader(
|
|
|
|
name=library_name.encode('ASCII'),
|
|
|
|
user_units_per_db_unit=logical_units_per_unit,
|
|
|
|
meters_per_db_unit=meters_per_unit,
|
|
|
|
)
|
2021-03-26 10:33:00 -07:00
|
|
|
header.write(stream)
|
2017-08-29 15:45:00 -07:00
|
|
|
|
2017-08-29 15:57:37 -07:00
|
|
|
# Now create a structure for each pattern, and add in any Boundary and SREF elements
|
2023-01-13 20:33:14 -08:00
|
|
|
for name, pat in library.items():
|
2021-03-26 10:33:00 -07:00
|
|
|
elements: List[klamath.elements.Element] = []
|
|
|
|
elements += _shapes_to_elements(pat.shapes)
|
|
|
|
elements += _labels_to_texts(pat.labels)
|
|
|
|
elements += _subpatterns_to_refs(pat.subpatterns)
|
2017-08-29 15:45:00 -07:00
|
|
|
|
2022-07-07 11:27:29 -07:00
|
|
|
klamath.library.write_struct(stream, name=name.encode('ASCII'), elements=elements)
|
2021-03-26 10:33:00 -07:00
|
|
|
records.ENDLIB.write(stream, None)
|
2020-05-19 00:03:29 -07:00
|
|
|
|
|
|
|
|
2022-02-23 11:27:11 -08:00
|
|
|
def writefile(
|
2022-07-07 11:27:29 -07:00
|
|
|
library: Mapping[str, Pattern],
|
2022-02-23 11:27:11 -08:00
|
|
|
filename: Union[str, pathlib.Path],
|
|
|
|
*args,
|
|
|
|
**kwargs,
|
|
|
|
) -> None:
|
2016-03-15 19:12:39 -07:00
|
|
|
"""
|
2021-03-26 10:33:00 -07:00
|
|
|
Wrapper for `write()` that takes a filename or path instead of a stream.
|
2016-03-15 19:12:39 -07:00
|
|
|
|
2019-04-20 15:29:56 -07:00
|
|
|
Will automatically compress the file if it has a .gz suffix.
|
2020-02-17 21:02:53 -08:00
|
|
|
|
|
|
|
Args:
|
2022-07-07 11:27:29 -07:00
|
|
|
library: {name: Pattern} pairs to save.
|
2020-02-17 21:02:53 -08:00
|
|
|
filename: Filename to save to.
|
2021-03-26 10:33:00 -07:00
|
|
|
*args: passed to `write()`
|
|
|
|
**kwargs: passed to `write()`
|
2016-03-15 19:12:39 -07:00
|
|
|
"""
|
2019-04-20 15:29:56 -07:00
|
|
|
path = pathlib.Path(filename)
|
2019-05-15 00:11:28 -07:00
|
|
|
if path.suffix == '.gz':
|
2020-05-11 19:09:35 -07:00
|
|
|
open_func: Callable = gzip.open
|
2019-04-20 15:29:56 -07:00
|
|
|
else:
|
|
|
|
open_func = open
|
|
|
|
|
2019-05-15 23:50:31 -07:00
|
|
|
with io.BufferedWriter(open_func(path, mode='wb')) as stream:
|
2023-01-13 20:33:14 -08:00
|
|
|
write(library, stream, *args, **kwargs)
|
2019-03-31 20:57:10 -07:00
|
|
|
|
2016-03-15 19:12:39 -07:00
|
|
|
|
2022-02-23 11:27:11 -08:00
|
|
|
def readfile(
|
|
|
|
filename: Union[str, pathlib.Path],
|
|
|
|
*args,
|
|
|
|
**kwargs,
|
|
|
|
) -> Tuple[Dict[str, Pattern], Dict[str, Any]]:
|
2017-08-29 15:45:00 -07:00
|
|
|
"""
|
2021-03-26 10:33:00 -07:00
|
|
|
Wrapper for `read()` that takes a filename or path instead of a stream.
|
2019-04-20 15:29:56 -07:00
|
|
|
|
2020-09-29 00:57:26 -07:00
|
|
|
Will automatically decompress gzipped files.
|
2020-02-17 21:02:53 -08:00
|
|
|
|
|
|
|
Args:
|
|
|
|
filename: Filename to save to.
|
2021-03-26 10:33:00 -07:00
|
|
|
*args: passed to `read()`
|
|
|
|
**kwargs: passed to `read()`
|
2017-08-29 15:45:00 -07:00
|
|
|
"""
|
2019-04-20 15:29:56 -07:00
|
|
|
path = pathlib.Path(filename)
|
2020-09-29 00:57:26 -07:00
|
|
|
if is_gzipped(path):
|
2020-05-11 19:09:35 -07:00
|
|
|
open_func: Callable = gzip.open
|
2019-04-20 15:29:56 -07:00
|
|
|
else:
|
|
|
|
open_func = open
|
|
|
|
|
2019-05-15 23:50:31 -07:00
|
|
|
with io.BufferedReader(open_func(path, mode='rb')) as stream:
|
2019-04-20 15:29:56 -07:00
|
|
|
results = read(stream, *args, **kwargs)
|
|
|
|
return results
|
2017-08-29 15:45:00 -07:00
|
|
|
|
|
|
|
|
2022-02-23 11:27:11 -08:00
|
|
|
def read(
|
|
|
|
stream: BinaryIO,
|
|
|
|
raw_mode: bool = True,
|
|
|
|
) -> Tuple[Dict[str, Pattern], Dict[str, Any]]:
|
2016-03-15 19:12:39 -07:00
|
|
|
"""
|
2018-09-16 20:18:04 -07:00
|
|
|
Read a gdsii file and translate it into a dict of Pattern objects. GDSII structures are
|
2016-03-15 19:12:39 -07:00
|
|
|
translated into Pattern objects; boundaries are translated into polygons, and srefs and arefs
|
|
|
|
are translated into SubPattern objects.
|
|
|
|
|
2018-09-16 20:19:28 -07:00
|
|
|
Additional library info is returned in a dict, containing:
|
|
|
|
'name': name of the library
|
|
|
|
'meters_per_unit': number of meters per database unit (all values are in database units)
|
|
|
|
'logical_units_per_unit': number of "logical" units displayed by layout tools (typically microns)
|
|
|
|
per database unit
|
|
|
|
|
2020-02-17 21:02:53 -08:00
|
|
|
Args:
|
2020-05-17 14:12:38 -07:00
|
|
|
stream: Stream to read from.
|
2021-03-26 10:33:00 -07:00
|
|
|
raw_mode: If True, constructs shapes in raw mode, bypassing most data validation, Default True.
|
2020-02-17 21:02:53 -08:00
|
|
|
|
|
|
|
Returns:
|
|
|
|
- Dict of pattern_name:Patterns generated from GDSII structures
|
|
|
|
- Dict of GDSII library info
|
2016-03-15 19:12:39 -07:00
|
|
|
"""
|
2021-03-26 10:33:00 -07:00
|
|
|
library_info = _read_header(stream)
|
2020-08-15 18:20:37 -07:00
|
|
|
|
2022-07-07 11:27:29 -07:00
|
|
|
patterns_dict = {}
|
2021-03-26 10:33:00 -07:00
|
|
|
found_struct = records.BGNSTR.skip_past(stream)
|
|
|
|
while found_struct:
|
|
|
|
name = records.STRNAME.skip_and_read(stream)
|
2022-07-07 11:27:29 -07:00
|
|
|
pat = read_elements(stream, raw_mode=raw_mode)
|
|
|
|
patterns_dict[name.decode('ASCII')] = pat
|
2021-03-26 10:33:00 -07:00
|
|
|
found_struct = records.BGNSTR.skip_past(stream)
|
2016-03-15 19:12:39 -07:00
|
|
|
|
|
|
|
return patterns_dict, library_info
|
2018-08-30 23:05:30 -07:00
|
|
|
|
|
|
|
|
2021-03-26 10:33:00 -07:00
|
|
|
def _read_header(stream: BinaryIO) -> Dict[str, Any]:
|
|
|
|
"""
|
|
|
|
Read the file header and create the library_info dict.
|
|
|
|
"""
|
|
|
|
header = klamath.library.FileHeader.read(stream)
|
|
|
|
|
|
|
|
library_info = {'name': header.name.decode('ASCII'),
|
|
|
|
'meters_per_unit': header.meters_per_db_unit,
|
|
|
|
'logical_units_per_unit': header.user_units_per_db_unit,
|
|
|
|
}
|
|
|
|
return library_info
|
|
|
|
|
|
|
|
|
2022-02-23 11:27:11 -08:00
|
|
|
def read_elements(
|
|
|
|
stream: BinaryIO,
|
|
|
|
raw_mode: bool = True,
|
|
|
|
) -> Pattern:
|
2021-03-26 10:33:00 -07:00
|
|
|
"""
|
|
|
|
Read elements from a GDS structure and build a Pattern from them.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
stream: Seekable stream, positioned at a record boundary.
|
|
|
|
Will be read until an ENDSTR record is consumed.
|
|
|
|
name: Name of the resulting Pattern
|
|
|
|
raw_mode: If True, bypass per-shape data validation. Default True.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A pattern containing the elements that were read.
|
|
|
|
"""
|
2022-07-07 11:27:29 -07:00
|
|
|
pat = Pattern()
|
2021-03-26 10:33:00 -07:00
|
|
|
|
|
|
|
elements = klamath.library.read_elements(stream)
|
|
|
|
for element in elements:
|
|
|
|
if isinstance(element, klamath.elements.Boundary):
|
|
|
|
poly = _boundary_to_polygon(element, raw_mode)
|
|
|
|
pat.shapes.append(poly)
|
|
|
|
elif isinstance(element, klamath.elements.Path):
|
|
|
|
path = _gpath_to_mpath(element, raw_mode)
|
|
|
|
pat.shapes.append(path)
|
|
|
|
elif isinstance(element, klamath.elements.Text):
|
2022-07-07 11:27:29 -07:00
|
|
|
label = Label(
|
|
|
|
offset=element.xy.astype(float),
|
|
|
|
layer=element.layer,
|
|
|
|
string=element.string.decode('ASCII'),
|
|
|
|
annotations=_properties_to_annotations(element.properties),
|
|
|
|
)
|
2021-03-26 10:33:00 -07:00
|
|
|
pat.labels.append(label)
|
|
|
|
elif isinstance(element, klamath.elements.Reference):
|
|
|
|
pat.subpatterns.append(_ref_to_subpat(element))
|
|
|
|
return pat
|
|
|
|
|
|
|
|
|
2020-05-11 18:39:02 -07:00
|
|
|
def _mlayer2gds(mlayer: layer_t) -> Tuple[int, int]:
|
2020-02-17 21:02:53 -08:00
|
|
|
""" Helper to turn a layer tuple-or-int into a layer and datatype"""
|
2020-05-12 14:17:35 -07:00
|
|
|
if isinstance(mlayer, int):
|
2018-08-30 23:05:30 -07:00
|
|
|
layer = mlayer
|
|
|
|
data_type = 0
|
2020-05-17 14:11:47 -07:00
|
|
|
elif isinstance(mlayer, tuple):
|
2018-08-30 23:05:30 -07:00
|
|
|
layer = mlayer[0]
|
|
|
|
if len(mlayer) > 1:
|
|
|
|
data_type = mlayer[1]
|
|
|
|
else:
|
|
|
|
data_type = 0
|
2020-05-17 14:11:47 -07:00
|
|
|
else:
|
2020-09-09 19:41:06 -07:00
|
|
|
raise PatternError(f'Invalid layer for gdsii: {mlayer}. Note that gdsii layers cannot be strings.')
|
2018-08-30 23:05:30 -07:00
|
|
|
return layer, data_type
|
2019-03-31 20:57:10 -07:00
|
|
|
|
|
|
|
|
2022-02-23 11:27:11 -08:00
|
|
|
def _ref_to_subpat(ref: klamath.library.Reference) -> SubPattern:
|
2020-02-17 21:02:53 -08:00
|
|
|
"""
|
2022-07-07 11:27:29 -07:00
|
|
|
Helper function to create a SubPattern from an SREF or AREF. Sets subpat.target to struct_name.
|
2020-02-17 21:02:53 -08:00
|
|
|
"""
|
2021-03-26 10:33:00 -07:00
|
|
|
xy = ref.xy.astype(float)
|
|
|
|
offset = xy[0]
|
2020-07-22 02:45:16 -07:00
|
|
|
repetition = None
|
2021-03-26 10:33:00 -07:00
|
|
|
if ref.colrow is not None:
|
|
|
|
a_count, b_count = ref.colrow
|
|
|
|
a_vector = (xy[1] - offset) / a_count
|
|
|
|
b_vector = (xy[2] - offset) / b_count
|
2020-07-22 02:45:16 -07:00
|
|
|
repetition = Grid(a_vector=a_vector, b_vector=b_vector,
|
|
|
|
a_count=a_count, b_count=b_count)
|
|
|
|
|
2022-07-07 11:27:29 -07:00
|
|
|
subpat = SubPattern(
|
2023-01-13 20:33:14 -08:00
|
|
|
target=ref.struct_name.decode('ASCII'),
|
2022-07-07 11:27:29 -07:00
|
|
|
offset=offset,
|
|
|
|
rotation=numpy.deg2rad(ref.angle_deg),
|
|
|
|
scale=ref.mag,
|
|
|
|
mirrored=(ref.invert_y, False),
|
|
|
|
annotations=_properties_to_annotations(ref.properties),
|
|
|
|
repetition=repetition,
|
|
|
|
)
|
2020-07-22 02:45:16 -07:00
|
|
|
return subpat
|
2019-03-31 20:57:10 -07:00
|
|
|
|
|
|
|
|
2021-03-26 10:33:00 -07:00
|
|
|
def _gpath_to_mpath(gpath: klamath.library.Path, raw_mode: bool) -> Path:
|
|
|
|
if gpath.path_type in path_cap_map:
|
|
|
|
cap = path_cap_map[gpath.path_type]
|
2020-08-15 18:20:37 -07:00
|
|
|
else:
|
2021-03-26 10:33:00 -07:00
|
|
|
raise PatternError(f'Unrecognized path type: {gpath.path_type}')
|
|
|
|
|
2022-07-07 11:27:29 -07:00
|
|
|
mpath = Path(
|
|
|
|
vertices=gpath.xy.astype(float),
|
|
|
|
layer=gpath.layer,
|
|
|
|
width=gpath.width,
|
|
|
|
cap=cap,
|
|
|
|
offset=numpy.zeros(2),
|
|
|
|
annotations=_properties_to_annotations(gpath.properties),
|
|
|
|
raw=raw_mode,
|
|
|
|
)
|
2020-08-15 18:20:37 -07:00
|
|
|
if cap == Path.Cap.SquareCustom:
|
2021-03-26 10:33:00 -07:00
|
|
|
mpath.cap_extensions = gpath.extension
|
|
|
|
return mpath
|
2020-08-15 18:20:37 -07:00
|
|
|
|
|
|
|
|
2021-03-26 10:33:00 -07:00
|
|
|
def _boundary_to_polygon(boundary: klamath.library.Boundary, raw_mode: bool) -> Polygon:
|
2022-07-07 11:27:29 -07:00
|
|
|
return Polygon(
|
|
|
|
vertices=boundary.xy[:-1].astype(float),
|
|
|
|
layer=boundary.layer,
|
|
|
|
offset=numpy.zeros(2),
|
|
|
|
annotations=_properties_to_annotations(boundary.properties),
|
|
|
|
raw=raw_mode,
|
|
|
|
)
|
2020-08-15 18:20:37 -07:00
|
|
|
|
|
|
|
|
2022-02-23 11:27:11 -08:00
|
|
|
def _subpatterns_to_refs(subpatterns: List[SubPattern]) -> List[klamath.library.Reference]:
|
2019-03-31 20:57:10 -07:00
|
|
|
refs = []
|
|
|
|
for subpat in subpatterns:
|
2022-07-07 11:27:29 -07:00
|
|
|
if subpat.target is None:
|
2020-05-11 18:58:57 -07:00
|
|
|
continue
|
2022-07-07 11:27:29 -07:00
|
|
|
encoded_name = subpat.target.encode('ASCII')
|
2019-03-31 20:57:10 -07:00
|
|
|
|
2019-12-05 23:18:18 -08:00
|
|
|
# Note: GDS mirrors first and rotates second
|
2020-02-07 23:01:14 -08:00
|
|
|
mirror_across_x, extra_angle = normalize_mirror(subpat.mirrored)
|
2020-07-22 02:45:16 -07:00
|
|
|
rep = subpat.repetition
|
2021-03-26 10:33:00 -07:00
|
|
|
angle_deg = numpy.rad2deg(subpat.rotation + extra_angle) % 360
|
|
|
|
properties = _annotations_to_properties(subpat.annotations, 512)
|
2020-07-22 21:48:34 -07:00
|
|
|
|
2020-07-22 02:45:16 -07:00
|
|
|
if isinstance(rep, Grid):
|
2022-02-23 15:47:38 -08:00
|
|
|
b_vector = rep.b_vector if rep.b_vector is not None else numpy.zeros(2)
|
|
|
|
b_count = rep.b_count if rep.b_count is not None else 1
|
|
|
|
xy: NDArray[numpy.float64] = numpy.array(subpat.offset) + [
|
2020-10-16 19:00:50 -07:00
|
|
|
[0, 0],
|
|
|
|
rep.a_vector * rep.a_count,
|
2022-02-23 15:47:38 -08:00
|
|
|
b_vector * b_count,
|
2020-10-16 19:00:50 -07:00
|
|
|
]
|
2022-07-07 11:27:29 -07:00
|
|
|
aref = klamath.library.Reference(
|
|
|
|
struct_name=encoded_name,
|
|
|
|
xy=rint_cast(xy),
|
|
|
|
colrow=(numpy.rint(rep.a_count), numpy.rint(rep.b_count)),
|
|
|
|
angle_deg=angle_deg,
|
|
|
|
invert_y=mirror_across_x,
|
|
|
|
mag=subpat.scale,
|
|
|
|
properties=properties,
|
|
|
|
)
|
2021-03-26 10:33:00 -07:00
|
|
|
refs.append(aref)
|
2020-07-22 02:45:16 -07:00
|
|
|
elif rep is None:
|
2022-07-07 11:27:29 -07:00
|
|
|
ref = klamath.library.Reference(
|
|
|
|
struct_name=encoded_name,
|
|
|
|
xy=rint_cast([subpat.offset]),
|
|
|
|
colrow=None,
|
|
|
|
angle_deg=angle_deg,
|
|
|
|
invert_y=mirror_across_x,
|
|
|
|
mag=subpat.scale,
|
|
|
|
properties=properties,
|
|
|
|
)
|
2021-03-26 10:33:00 -07:00
|
|
|
refs.append(ref)
|
2020-07-22 02:45:16 -07:00
|
|
|
else:
|
2022-07-07 11:27:29 -07:00
|
|
|
new_srefs = [
|
|
|
|
klamath.library.Reference(
|
|
|
|
struct_name=encoded_name,
|
|
|
|
xy=rint_cast([subpat.offset + dd]),
|
|
|
|
colrow=None,
|
|
|
|
angle_deg=angle_deg,
|
|
|
|
invert_y=mirror_across_x,
|
|
|
|
mag=subpat.scale,
|
|
|
|
properties=properties,
|
|
|
|
)
|
|
|
|
for dd in rep.displacements]
|
2021-03-26 10:33:00 -07:00
|
|
|
refs += new_srefs
|
2019-03-31 20:57:10 -07:00
|
|
|
return refs
|
|
|
|
|
|
|
|
|
2021-03-26 10:33:00 -07:00
|
|
|
def _properties_to_annotations(properties: Dict[int, bytes]) -> annotations_t:
|
|
|
|
return {str(k): [v.decode()] for k, v in properties.items()}
|
2020-09-10 20:06:58 -07:00
|
|
|
|
|
|
|
|
2021-03-26 10:33:00 -07:00
|
|
|
def _annotations_to_properties(annotations: annotations_t, max_len: int = 126) -> Dict[int, bytes]:
|
2020-09-10 20:06:58 -07:00
|
|
|
cum_len = 0
|
2021-03-26 10:33:00 -07:00
|
|
|
props = {}
|
2020-09-10 20:06:58 -07:00
|
|
|
for key, vals in annotations.items():
|
|
|
|
try:
|
|
|
|
i = int(key)
|
2020-10-16 19:00:50 -07:00
|
|
|
except ValueError:
|
2020-09-10 20:06:58 -07:00
|
|
|
raise PatternError(f'Annotation key {key} is not convertable to an integer')
|
|
|
|
if not (0 < i < 126):
|
|
|
|
raise PatternError(f'Annotation key {key} converts to {i} (must be in the range [1,125])')
|
|
|
|
|
|
|
|
val_strings = ' '.join(str(val) for val in vals)
|
|
|
|
b = val_strings.encode()
|
|
|
|
if len(b) > 126:
|
|
|
|
raise PatternError(f'Annotation value {b!r} is longer than 126 characters!')
|
|
|
|
cum_len += numpy.ceil(len(b) / 2) * 2 + 2
|
|
|
|
if cum_len > max_len:
|
|
|
|
raise PatternError(f'Sum of annotation data will be longer than {max_len} bytes! Generated bytes were {b!r}')
|
2021-03-26 10:33:00 -07:00
|
|
|
props[i] = b
|
2020-09-10 20:06:58 -07:00
|
|
|
return props
|
|
|
|
|
|
|
|
|
2022-02-23 11:27:11 -08:00
|
|
|
def _shapes_to_elements(
|
|
|
|
shapes: List[Shape],
|
|
|
|
polygonize_paths: bool = False,
|
|
|
|
) -> List[klamath.elements.Element]:
|
2021-03-26 10:33:00 -07:00
|
|
|
elements: List[klamath.elements.Element] = []
|
2019-04-20 15:25:19 -07:00
|
|
|
# Add a Boundary element for each shape, and Path elements if necessary
|
2019-03-31 20:57:10 -07:00
|
|
|
for shape in shapes:
|
|
|
|
layer, data_type = _mlayer2gds(shape.layer)
|
2020-09-10 20:06:58 -07:00
|
|
|
properties = _annotations_to_properties(shape.annotations, 128)
|
2019-04-20 15:25:19 -07:00
|
|
|
if isinstance(shape, Path) and not polygonize_paths:
|
2022-07-07 11:27:29 -07:00
|
|
|
xy = rint_cast(shape.vertices + shape.offset)
|
|
|
|
width = rint_cast(shape.width)
|
2020-10-16 19:00:50 -07:00
|
|
|
path_type = next(k for k, v in path_cap_map.items() if v == shape.cap) # reverse lookup
|
2021-03-26 10:33:00 -07:00
|
|
|
|
|
|
|
extension: Tuple[int, int]
|
|
|
|
if shape.cap == Path.Cap.SquareCustom and shape.cap_extensions is not None:
|
|
|
|
extension = tuple(shape.cap_extensions) # type: ignore
|
|
|
|
else:
|
|
|
|
extension = (0, 0)
|
|
|
|
|
2022-07-07 11:27:29 -07:00
|
|
|
path = klamath.elements.Path(
|
|
|
|
layer=(layer, data_type),
|
|
|
|
xy=xy,
|
|
|
|
path_type=path_type,
|
|
|
|
width=width,
|
|
|
|
extension=extension,
|
|
|
|
properties=properties,
|
|
|
|
)
|
2019-04-20 15:25:19 -07:00
|
|
|
elements.append(path)
|
2021-03-26 10:33:00 -07:00
|
|
|
elif isinstance(shape, Polygon):
|
|
|
|
polygon = shape
|
2022-06-08 20:55:25 -07:00
|
|
|
xy_closed = numpy.empty((polygon.vertices.shape[0] + 1, 2), dtype=numpy.int32)
|
|
|
|
numpy.rint(polygon.vertices + polygon.offset, out=xy_closed[:-1], casting='unsafe')
|
|
|
|
xy_closed[-1] = xy_closed[0]
|
2022-07-07 11:27:29 -07:00
|
|
|
boundary = klamath.elements.Boundary(
|
|
|
|
layer=(layer, data_type),
|
|
|
|
xy=xy_closed,
|
|
|
|
properties=properties,
|
|
|
|
)
|
2021-03-26 10:33:00 -07:00
|
|
|
elements.append(boundary)
|
2019-04-20 15:25:19 -07:00
|
|
|
else:
|
|
|
|
for polygon in shape.to_polygons():
|
2022-06-08 20:55:25 -07:00
|
|
|
xy_closed = numpy.empty((polygon.vertices.shape[0] + 1, 2), dtype=numpy.int32)
|
|
|
|
numpy.rint(polygon.vertices + polygon.offset, out=xy_closed[:-1], casting='unsafe')
|
|
|
|
xy_closed[-1] = xy_closed[0]
|
2022-07-07 11:27:29 -07:00
|
|
|
boundary = klamath.elements.Boundary(
|
|
|
|
layer=(layer, data_type),
|
|
|
|
xy=xy_closed,
|
|
|
|
properties=properties,
|
|
|
|
)
|
2020-09-10 20:06:58 -07:00
|
|
|
elements.append(boundary)
|
2019-04-20 15:25:19 -07:00
|
|
|
return elements
|
2019-03-31 20:57:10 -07:00
|
|
|
|
|
|
|
|
2021-03-26 10:33:00 -07:00
|
|
|
def _labels_to_texts(labels: List[Label]) -> List[klamath.elements.Text]:
|
2019-03-31 20:57:10 -07:00
|
|
|
texts = []
|
|
|
|
for label in labels:
|
2020-09-10 20:06:58 -07:00
|
|
|
properties = _annotations_to_properties(label.annotations, 128)
|
2019-03-31 20:57:10 -07:00
|
|
|
layer, text_type = _mlayer2gds(label.layer)
|
2022-07-07 11:27:29 -07:00
|
|
|
xy = rint_cast([label.offset])
|
|
|
|
text = klamath.elements.Text(
|
|
|
|
layer=(layer, text_type),
|
|
|
|
xy=xy,
|
|
|
|
string=label.string.encode('ASCII'),
|
|
|
|
properties=properties,
|
|
|
|
presentation=0, # TODO maybe set some of these?
|
|
|
|
angle_deg=0,
|
|
|
|
invert_y=False,
|
|
|
|
width=0,
|
|
|
|
path_type=0,
|
|
|
|
mag=1,
|
|
|
|
)
|
2020-09-10 20:06:58 -07:00
|
|
|
texts.append(text)
|
2019-03-31 20:57:10 -07:00
|
|
|
return texts
|
2019-04-13 21:10:08 -07:00
|
|
|
|
|
|
|
|
2022-02-23 11:27:11 -08:00
|
|
|
def disambiguate_pattern_names(
|
2022-07-07 11:27:29 -07:00
|
|
|
names: Iterable[str],
|
2022-02-23 11:27:11 -08:00
|
|
|
max_name_length: int = 32,
|
|
|
|
suffix_length: int = 6,
|
2022-07-07 11:27:29 -07:00
|
|
|
) -> List[str]:
|
2020-05-23 19:37:55 -07:00
|
|
|
"""
|
|
|
|
Args:
|
2022-07-07 11:27:29 -07:00
|
|
|
names: List of pattern names to disambiguate
|
2020-05-23 19:37:55 -07:00
|
|
|
max_name_length: Names longer than this will be truncated
|
|
|
|
suffix_length: Names which get truncated are truncated by this many extra characters. This is to
|
|
|
|
leave room for a suffix if one is necessary.
|
|
|
|
"""
|
2022-07-07 11:27:29 -07:00
|
|
|
new_names = []
|
|
|
|
for name in names:
|
2020-05-23 19:37:55 -07:00
|
|
|
# Shorten names which already exceed max-length
|
2022-07-07 11:27:29 -07:00
|
|
|
if len(name) > max_name_length:
|
|
|
|
shortened_name = name[:max_name_length - suffix_length]
|
|
|
|
logger.warning(f'Pattern name "{name}" is too long ({len(name)}/{max_name_length} chars),\n'
|
2020-10-16 19:00:50 -07:00
|
|
|
+ f' shortening to "{shortened_name}" before generating suffix')
|
2019-05-15 23:51:00 -07:00
|
|
|
else:
|
2022-07-07 11:27:29 -07:00
|
|
|
shortened_name = name
|
2019-05-15 23:51:00 -07:00
|
|
|
|
2020-05-23 19:37:55 -07:00
|
|
|
# Remove invalid characters
|
2020-10-16 19:00:50 -07:00
|
|
|
sanitized_name = re.compile(r'[^A-Za-z0-9_\?\$]').sub('_', shortened_name)
|
2019-04-13 21:10:08 -07:00
|
|
|
|
2020-05-23 19:37:55 -07:00
|
|
|
# Add a suffix that makes the name unique
|
2019-04-13 21:10:08 -07:00
|
|
|
i = 0
|
|
|
|
suffixed_name = sanitized_name
|
2022-07-07 11:27:29 -07:00
|
|
|
while suffixed_name in new_names or suffixed_name == '':
|
2019-04-13 21:10:08 -07:00
|
|
|
suffix = base64.b64encode(struct.pack('>Q', i), b'$?').decode('ASCII')
|
|
|
|
|
|
|
|
suffixed_name = sanitized_name + '$' + suffix[:-1].lstrip('A')
|
|
|
|
i += 1
|
|
|
|
|
2019-04-18 01:14:08 -07:00
|
|
|
if sanitized_name == '':
|
2020-08-15 18:23:04 -07:00
|
|
|
logger.warning(f'Empty pattern name saved as "{suffixed_name}"')
|
2019-04-13 21:10:08 -07:00
|
|
|
|
2020-05-23 19:37:55 -07:00
|
|
|
# Encode into a byte-string and perform some final checks
|
2019-04-16 00:41:18 -07:00
|
|
|
encoded_name = suffixed_name.encode('ASCII')
|
2019-04-13 21:10:08 -07:00
|
|
|
if len(encoded_name) == 0:
|
2019-04-18 01:14:08 -07:00
|
|
|
# Should never happen since zero-length names are replaced
|
2022-07-07 11:27:29 -07:00
|
|
|
raise PatternError(f'Zero-length name after sanitize+encode,\n originally "{name}"')
|
2019-12-12 01:19:07 -08:00
|
|
|
if len(encoded_name) > max_name_length:
|
2020-10-16 19:00:50 -07:00
|
|
|
raise PatternError(f'Pattern name "{encoded_name!r}" length > {max_name_length} after encode,\n'
|
2022-07-07 11:27:29 -07:00
|
|
|
+ f' originally "{name}"')
|
2019-04-13 21:10:08 -07:00
|
|
|
|
2022-07-07 11:27:29 -07:00
|
|
|
new_names.append(suffixed_name)
|
|
|
|
return new_names
|
2021-03-26 10:33:00 -07:00
|
|
|
|
|
|
|
|
2022-02-23 11:27:11 -08:00
|
|
|
def load_library(
|
|
|
|
stream: BinaryIO,
|
|
|
|
*,
|
|
|
|
full_load: bool = False,
|
2023-01-13 20:33:14 -08:00
|
|
|
) -> Tuple[LazyLibrary, Dict[str, Any]]:
|
2021-03-26 10:33:00 -07:00
|
|
|
"""
|
|
|
|
Scan a GDSII stream to determine what structures are present, and create
|
|
|
|
a library from them. This enables deferred reading of structures
|
|
|
|
on an as-needed basis.
|
|
|
|
All structures are loaded as secondary
|
|
|
|
|
|
|
|
Args:
|
|
|
|
stream: Seekable stream. Position 0 should be the start of the file.
|
2022-07-07 11:27:29 -07:00
|
|
|
The caller should leave the stream open while the library
|
|
|
|
is still in use, since the library will need to access it
|
|
|
|
in order to read the structure contents.
|
2021-03-26 10:33:00 -07:00
|
|
|
full_load: If True, force all structures to be read immediately rather
|
2022-07-07 11:27:29 -07:00
|
|
|
than as-needed. Since data is read sequentially from the file, this
|
|
|
|
will be faster than using the resulting library's `precache` method.
|
2021-03-26 10:33:00 -07:00
|
|
|
|
|
|
|
Returns:
|
2023-01-13 20:33:14 -08:00
|
|
|
LazyLibrary object, allowing for deferred load of structures.
|
2021-03-26 10:33:00 -07:00
|
|
|
Additional library info (dict, same format as from `read`).
|
|
|
|
"""
|
|
|
|
stream.seek(0)
|
2023-01-13 20:33:14 -08:00
|
|
|
lib = LazyLibrary()
|
2021-03-26 10:33:00 -07:00
|
|
|
|
|
|
|
if full_load:
|
|
|
|
# Full load approach (immediately load everything)
|
|
|
|
patterns, library_info = read(stream)
|
|
|
|
for name, pattern in patterns.items():
|
2022-07-07 11:27:29 -07:00
|
|
|
lib[name] = lambda: pattern
|
2021-03-26 10:33:00 -07:00
|
|
|
return lib, library_info
|
|
|
|
|
|
|
|
# Normal approach (scan and defer load)
|
|
|
|
library_info = _read_header(stream)
|
|
|
|
structs = klamath.library.scan_structs(stream)
|
|
|
|
|
|
|
|
for name_bytes, pos in structs.items():
|
|
|
|
name = name_bytes.decode('ASCII')
|
|
|
|
|
2022-07-07 11:27:29 -07:00
|
|
|
def mkstruct(pos: int = pos) -> Pattern:
|
2021-03-26 10:33:00 -07:00
|
|
|
stream.seek(pos)
|
2022-07-07 11:27:29 -07:00
|
|
|
return read_elements(stream, raw_mode=True)
|
2021-03-26 10:33:00 -07:00
|
|
|
|
2022-07-07 11:27:29 -07:00
|
|
|
lib[name] = mkstruct
|
2021-03-26 10:33:00 -07:00
|
|
|
|
|
|
|
return lib, library_info
|
|
|
|
|
|
|
|
|
2022-02-23 11:27:11 -08:00
|
|
|
def load_libraryfile(
|
|
|
|
filename: Union[str, pathlib.Path],
|
|
|
|
*,
|
|
|
|
use_mmap: bool = True,
|
|
|
|
full_load: bool = False,
|
2023-01-13 20:33:14 -08:00
|
|
|
) -> Tuple[LazyLibrary, Dict[str, Any]]:
|
2021-03-26 10:33:00 -07:00
|
|
|
"""
|
|
|
|
Wrapper for `load_library()` that takes a filename or path instead of a stream.
|
|
|
|
|
|
|
|
Will automatically decompress the file if it is gzipped.
|
|
|
|
|
|
|
|
NOTE that any streams/mmaps opened will remain open until ALL of the
|
|
|
|
`PatternGenerator` objects in the library are garbage collected.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
path: filename or path to read from
|
|
|
|
use_mmap: If `True`, will attempt to memory-map the file instead
|
|
|
|
of buffering. In the case of gzipped files, the file
|
|
|
|
is decompressed into a python `bytes` object in memory
|
|
|
|
and reopened as an `io.BytesIO` stream.
|
|
|
|
full_load: If `True`, immediately loads all data. See `load_library`.
|
|
|
|
|
|
|
|
Returns:
|
2023-01-13 20:33:14 -08:00
|
|
|
LazyLibrary object, allowing for deferred load of structures.
|
2021-03-26 10:33:00 -07:00
|
|
|
Additional library info (dict, same format as from `read`).
|
|
|
|
"""
|
|
|
|
path = pathlib.Path(filename)
|
|
|
|
if is_gzipped(path):
|
|
|
|
if mmap:
|
|
|
|
logger.info('Asked to mmap a gzipped file, reading into memory instead...')
|
|
|
|
base_stream = gzip.open(path, mode='rb')
|
|
|
|
stream = io.BytesIO(base_stream.read())
|
|
|
|
else:
|
|
|
|
base_stream = gzip.open(path, mode='rb')
|
|
|
|
stream = io.BufferedReader(base_stream)
|
|
|
|
else:
|
|
|
|
base_stream = open(path, mode='rb')
|
|
|
|
if mmap:
|
|
|
|
stream = mmap.mmap(base_stream.fileno(), 0, access=mmap.ACCESS_READ)
|
|
|
|
else:
|
|
|
|
stream = io.BufferedReader(base_stream)
|
2022-07-07 11:27:29 -07:00
|
|
|
return load_library(stream, full_load=full_load)
|