fix more type issues

This commit is contained in:
Jan Petykiewicz 2023-01-22 22:16:09 -08:00
parent 6565b8baa3
commit 8484628f2f
11 changed files with 54 additions and 34 deletions

View File

@ -127,7 +127,7 @@ def readfile(
filename: Union[str, pathlib.Path], filename: Union[str, pathlib.Path],
*args, *args,
**kwargs, **kwargs,
) -> Tuple[Pattern, Dict[str, Any]]: ) -> Tuple[Dict[str, Pattern], Dict[str, Any]]:
""" """
Wrapper for `dxf.read()` that takes a filename or path instead of a stream. Wrapper for `dxf.read()` that takes a filename or path instead of a stream.

View File

@ -19,7 +19,7 @@ Notes:
* Creation/modification/access times are set to 1900-01-01 for reproducibility. * Creation/modification/access times are set to 1900-01-01 for reproducibility.
""" """
from typing import List, Any, Dict, Tuple, Callable, Union, Iterable, Optional from typing import List, Any, Dict, Tuple, Callable, Union, Iterable, Optional
from typing import Sequence, BinaryIO, Mapping from typing import Sequence, BinaryIO, Mapping, cast
import re import re
import io import io
import mmap import mmap
@ -298,7 +298,7 @@ def _gref_to_mref(ref: klamath.library.Reference) -> Ref:
repetition = Grid(a_vector=a_vector, b_vector=b_vector, repetition = Grid(a_vector=a_vector, b_vector=b_vector,
a_count=a_count, b_count=b_count) a_count=a_count, b_count=b_count)
ref = Ref( mref = Ref(
target=ref.struct_name.decode('ASCII'), target=ref.struct_name.decode('ASCII'),
offset=offset, offset=offset,
rotation=numpy.deg2rad(ref.angle_deg), rotation=numpy.deg2rad(ref.angle_deg),
@ -307,7 +307,7 @@ def _gref_to_mref(ref: klamath.library.Reference) -> Ref:
annotations=_properties_to_annotations(ref.properties), annotations=_properties_to_annotations(ref.properties),
repetition=repetition, repetition=repetition,
) )
return ref return mref
def _gpath_to_mpath(gpath: klamath.library.Path, raw_mode: bool) -> Path: def _gpath_to_mpath(gpath: klamath.library.Path, raw_mode: bool) -> Path:
@ -341,7 +341,7 @@ def _boundary_to_polygon(boundary: klamath.library.Boundary, raw_mode: bool) ->
def _mrefs_to_grefs(refs: List[Ref]) -> List[klamath.library.Reference]: def _mrefs_to_grefs(refs: List[Ref]) -> List[klamath.library.Reference]:
refs = [] grefs = []
for ref in refs: for ref in refs:
if ref.target is None: if ref.target is None:
continue continue
@ -370,9 +370,9 @@ def _mrefs_to_grefs(refs: List[Ref]) -> List[klamath.library.Reference]:
mag=ref.scale, mag=ref.scale,
properties=properties, properties=properties,
) )
refs.append(aref) grefs.append(aref)
elif rep is None: elif rep is None:
ref = klamath.library.Reference( sref = klamath.library.Reference(
struct_name=encoded_name, struct_name=encoded_name,
xy=rint_cast([ref.offset]), xy=rint_cast([ref.offset]),
colrow=None, colrow=None,
@ -381,7 +381,7 @@ def _mrefs_to_grefs(refs: List[Ref]) -> List[klamath.library.Reference]:
mag=ref.scale, mag=ref.scale,
properties=properties, properties=properties,
) )
refs.append(ref) grefs.append(sref)
else: else:
new_srefs = [ new_srefs = [
klamath.library.Reference( klamath.library.Reference(
@ -394,8 +394,8 @@ def _mrefs_to_grefs(refs: List[Ref]) -> List[klamath.library.Reference]:
properties=properties, properties=properties,
) )
for dd in rep.displacements] for dd in rep.displacements]
refs += new_srefs grefs += new_srefs
return refs return grefs
def _properties_to_annotations(properties: Dict[int, bytes]) -> annotations_t: def _properties_to_annotations(properties: Dict[int, bytes]) -> annotations_t:
@ -635,17 +635,17 @@ def load_libraryfile(
if is_gzipped(path): if is_gzipped(path):
if mmap: if mmap:
logger.info('Asked to mmap a gzipped file, reading into memory instead...') logger.info('Asked to mmap a gzipped file, reading into memory instead...')
base_stream = gzip.open(path, mode='rb') gz_stream = gzip.open(path, mode='rb')
stream = io.BytesIO(base_stream.read()) stream = io.BytesIO(gz_stream.read()) # type: ignore
else: else:
base_stream = gzip.open(path, mode='rb') gz_stream = gzip.open(path, mode='rb')
stream = io.BufferedReader(base_stream) stream = io.BufferedReader(gz_stream) # type: ignore
else: else:
base_stream = open(path, mode='rb')
if mmap: if mmap:
stream = mmap.mmap(base_stream.fileno(), 0, access=mmap.ACCESS_READ) base_stream = open(path, mode='rb', buffering=0)
stream = mmap.mmap(base_stream.fileno(), 0, access=mmap.ACCESS_READ) # type: ignore
else: else:
stream = io.BufferedReader(base_stream) stream = open(path, mode='rb')
return load_library(stream, full_load=full_load) return load_library(stream, full_load=full_load)

View File

@ -481,8 +481,10 @@ def _placement_to_ref(placement: fatrec.Placement, lib: fatamorgana.OasisLayout)
assert(not isinstance(placement.repetition, fatamorgana.ReuseRepetition)) assert(not isinstance(placement.repetition, fatamorgana.ReuseRepetition))
xy = numpy.array((placement.x, placement.y)) xy = numpy.array((placement.x, placement.y))
mag = placement.magnification if placement.magnification is not None else 1 mag = placement.magnification if placement.magnification is not None else 1
pname = placement.get_name() pname = placement.get_name()
name = pname if isinstance(pname, int) else pname.string name: Union[int, str] = pname if isinstance(pname, int) else pname.string # TODO deal with referenced names
annotations = properties_to_annotations(placement.properties, lib.propnames, lib.propstrings) annotations = properties_to_annotations(placement.properties, lib.propnames, lib.propstrings)
if placement.angle is None: if placement.angle is None:
rotation = 0 rotation = 0
@ -503,7 +505,7 @@ def _placement_to_ref(placement: fatrec.Placement, lib: fatamorgana.OasisLayout)
def _refs_to_placements( def _refs_to_placements(
refs: List[Ref], refs: List[Ref],
) -> List[fatrec.Placement]: ) -> List[fatrec.Placement]:
refs = [] placements = []
for ref in refs: for ref in refs:
if ref.target is None: if ref.target is None:
continue continue
@ -514,7 +516,7 @@ def _refs_to_placements(
offset = rint_cast(ref.offset + rep_offset) offset = rint_cast(ref.offset + rep_offset)
angle = numpy.rad2deg(ref.rotation + extra_angle) % 360 angle = numpy.rad2deg(ref.rotation + extra_angle) % 360
ref = fatrec.Placement( placement = fatrec.Placement(
name=ref.target, name=ref.target,
flip=mirror_across_x, flip=mirror_across_x,
angle=angle, angle=angle,
@ -525,8 +527,8 @@ def _refs_to_placements(
repetition=frep, repetition=frep,
) )
refs.append(ref) placements.append(placement)
return refs return placements
def _shapes_to_elements( def _shapes_to_elements(

View File

@ -1,4 +1,4 @@
from typing import List, Tuple, Dict, Optional, Sequence, Any from typing import List, Tuple, Dict, Optional, Sequence, Any, cast
import copy import copy
from enum import Enum from enum import Enum
@ -365,7 +365,7 @@ class Path(Shape, metaclass=AutoSlots):
x_min = rotated_vertices[:, 0].argmin() x_min = rotated_vertices[:, 0].argmin()
if not is_scalar(x_min): if not is_scalar(x_min):
y_min = rotated_vertices[x_min, 1].argmin() y_min = rotated_vertices[x_min, 1].argmin()
x_min = x_min[y_min] x_min = cast(Sequence, x_min)[y_min]
reordered_vertices = numpy.roll(rotated_vertices, -x_min, axis=0) reordered_vertices = numpy.roll(rotated_vertices, -x_min, axis=0)
width0 = self.width / norm_value width0 = self.width / norm_value

View File

@ -1,4 +1,4 @@
from typing import List, Dict, Optional, Sequence, Any from typing import List, Dict, Optional, Sequence, Any, cast
import copy import copy
import numpy import numpy
@ -374,7 +374,7 @@ class Polygon(Shape, metaclass=AutoSlots):
x_min = rotated_vertices[:, 0].argmin() x_min = rotated_vertices[:, 0].argmin()
if not is_scalar(x_min): if not is_scalar(x_min):
y_min = rotated_vertices[x_min, 1].argmin() y_min = rotated_vertices[x_min, 1].argmin()
x_min = x_min[y_min] x_min = cast(Sequence, x_min)[y_min]
reordered_vertices = numpy.roll(rotated_vertices, -x_min, axis=0) reordered_vertices = numpy.roll(rotated_vertices, -x_min, axis=0)
# TODO: normalize mirroring? # TODO: normalize mirroring?

View File

@ -6,6 +6,9 @@ from ..utils import annotations_t
from ..error import MasqueError from ..error import MasqueError
_empty_slots = () # Workaround to get mypy to ignore intentionally empty slots for superclass
T = TypeVar('T', bound='Annotatable') T = TypeVar('T', bound='Annotatable')
I = TypeVar('I', bound='AnnotatableImpl') I = TypeVar('I', bound='AnnotatableImpl')
@ -33,7 +36,7 @@ class AnnotatableImpl(Annotatable, metaclass=ABCMeta):
""" """
Simple implementation of `Annotatable`. Simple implementation of `Annotatable`.
""" """
__slots__ = () __slots__ = _empty_slots
_annotations: annotations_t _annotations: annotations_t
""" Dictionary storing annotation name/value pairs """ """ Dictionary storing annotation name/value pairs """
@ -46,7 +49,7 @@ class AnnotatableImpl(Annotatable, metaclass=ABCMeta):
return self._annotations return self._annotations
@annotations.setter @annotations.setter
def annotations(self, annotations: annotations_t): def annotations(self, annotations: annotations_t) -> None:
if not isinstance(annotations, dict): if not isinstance(annotations, dict):
raise MasqueError(f'annotations expected dict, got {type(annotations)}') raise MasqueError(f'annotations expected dict, got {type(annotations)}')
self._annotations = annotations self._annotations = annotations

View File

@ -4,6 +4,9 @@ from abc import ABCMeta, abstractmethod
from ..utils import layer_t from ..utils import layer_t
_empty_slots = () # Workaround to get mypy to ignore intentionally empty slots for superclass
T = TypeVar('T', bound='Layerable') T = TypeVar('T', bound='Layerable')
I = TypeVar('I', bound='LayerableImpl') I = TypeVar('I', bound='LayerableImpl')
@ -50,7 +53,7 @@ class LayerableImpl(Layerable, metaclass=ABCMeta):
""" """
Simple implementation of Layerable Simple implementation of Layerable
""" """
__slots__ = () __slots__ = _empty_slots
_layer: layer_t _layer: layer_t
""" Layer number, pair, or name """ """ Layer number, pair, or name """

View File

@ -9,6 +9,9 @@ from numpy.typing import NDArray, ArrayLike
from ..error import MasqueError from ..error import MasqueError
_empty_slots = () # Workaround to get mypy to ignore intentionally empty slots for superclass
T = TypeVar('T', bound='Positionable') T = TypeVar('T', bound='Positionable')
I = TypeVar('I', bound='PositionableImpl') I = TypeVar('I', bound='PositionableImpl')
@ -85,7 +88,7 @@ class PositionableImpl(Positionable, metaclass=ABCMeta):
""" """
Simple implementation of Positionable Simple implementation of Positionable
""" """
__slots__ = () __slots__ = _empty_slots
_offset: NDArray[numpy.float64] _offset: NDArray[numpy.float64]
""" `[x_offset, y_offset]` """ """ `[x_offset, y_offset]` """
@ -108,7 +111,7 @@ class PositionableImpl(Positionable, metaclass=ABCMeta):
if val.size != 2: if val.size != 2:
raise MasqueError('Offset must be convertible to size-2 ndarray') raise MasqueError('Offset must be convertible to size-2 ndarray')
self._offset = val.flatten() self._offset = val.flatten() # type: ignore
''' '''
---- Methods ---- Methods

View File

@ -4,6 +4,9 @@ from abc import ABCMeta, abstractmethod
from ..error import MasqueError from ..error import MasqueError
_empty_slots = () # Workaround to get mypy to ignore intentionally empty slots for superclass
if TYPE_CHECKING: if TYPE_CHECKING:
from ..repetition import Repetition from ..repetition import Repetition
@ -55,7 +58,7 @@ class RepeatableImpl(Repeatable, metaclass=ABCMeta):
""" """
Simple implementation of `Repeatable` Simple implementation of `Repeatable`
""" """
__slots__ = () __slots__ = _empty_slots
_repetition: Optional['Repetition'] _repetition: Optional['Repetition']
""" Repetition object, or None (single instance only) """ """ Repetition object, or None (single instance only) """

View File

@ -10,6 +10,9 @@ from ..error import MasqueError
from ..utils import is_scalar, rotation_matrix_2d from ..utils import is_scalar, rotation_matrix_2d
_empty_slots = () # Workaround to get mypy to ignore intentionally empty slots for superclass
T = TypeVar('T', bound='Rotatable') T = TypeVar('T', bound='Rotatable')
I = TypeVar('I', bound='RotatableImpl') I = TypeVar('I', bound='RotatableImpl')
P = TypeVar('P', bound='Pivotable') P = TypeVar('P', bound='Pivotable')
@ -43,7 +46,7 @@ class RotatableImpl(Rotatable, metaclass=ABCMeta):
""" """
Simple implementation of `Rotatable` Simple implementation of `Rotatable`
""" """
__slots__ = () __slots__ = _empty_slots
_rotation: float _rotation: float
""" rotation for the object, radians counterclockwise """ """ rotation for the object, radians counterclockwise """

View File

@ -5,6 +5,9 @@ from ..error import MasqueError
from ..utils import is_scalar from ..utils import is_scalar
_empty_slots = () # Workaround to get mypy to ignore intentionally empty slots for superclass
T = TypeVar('T', bound='Scalable') T = TypeVar('T', bound='Scalable')
I = TypeVar('I', bound='ScalableImpl') I = TypeVar('I', bound='ScalableImpl')
@ -36,7 +39,7 @@ class ScalableImpl(Scalable, metaclass=ABCMeta):
""" """
Simple implementation of Scalable Simple implementation of Scalable
""" """
__slots__ = () __slots__ = _empty_slots
_scale: float _scale: float
""" scale factor for the entity """ """ scale factor for the entity """