Compare commits

..

3 Commits

Author SHA1 Message Date
da7118f521 misc cleanup 2024-07-29 03:13:36 -07:00
ef6c5df386 be more consistent about when copies are made 2024-07-29 03:13:23 -07:00
ad0adec8e8 numpy.array(..., copy=False) -> numpy.asarray(...)
For numpy 2.0
2024-07-29 02:37:48 -07:00
18 changed files with 42 additions and 47 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

@ -154,7 +154,7 @@ def poly2path(vertices: ArrayLike) -> str:
Returns: Returns:
SVG path-string. SVG path-string.
""" """
verts = numpy.array(vertices, copy=False) verts = numpy.asarray(vertices)
commands = 'M{:g},{:g} '.format(verts[0][0], verts[0][1]) # noqa: UP032 commands = 'M{:g},{:g} '.format(verts[0][0], verts[0][1]) # noqa: UP032
for vertex in verts[1:]: for vertex in verts[1:]:
commands += 'L{:g},{:g}'.format(vertex[0], vertex[1]) # noqa: UP032 commands += 'L{:g},{:g}'.format(vertex[0], vertex[1]) # noqa: UP032

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

@ -460,7 +460,7 @@ class ILibraryView(Mapping[str, 'Pattern'], metaclass=ABCMeta):
if transform is None or transform is True: if transform is None or transform is True:
transform = numpy.zeros(4) transform = numpy.zeros(4)
elif transform is not False: elif transform is not False:
transform = numpy.array(transform, dtype=float, copy=False) transform = numpy.asarray(transform, dtype=float)
original_pattern = pattern original_pattern = pattern

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')
@ -334,9 +332,9 @@ class Arbitrary(Repetition):
@displacements.setter @displacements.setter
def displacements(self, val: ArrayLike) -> None: def displacements(self, val: ArrayLike) -> None:
vala: NDArray[numpy.float64] = numpy.array(val, dtype=float) vala = numpy.array(val, dtype=float)
vala = numpy.sort(vala.view([('', vala.dtype)] * vala.shape[1]), 0).view(vala.dtype) # sort rows order = numpy.lexsort(vala.T[::-1]) # sortrows
self._displacements = vala self._displacements = vala[order]
def __init__( def __init__(
self, self,

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.array(..., copy=False)` 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.array(.., copy=False)`.
""" """
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.array(..., copy=False)` 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.array(.., copy=False)`.
""" """
return self._vertices return self._vertices

View File

@ -230,7 +230,8 @@ def get_char_as_polygons(
outline = slot.outline outline = slot.outline
start = 0 start = 0
all_verts_list, all_codes = [], [] all_verts_list = []
all_codes = []
for end in outline.contours: for end in outline.contours:
points = outline.points[start:end + 1] points = outline.points[start:end + 1]
points.append(points[0]) points.append(points[0])

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

@ -38,8 +38,8 @@ def maxrects_bssf(
Raises: Raises:
MasqueError if `allow_rejects` is `True` but some `rects` could not be placed. MasqueError if `allow_rejects` is `True` but some `rects` could not be placed.
""" """
regions = numpy.array(containers, copy=False, dtype=float) regions = numpy.asarray(containers, dtype=float)
rect_sizes = numpy.array(rects, copy=False, dtype=float) rect_sizes = numpy.asarray(rects, dtype=float)
rect_locs = numpy.zeros_like(rect_sizes) rect_locs = numpy.zeros_like(rect_sizes)
rejected_inds = set() rejected_inds = set()
@ -139,8 +139,8 @@ def guillotine_bssf_sas(
Raises: Raises:
MasqueError if `allow_rejects` is `True` but some `rects` could not be placed. MasqueError if `allow_rejects` is `True` but some `rects` could not be placed.
""" """
regions = numpy.array(containers, copy=False, dtype=float) regions = numpy.asarray(containers, dtype=float)
rect_sizes = numpy.array(rects, copy=False, dtype=float) rect_sizes = numpy.asarray(rects, dtype=float)
rect_locs = numpy.zeros_like(rect_sizes) rect_locs = numpy.zeros_like(rect_sizes)
rejected_inds = set() rejected_inds = set()
@ -227,7 +227,7 @@ def pack_patterns(
MasqueError if `allow_rejects` is `True` but some `rects` could not be placed. MasqueError if `allow_rejects` is `True` but some `rects` could not be placed.
""" """
half_spacing = numpy.array(spacing, copy=False, dtype=float) / 2 half_spacing = numpy.asarray(spacing, dtype=float) / 2
bounds = [library[pp].get_bounds() for pp in patterns] bounds = [library[pp].get_bounds() for pp in patterns]
sizes = [bb[1] - bb[0] + spacing if bb is not None else spacing for bb in bounds] sizes = [bb[1] - bb[0] + spacing if bb is not None else spacing for bb in bounds]

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)
@ -73,8 +73,8 @@ def poly_contains_points(
Returns: Returns:
ndarray of booleans, [point0_is_in_shape, point1_is_in_shape, ...] ndarray of booleans, [point0_is_in_shape, point1_is_in_shape, ...]
""" """
points = numpy.array(points, copy=False) points = numpy.asarray(points, dtype=float)
vertices = numpy.array(vertices, copy=False) vertices = numpy.asarray(vertices, dtype=float)
if points.size == 0: if points.size == 0:
return numpy.zeros(0, dtype=numpy.int8) return numpy.zeros(0, dtype=numpy.int8)