be more consistent about when copies are made

This commit is contained in:
Jan Petykiewicz 2024-07-29 03:13:23 -07:00
parent ad0adec8e8
commit ef6c5df386
14 changed files with 28 additions and 34 deletions

View File

@ -233,8 +233,8 @@ def ln_shift_defect(
# Shift holes # Shift holes
# Expand shifts as necessary # Expand shifts as necessary
tmp_a = numpy.array(shifts_a) tmp_a = numpy.asarray(shifts_a)
tmp_r = numpy.array(shifts_r) tmp_r = numpy.asarray(shifts_r)
n_shifted = max(tmp_a.size, tmp_r.size) n_shifted = max(tmp_a.size, tmp_r.size)
shifts_a = numpy.ones(n_shifted) shifts_a = numpy.ones(n_shifted)

View File

@ -97,7 +97,7 @@ class Abstract(PortList):
Returns: Returns:
self self
""" """
pivot = numpy.array(pivot) pivot = numpy.asarray(pivot, dtype=float)
self.translate_ports(-pivot) self.translate_ports(-pivot)
self.rotate_ports(rotation) self.rotate_ports(rotation)
self.rotate_port_offsets(rotation) self.rotate_port_offsets(rotation)

View File

@ -212,9 +212,9 @@ def _read_block(block: ezdxf.layouts.BlockLayout | ezdxf.layouts.Modelspace) ->
for element in block: for element in block:
if isinstance(element, LWPolyline | Polyline): if isinstance(element, LWPolyline | Polyline):
if isinstance(element, LWPolyline): if isinstance(element, LWPolyline):
points = numpy.array(element.get_points()) points = numpy.asarray(element.get_points())
elif isinstance(element, Polyline): elif isinstance(element, Polyline):
points = numpy.array(element.points())[:, :2] points = numpy.asarray(element.points())[:, :2]
attr = element.dxfattribs() attr = element.dxfattribs()
layer = attr.get('layer', DEFAULT_LAYER) layer = attr.get('layer', DEFAULT_LAYER)
@ -241,7 +241,7 @@ def _read_block(block: ezdxf.layouts.BlockLayout | ezdxf.layouts.Modelspace) ->
elif isinstance(element, Text): elif isinstance(element, Text):
args = dict( args = dict(
offset=numpy.array(element.get_placement()[1])[:2], offset=numpy.asarray(element.get_placement()[1])[:2],
layer=element.dxfattribs().get('layer', DEFAULT_LAYER), layer=element.dxfattribs().get('layer', DEFAULT_LAYER),
) )
string = element.dxfattribs().get('text', '') string = element.dxfattribs().get('text', '')
@ -262,7 +262,7 @@ def _read_block(block: ezdxf.layouts.BlockLayout | ezdxf.layouts.Modelspace) ->
mirrored, extra_angle = normalize_mirror((yscale < 0, xscale < 0)) mirrored, extra_angle = normalize_mirror((yscale < 0, xscale < 0))
rotation = numpy.deg2rad(attr.get('rotation', 0)) + extra_angle rotation = numpy.deg2rad(attr.get('rotation', 0)) + extra_angle
offset = numpy.array(attr.get('insert', (0, 0, 0)))[:2] offset = numpy.asarray(attr.get('insert', (0, 0, 0)))[:2]
args = dict( args = dict(
target=attr.get('name', None), target=attr.get('name', None),

View File

@ -357,7 +357,7 @@ def _mrefs_to_grefs(refs: dict[str | None, list[Ref]]) -> list[klamath.library.R
if isinstance(rep, Grid): if isinstance(rep, Grid):
b_vector = rep.b_vector if rep.b_vector is not None else numpy.zeros(2) 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 b_count = rep.b_count if rep.b_count is not None else 1
xy = numpy.array(ref.offset) + numpy.array([ xy = numpy.asarray(ref.offset) + numpy.array([
[0.0, 0.0], [0.0, 0.0],
rep.a_vector * rep.a_count, rep.a_vector * rep.a_count,
b_vector * b_count, b_vector * b_count,

View File

@ -49,7 +49,7 @@ class Label(PositionableImpl, RepeatableImpl, AnnotatableImpl, Bounded, Pivotabl
annotations: annotations_t | None = None, annotations: annotations_t | None = None,
) -> None: ) -> None:
self.string = string self.string = string
self.offset = numpy.array(offset, dtype=float, copy=True) self.offset = numpy.array(offset, dtype=float)
self.repetition = repetition self.repetition = repetition
self.annotations = annotations if annotations is not None else {} self.annotations = annotations if annotations is not None else {}
@ -94,7 +94,7 @@ class Label(PositionableImpl, RepeatableImpl, AnnotatableImpl, Bounded, Pivotabl
Returns: Returns:
self self
""" """
pivot = numpy.array(pivot, dtype=float) pivot = numpy.asarray(pivot, dtype=float)
self.translate(-pivot) self.translate(-pivot)
self.offset = numpy.dot(rotation_matrix_2d(rotation), self.offset) self.offset = numpy.dot(rotation_matrix_2d(rotation), self.offset)
self.translate(+pivot) self.translate(+pivot)

View File

@ -690,7 +690,7 @@ class Pattern(PortList, AnnotatableImpl, Mirrorable):
Returns: Returns:
self self
""" """
pivot = numpy.array(pivot) pivot = numpy.asarray(pivot, dtype=float)
self.translate_elements(-pivot) self.translate_elements(-pivot)
self.rotate_elements(rotation) self.rotate_elements(rotation)
self.rotate_element_centers(rotation) self.rotate_element_centers(rotation)
@ -1023,7 +1023,7 @@ class Pattern(PortList, AnnotatableImpl, Mirrorable):
if self.has_refs() and library is None: if self.has_refs() and library is None:
raise PatternError('Must provide a library when visualizing a pattern with refs') raise PatternError('Must provide a library when visualizing a pattern with refs')
offset = numpy.array(offset, dtype=float) offset = numpy.asarray(offset, dtype=float)
if not overdraw: if not overdraw:
figure = pyplot.figure() figure = pyplot.figure()

View File

@ -156,12 +156,11 @@ class Grid(Repetition):
@a_vector.setter @a_vector.setter
def a_vector(self, val: ArrayLike) -> None: def a_vector(self, val: ArrayLike) -> None:
if not isinstance(val, numpy.ndarray): val = numpy.array(val, dtype=float)
val = numpy.array(val, dtype=float)
if val.size != 2: if val.size != 2:
raise PatternError('a_vector must be convertible to size-2 ndarray') raise PatternError('a_vector must be convertible to size-2 ndarray')
self._a_vector = val.flatten().astype(float) self._a_vector = val.flatten()
# b_vector property # b_vector property
@property @property
@ -170,8 +169,7 @@ class Grid(Repetition):
@b_vector.setter @b_vector.setter
def b_vector(self, val: ArrayLike) -> None: def b_vector(self, val: ArrayLike) -> None:
if not isinstance(val, numpy.ndarray): val = numpy.array(val, dtype=float)
val = numpy.array(val, dtype=float, copy=True)
if val.size != 2: if val.size != 2:
raise PatternError('b_vector must be convertible to size-2 ndarray') raise PatternError('b_vector must be convertible to size-2 ndarray')

View File

@ -472,7 +472,7 @@ class Arc(Shape):
a1 += sign * 2 * pi a1 += sign * 2 * pi
a.append((a0, a1)) a.append((a0, a1))
return numpy.array(a) return numpy.array(a, dtype=float)
def __repr__(self) -> str: def __repr__(self) -> str:
angles = f'{numpy.rad2deg(self.angles)}' angles = f'{numpy.rad2deg(self.angles)}'

View File

@ -33,8 +33,7 @@ class Path(Shape):
A path, consisting of a bunch of vertices (Nx2 ndarray), a width, an end-cap shape, A path, consisting of a bunch of vertices (Nx2 ndarray), a width, an end-cap shape,
and an offset. and an offset.
Note that the setter for `Path.vertices` may (but may not) create a copy of the Note that the setter for `Path.vertices` will create a copy of the passed vertex coordinates.
passed vertex coordinates. See `numpy.asarray()` for details.
A normalized_form(...) is available, but can be quite slow with lots of vertices. A normalized_form(...) is available, but can be quite slow with lots of vertices.
""" """
@ -118,8 +117,7 @@ class Path(Shape):
""" """
Vertices of the path (Nx2 ndarray: `[[x0, y0], [x1, y1], ...]` Vertices of the path (Nx2 ndarray: `[[x0, y0], [x1, y1], ...]`
When setting, note that a copy of the provided vertices may or may not be made, When setting, note that a copy of the provided vertices will be made.
following the rules from `numpy.asarray()`.
""" """
return self._vertices return self._vertices

View File

@ -20,8 +20,8 @@ class Polygon(Shape):
A polygon, consisting of a bunch of vertices (Nx2 ndarray) which specify an A polygon, consisting of a bunch of vertices (Nx2 ndarray) which specify an
implicitly-closed boundary, and an offset. implicitly-closed boundary, and an offset.
Note that the setter for `Polygon.vertices` may (but may not) create a copy of the Note that the setter for `Polygon.vertices` may creates a copy of the
passed vertex coordinates. See `numpy.asarray() for details. passed vertex coordinates.
A `normalized_form(...)` is available, but can be quite slow with lots of vertices. A `normalized_form(...)` is available, but can be quite slow with lots of vertices.
""" """
@ -40,8 +40,7 @@ class Polygon(Shape):
""" """
Vertices of the polygon (Nx2 ndarray: `[[x0, y0], [x1, y1], ...]`) Vertices of the polygon (Nx2 ndarray: `[[x0, y0], [x1, y1], ...]`)
When setting, note that a copy of the provided vertices may or may not be made, When setting, note that a copy of the provided vertices will be made,
following the rules from `numpy.asarray()`.
""" """
return self._vertices return self._vertices

View File

@ -60,7 +60,7 @@ class Mirrorable(metaclass=ABCMeta):
# def mirrored(self, val: Sequence[bool]) -> None: # def mirrored(self, val: Sequence[bool]) -> None:
# if is_scalar(val): # if is_scalar(val):
# raise MasqueError('Mirrored must be a 2-element list of booleans') # raise MasqueError('Mirrored must be a 2-element list of booleans')
# self._mirrored = numpy.array(val, dtype=bool, copy=True) # self._mirrored = numpy.array(val, dtype=bool)
# #
# # # #
# # Methods # # Methods

View File

@ -81,12 +81,11 @@ class PositionableImpl(Positionable, metaclass=ABCMeta):
@offset.setter @offset.setter
def offset(self, val: ArrayLike) -> None: def offset(self, val: ArrayLike) -> None:
if not isinstance(val, numpy.ndarray) or val.dtype != numpy.float64: val = numpy.array(val, dtype=float)
val = numpy.array(val, dtype=float)
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() # type: ignore self._offset = val.flatten()
# #
# Methods # Methods

View File

@ -112,7 +112,7 @@ class PivotableImpl(Pivotable, metaclass=ABCMeta):
""" `[x_offset, y_offset]` """ """ `[x_offset, y_offset]` """
def rotate_around(self, pivot: ArrayLike, rotation: float) -> Self: def rotate_around(self, pivot: ArrayLike, rotation: float) -> Self:
pivot = numpy.array(pivot, dtype=float) pivot = numpy.asarray(pivot, dtype=float)
cast(Positionable, self).translate(-pivot) cast(Positionable, self).translate(-pivot)
cast(Rotatable, self).rotate(rotation) cast(Rotatable, self).rotate(rotation)
self.offset = numpy.dot(rotation_matrix_2d(rotation), self.offset) # type: ignore # mypy#3004 self.offset = numpy.dot(rotation_matrix_2d(rotation), self.offset) # type: ignore # mypy#3004

View File

@ -15,9 +15,9 @@ def remove_duplicate_vertices(vertices: ArrayLike, closed_path: bool = True) ->
(i.e. the last vertex will be removed if it is the same as the first) (i.e. the last vertex will be removed if it is the same as the first)
Returns: Returns:
`vertices` with no consecutive duplicates. `vertices` with no consecutive duplicates. This may be a view into the original array.
""" """
vertices = numpy.array(vertices) vertices = numpy.asarray(vertices)
duplicates = (vertices == numpy.roll(vertices, 1, axis=0)).all(axis=1) duplicates = (vertices == numpy.roll(vertices, 1, axis=0)).all(axis=1)
if not closed_path: if not closed_path:
duplicates[0] = False duplicates[0] = False
@ -35,7 +35,7 @@ def remove_colinear_vertices(vertices: ArrayLike, closed_path: bool = True) -> N
closed path. If `False`, the path is assumed to be open. Default `True`. closed path. If `False`, the path is assumed to be open. Default `True`.
Returns: Returns:
`vertices` with colinear (superflous) vertices removed. `vertices` with colinear (superflous) vertices removed. May be a view into the original array.
""" """
vertices = remove_duplicate_vertices(vertices) vertices = remove_duplicate_vertices(vertices)