-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathgeometry.py
2915 lines (2400 loc) · 111 KB
/
geometry.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Classes describing geometry in sectionproperties."""
from __future__ import annotations
import copy
import math
import pathlib
from typing import TYPE_CHECKING, Any, cast
import more_itertools
import numpy as np
import numpy.typing as npt
from shapely import (
GeometryCollection,
LinearRing,
LineString,
MultiLineString,
MultiPolygon,
Point,
Polygon,
affinity,
box, # pyright: ignore [reportUnknownVariableType]
line_merge, # pyright: ignore [reportUnknownVariableType]
shared_paths, # pyright: ignore [reportUnknownVariableType]
)
from shapely.ops import split, unary_union
import sectionproperties.post.post as post
import sectionproperties.pre.bisect_section as bisect
import sectionproperties.pre.pre as pre
if TYPE_CHECKING:
import matplotlib.axes
SCALE_CONSTANT = 1e-9
class Geometry:
"""Class for defining the geometry of a contiguous section of a single material.
Provides an interface for the user to specify the geometry defining a section. A
method is provided for generating a triangular mesh, transforming the section (e.g.
translation, rotation, perimeter offset, mirroring), aligning the geometry to
another geometry, and designating stress recovery points.
"""
def __init__(
self,
geom: Polygon,
material: pre.Material | None = pre.DEFAULT_MATERIAL,
control_points: Point | tuple[float, float] | None = None,
tol: int = 12,
) -> None:
"""Inits the Geometry class.
Args:
geom: A Shapely Polygon object that defines the geometry
material: A material to associate with this geometry. Defaults to
``pre.DEFAULT_MATERIAL``.
control_points: An ``(x, y)`` coordinate within the geometry that represents
a pre-assigned control point (aka, a region identification point) to be
used instead of the automatically assigned control point generated with
:meth:`shapely.Polygon.representative_point`. Defaults to ``None``.
tol: Number of decimal places to round the geometry vertices to. A lower
value may reduce accuracy of geometry but increases precision when
aligning geometries to each other. Defaults to ``12``.
Raises:
ValueError: If ``geom`` is not valid, i.e. not a shapely object, or a
MultiPolygon object
"""
if isinstance(geom, MultiPolygon):
msg = "Use CompoundGeometry(...) for a MultiPolygon object."
raise ValueError(msg)
if not isinstance(geom, Polygon): # pyright: ignore [reportUnnecessaryIsInstance]
msg = f"Argument is not a valid shapely.Polygon object: {geom!r}"
raise ValueError(msg)
self.assigned_control_point = None
if control_points is not None and (
isinstance(control_points, Point) or len(control_points) == 2
):
self.assigned_control_point = Point(control_points)
self.tol = tol # num of decimal places of precision for point locations
self.geom = round_polygon_vertices(geom, self.tol)
self.material = pre.DEFAULT_MATERIAL if material is None else material
self.control_points: list[tuple[float, float]] = []
self.points: list[tuple[float, float]] = []
self.facets: list[tuple[int, int]] = []
self.holes: list[tuple[float, float]] = []
self._recovery_points: list[tuple[float, float]] | list[Point] = []
self.mesh: dict[str, Any] | None = None
self.compile_geometry()
def _repr_svg_(self) -> str:
"""Generates an svg of the geometry.
Returns:
Representative svg
"""
print("sectionproperties.pre.geometry.Geometry")
print(f"object at: {hex(id(self))}")
print(f"Material: {self.material.name}")
return str(self.geom._repr_svg_())
def assign_control_point(
self,
control_point: tuple[float, float],
) -> Geometry:
"""Assigns a control point to the geometry.
Returns a new Geometry object with ``control_point`` assigned as the control
point for the new Geometry. The assignment of a control point is intended to
replace the control point automatically generated by
:meth:`shapely.Polygon.representative_point()`.
An assigned control point is carried through and transformed with the Geometry
whenever it is shifted, aligned, mirrored, unioned, and/or rotated. If a
perimeter_offset operation is applied, a check is performed to see if the
assigned control point is still valid (within the new region) and, if so, it is
kept. If not, a new control point is auto-generated.
The same check is performed when the geometry undergoes a difference operation
(with the ``-`` operator) or a shift_points operation. If the assigned control
point is valid, it is kept. If not, a new one is auto-generated.
For all other operations (e.g. symmetric difference, intersection, split), the
assigned control point is discarded and a new one auto-generated.
Args:
control_point: An (``x``, ``y``) coordinate that describes the distinct,
contiguous, region of a single material within the geometry.
Returns:
New Geometry object with ``control_point`` assigned as the control point
"""
return Geometry(
geom=self.geom,
material=self.material,
control_points=control_point,
tol=self.tol,
)
@staticmethod
def from_points(
points: list[tuple[float, float]],
facets: list[tuple[int, int]],
control_points: list[tuple[float, float]],
holes: list[tuple[float, float]] | None = None,
material: pre.Material = pre.DEFAULT_MATERIAL,
) -> Geometry:
"""Creates Geometry from points, facets, a control point and holes.
Args:
points: List of points (``x``, ``y``) defining the vertices of the section
geometry. If the geometry simply contains a continuous list of exterior
points, consider creating a :class:`shapely.Polygon` object (only
requiring points), and create a ``Geometry`` object using the
constructor.
facets: A list of (``start``, ``end``) indices of vertices defining the
edges of the section geoemtry. Can be used to define both external and
internal perimeters of holes. Facets are assumed to be described in the
order of exterior perimeter, interior perimeter 1, interior perimeter 2,
etc.
control_points: An (``x``, ``y``) coordinate that describes the distinct,
contiguous, region of a single material within the geometry. Must be
entered as a list of coordinates, e.g. [(0.5, 3.2)]. Exactly one point
is required for each geometry with a distinct material. If there are
multiple distinct regions, then use
:meth:`sectionproperties.pre.geometry.CompoundGeometry.from_points()`
holes: A list of points (``x``, ``y``) that define interior regions as
being holes or voids. The point can be located anywhere within the hole
region. Only one point is required per hole region. Defaults to
``None``.
material: A :class:`~sectionproperties.pre.pre.Material` object that is to
be assigned. Defaults to ``pre.DEFAULT_MATERIAL``.
Raises:
ValueError: If there is not exactly one control point specified
RuntimeError: If geometry generation failed
Returns:
Geometry object
Example:
.. plot::
:include-source: True
:caption: Geometry created from points, facets and holes.
from sectionproperties.pre import Geometry
points = [(0, 0), (10, 5), (15, 15), (5, 10), (6, 6), (9, 7), (7, 9)]
facets = [(0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 4)]
control_points = [(4, 4)]
holes = [(7, 7)]
Geometry.from_points(
points=points,
facets=facets,
control_points=control_points,
holes=holes,
).plot_geometry()
"""
if len(control_points) != 1:
msg = "Control points for Geometry instances must have exactly "
msg += "one x, y coordinate and entered as a list of 2D float tuples, "
msg += "e.g. [(0.1, 3.4)]. CompoundGeometry.from_points() can accept "
msg += "multiple control points\n"
msg += f"Control points received: {control_points}"
raise ValueError(msg)
if holes is None:
holes = []
prev_facet: tuple[int, int] | None = None
# Initialize the total number of accumulators needed
# Always an exterior, plus, a separate accumulator for each interior region
exterior: list[tuple[float, float]] = []
interiors: list[list[tuple[float, float]]] = [[] for _ in holes]
interior_counter = 0 # To keep track of interior regions
active_list = exterior # The active_list is the list being accumulated on
for facet in facets: # Loop through facets for graph connectivity
i_idx, _ = facet
if not prev_facet: # Add the first facet vertex to exterior and move on
vertex = points[i_idx]
active_list.append(vertex)
prev_facet = facet
continue
# Look at the last j_idx to test for a break in the chain of edges
prev_j_idx = prev_facet[1]
# If there is a break in the chain of edges...
if i_idx != prev_j_idx and holes:
# ...and we are still accumulating on the exterior...
if active_list == exterior:
active_list = interiors[interior_counter]
# ... then move to the interior accumulator
# ...or if we are already in the interior accumulator...
else:
# ...then start the next interior accumulator for a new hole.
interior_counter += 1
active_list = interiors[interior_counter]
active_list.append(points[i_idx])
else:
# Only need i_idx b/c shapely auto-closes polygons
active_list.append(points[i_idx])
prev_facet = facet
exterior_geometry = Polygon(exterior)
interior_polys = [Polygon(interior) for interior in interiors]
interior_geometry = MultiPolygon(interior_polys)
sub_poly = exterior_geometry - interior_geometry
if isinstance(sub_poly, Polygon):
return Geometry(
geom=sub_poly, material=material, control_points=control_points[0]
)
else:
msg = "Geometry generation failed."
raise RuntimeError(msg)
@staticmethod
def from_dxf(
dxf_filepath: str | pathlib.Path,
spline_delta: float = 0.1,
degrees_per_segment: float = 1.0,
) -> Geometry | CompoundGeometry:
"""An interface for the creation of Geometry objects from CAD .dxf files.
Args:
dxf_filepath: A path-like object for the dxf file
spline_delta: Splines are not supported in ``shapely``, so they are
approximated as polylines, this argument affects the spline sampling
rate. Defaults to ``0.1``.
degrees_per_segment: The number of degrees discretised as a single line
segment. Defaults to ``1.0``.
Returns:
Geometry or CompoundGeometry object
"""
return load_dxf(
dxf_filepath=dxf_filepath,
spline_delta=spline_delta,
degrees_per_segment=degrees_per_segment,
)
@classmethod
def from_3dm(
cls,
filepath: str | pathlib.Path,
**kwargs: Any,
) -> Geometry:
"""Creates a Geometry object from a Rhino ``.3dm`` file.
Args:
filepath: File path to the rhino ``.3dm`` file.
kwargs: See below.
Keyword Args:
refine_num (Optional[int]): Bézier curve interpolation number. In Rhino a
surface's edges are nurb based curves. Shapely does not support nurbs,
so the individual Bézier curves are interpolated using straight lines.
This parameter sets the number of straight lines used in the
interpolation. Default is 1.
vec1 (Optional[numpy.ndarray]): A 3d vector in the Shapely plane. Rhino is a
3D geometry environment. Shapely is a 2D geometric library. Thus a 2D
plane needs to be defined in Rhino that represents the Shapely
coordinate system. ``vec1`` represents the 1st vector of this plane. It
will be used as Shapely's x direction. Default is [1,0,0].
vec2 (Optional[numpy.ndarray]): Continuing from ``vec1``, ``vec2`` is
another vector to define the Shapely plane. It must not be [0,0,0] and
it's only requirement is that it is any vector in the Shapely plane (but
not equal to ``vec1``). Default is [0,1,0].
plane_distance (Optional[float]): The distance to the Shapely plane. Default
is 0.
project (Optional[bool]): Controls if the breps are projected onto the plane
in the direction of the Shapley plane's normal. Default is True.
parallel (Optional[bool]): Controls if only the rhino surfaces that have the
same normal as the Shapely plane are yielded. If true, all non parallel
surfaces are filtered out. Default is False.
Raises:
RuntimeError: A RuntimeError is raised if two or more polygons are found.
This is dependent on the keyword arguments. Try adjusting the keyword
arguments if this error is raised.
ImportError: If ``rhino3dm`` is not installed. To enable rhino features use
``pip install sectionproperties[rhino]``.
Returns:
A Geometry object.
"""
try:
import sectionproperties.pre.rhino as rhino_importer
except ImportError as e:
print(e)
msg = "There is something wrong with your rhino library installation. "
msg += "Please report this error at "
msg += "https://github.com/robbievanleeuwen/section-properties/issues"
raise ImportError(msg) from e
geom = None
list_poly = rhino_importer.load_3dm(filepath, **kwargs)
if len(list_poly) == 1:
geom = cls(geom=list_poly[0])
else:
msg = "Multiple surfaces extracted from the file. Either use "
msg += "CompoundGeometry or extract individual surfaces manually via "
msg += "pre.rhino."
raise RuntimeError(msg)
return geom
@classmethod
def from_rhino_encoding(
cls,
r3dm_brep: str,
**kwargs: Any,
) -> Geometry:
"""Load an encoded single surface planer brep.
Args:
r3dm_brep: A Rhino3dm.Brep encoded as a string.
kwargs: See below.
Keyword Args:
refine_num (Optional[int]): Bézier curve interpolation number. In Rhino a
surface's edges are nurb based curves. Shapely does not support nurbs,
so the individual Bézier curves are interpolated using straight lines.
This parameter sets the number of straight lines used in the
interpolation. Default is 1.
vec1 (Optional[numpy.ndarray]): A 3d vector in the Shapely plane. Rhino is a
3D geometry environment. Shapely is a 2D geometric library. Thus a 2D
plane needs to be defined in Rhino that represents the Shapely
coordinate system. ``vec1`` represents the 1st vector of this plane. It
will be used as Shapely's x direction. Default is [1,0,0].
vec2 (Optional[numpy.ndarray]): Continuing from ``vec1``, ``vec2`` is
another vector to define the Shapely plane. It must not be [0,0,0] and
it's only requirement is that it is any vector in the Shapely plane (but
not equal to ``vec1``). Default is [0,1,0].
plane_distance (Optional[float]): The distance to the Shapely plane. Default
is 0.
project (Optional[bool]): Controls if the breps are projected onto the plane
in the direction of the Shapley plane's normal. Default is True.
parallel (Optional[bool]): Controls if only the rhino surfaces that have the
same normal as the Shapely plane are yielded. If true, all non parallel
surfaces are filtered out. Default is False.
Raises:
ImportError: If ``rhino3dm`` is not installed. To enable rhino features use
``pip install sectionproperties[rhino]``.
Returns:
A Geometry object found in the encoded string.
"""
try:
import sectionproperties.pre.rhino as rhino_importer
except ImportError as e:
msg = "There is something wrong with your rhino library installation. "
msg += "Please report this error at "
msg += "https://github.com/robbievanleeuwen/section-properties/issues"
raise ImportError(msg) from e
return cls(geom=rhino_importer.load_brep_encoding(r3dm_brep, **kwargs)[0])
def create_facets_and_control_points(self) -> None:
"""Creates geometry data from shapely data.
Generates points, facets, control points, holes and perimeter from the
shapely geometry.
"""
self.holes = []
self.points = []
self.facets = []
self.points, self.facets = create_points_and_facets(
shape=self.geom,
tol=self.tol,
)
if not self.assigned_control_point:
self.control_points = list(self.geom.representative_point().coords) # pyright: ignore [reportAttributeAccessIssue]
else:
self.control_points = list(self.assigned_control_point.coords) # pyright: ignore [reportAttributeAccessIssue]
for hole in self.geom.interiors:
hole_polygon = Polygon(hole)
self.holes += tuple(hole_polygon.representative_point().coords) # pyright: ignore [reportOperatorIssue]
def compile_geometry(self) -> None:
"""Alias for ``create_facets_and_control_points()``.
Alters attributes .points, .facets, .holes, .control_points to represent
the data in the shapely geometry.
"""
self.create_facets_and_control_points()
def create_mesh(
self,
mesh_sizes: float | list[float],
min_angle: float = 30.0,
coarse: bool = False,
) -> Geometry:
r"""Creates a quadratic triangular mesh from the Geometry object.
Args:
mesh_sizes: A float describing the maximum mesh element area to be used
within the Geometry-object finite-element mesh (may also be a list of
length 1)
min_angle: The meshing algorithm adds vertices to the mesh to ensure that no
angle smaller than the minimum angle (in degrees, rounded to 1 decimal
place). Note that small angles between input segments cannot be
eliminated. If the minimum angle is 20.7 deg or smaller, the
triangulation algorithm is theoretically guaranteed to terminate (given
sufficient precision). The algorithm often doesn't terminate for angles
greater than 33 deg. Some meshes may require angles well below 20 deg to
avoid problems associated with insufficient floating-point precision.
Defaults to ``30.0``.
coarse: If set to True, will create a coarse mesh (no area or quality
constraints). Defaults to ``False``.
Raises:
ValueError: ``mesh_sizes`` is not valid
Returns:
``Geometry`` object with mesh data stored in ``.mesh`` attribute. Returned
``Geometry`` object is self, not a new instance.
Example:
The following example creates a circular cross-section with a diameter of
50 mm with 64 points, and generates a mesh with a maximum triangular area of
2.5 mm\ :sup:`2`.
.. plot::
:include-source: True
:caption: Mesh for a 50 mm diameter circle
from sectionproperties.pre.library import circular_section
from sectionproperties.analysis import Section
geom = circular_section(d=50, n=64)
geom = geom.create_mesh(mesh_sizes=2.5)
Section(geom).plot_mesh(materials=False)
"""
if isinstance(mesh_sizes, list) and len(mesh_sizes) == 1:
mesh_size = mesh_sizes[0]
elif isinstance(mesh_sizes, float | int):
mesh_size = mesh_sizes
else:
msg = "Argument 'mesh_sizes' for a Geometry must be either a float, or a "
msg += f"list of float with length of 1, not {mesh_sizes}."
raise ValueError(msg)
self.mesh = pre.create_mesh(
points=self.points,
facets=self.facets,
holes=self.holes,
control_points=self.control_points,
mesh_sizes=mesh_size,
min_angle=min_angle,
coarse=coarse,
)
return self
def align_to(
self,
other: Geometry | CompoundGeometry | tuple[float, float],
on: str,
inner: bool = False,
) -> Geometry:
"""Aligns the geometry to another Geometry object.
Returns a new Geometry object, representing ``self`` translated so that is
aligned ``on`` one of the outer bounding box edges of ``other``.
If ``other`` is a tuple representing an (``x``, ``y``) coordinate, then the new
Geometry object will represent 'self' translated so that it is aligned ``on``
that side of the point.
Args:
other: Either another Geometry or a tuple representing an (``x``, ``y``)
coordinate point that ``self`` should align to.
on: A str of either "left", "right", "bottom", or "top" indicating which
side of ``other`` that ``self`` should be aligned to.
inner: If True, align ``self`` to ``other`` in such a way that ``self`` is
aligned to the "inside" of ``other``. In other words, align ``self`` to
``other`` on the specified edge so they overlap. Defaults to ``False``.
Returns:
Geometry object translated to alignment location
Example:
.. plot::
:include-source: True
:caption: A triangle aligned to the top of a rectangle.
from sectionproperties.pre.library import rectangular_section
from sectionproperties.pre.library import triangular_section
rect = rectangular_section(b=100, d=50)
tri = triangular_section(b=50, h=50)
tri = tri.align_to(other=rect, on="top")
(rect + tri).plot_geometry()
"""
# Mappings are for indexes in the list of bbox extents of both
# 'self' and 'align_to'. i.e. a mapping of which "word" corresponds
# to which bounding box coordinate
align_self_map = {
"left": 1,
"right": 0,
"bottom": 3,
"top": 2,
}
other_as_geom_map = {
"left": 0,
"right": 1,
"bottom": 2,
"top": 3,
}
other_as_point_map = {
"left": 0,
"right": 0,
"bottom": 1,
"top": 1,
}
self_align_idx = align_self_map[on]
if isinstance(other, Geometry | CompoundGeometry):
align_to_idx = other_as_geom_map[on]
align_to_coord = other.calculate_extents()[align_to_idx]
else:
align_to_idx = other_as_point_map[on]
align_to_coord = other[align_to_idx]
self_extents = self.calculate_extents() # min x, max x, min y, max y
self_align_coord = self_extents[self_align_idx]
if inner:
self_align_coord = self_extents[align_to_idx]
offset = align_to_coord - self_align_coord
arg = "x_offset"
if on in ["top", "bottom"]:
arg = "y_offset"
kwargs = {arg: offset}
return self.shift_section(**kwargs)
def align_center(
self,
align_to: Geometry | tuple[float, float] | None = None,
) -> Geometry:
"""Aligns the geometry to a center point.
Returns a new Geometry object, translated in both ``x`` and ``y``, so that the
the new object's centroid will be aligned with the centroid of the object in
``align_to``. If ``align_to`` is an (``x``, ``y``) coordinate, then the centroid
will be aligned to the coordinate. If ``align_to`` is ``None`` then the new
object will be aligned with its centroid at the origin.
Args:
align_to: Another Geometry to align to, an (``x``, ``y``) coordinate or
``None``. Defaults to ``None``.
Raises:
ValueError: ``align_to`` is not valid
Returns:
Geometry object translated to new alignment
Example:
.. plot::
:include-source: True
:caption: A triangular hole aligned to the centre of a square.
from sectionproperties.pre.library import rectangular_section
from sectionproperties.pre.library import triangular_section
rect = rectangular_section(b=200, d=200)
tri = triangular_section(b=50, h=50)
tri = tri.align_center(align_to=rect)
geom = rect + tri
geom.holes = [(100, 100)]
geom.control_points = [(25, 25)]
geom.plot_geometry()
"""
cx, cy = next(iter(self.geom.centroid.coords))
# Suggested by @Agent6-6-6: Hard-rounding of cx and cy allows
# for greater precision in placing geometry with its centroid
# near [0, 0]. True [0, 0] placement will not be possible due
# to floating point errors.
if align_to is None:
shift_x, shift_y = round(-cx, self.tol), round(-cy, self.tol)
elif isinstance(align_to, Geometry):
align_cx, align_cy = next(iter(align_to.geom.centroid.coords)) # RUF015
shift_x = round(align_cx - cx, self.tol)
shift_y = round(align_cy - cy, self.tol)
else:
try:
point_x, point_y = align_to
shift_x = round(point_x - cx, self.tol)
shift_y = round(point_y - cy, self.tol)
except (
TypeError,
ValueError,
) as e: # align_to not subscriptable, incorrect length, etc.
msg = "align_to must be either a Geometry object, an x, y coordinate, "
msg += f"or None, not {align_to}."
raise ValueError(msg) from e
return self.shift_section(x_offset=shift_x, y_offset=shift_y)
def shift_section(
self,
x_offset: float = 0.0,
y_offset: float = 0.0,
) -> Geometry:
"""Returns a new Geometry object translated by (``x_offset``, ``y_offset``).
Args:
x_offset: Distance in x-direction by which to shift the geometry. Defaults
to ``0.0``.
y_offset: Distance in y-direction by which to shift the geometry. Defaults
to ``0.0``.
Returns:
New Geometry object shifted by ``x_offset`` and ``y_offset``
Example:
.. plot::
:include-source: True
:caption: Using ``shift_section`` to shift geometry.
from sectionproperties.pre.library import rectangular_section
rect1 = rectangular_section(b=200, d=100)
rect2 = rect1.shift_section(x_offset=100, y_offset=100)
(rect1 + rect2).plot_geometry()
"""
# Move assigned control point
new_ctrl_point: tuple[float, float] | None = None
if self.assigned_control_point:
new_ctrl_point_geom = affinity.translate(
self.assigned_control_point, x_offset, y_offset
)
new_ctrl_point = new_ctrl_point_geom.x, new_ctrl_point_geom.y
return Geometry(
geom=affinity.translate(self.geom, x_offset, y_offset),
material=self.material,
control_points=new_ctrl_point,
tol=self.tol,
)
def rotate_section(
self,
angle: float,
rot_point: tuple[float, float] | str = "center",
use_radians: bool = False,
) -> Geometry:
"""Rotate the Geometry object.
Rotates the geometry and specified angle about a point. If the rotation point is
not provided, rotates the section about the center of the geometry's bounding
box.
Args:
angle: Angle (degrees by default) by which to rotate the section. A positive
angle leads to a counter-clockwise rotation.
rot_point: Point (``x``, ``y``) about which to rotate the section. If not
provided, will rotate about the "center" of the geometry's bounding box.
Defaults to ``"center"``.
use_radians: Boolean to indicate whether ``angle`` is in degrees or radians.
If True, ``angle`` is interpreted as radians. Defaults to ``False``.
Returns:
New Geometry object rotated by ``angle`` about ``rot_point``
Example:
.. plot::
:include-source: True
:caption: A 200UB25 section rotated clockwise by 30 degrees
from sectionproperties.pre.library import i_section
geom = i_section(d=203, b=133, t_f=7.8, t_w=5.8, r=8.9, n_r=8)
geom.rotate_section(angle=-30).plot_geometry()
"""
new_ctrl_point = None
if self.assigned_control_point:
if rot_point == "center":
centre = box(*self.geom.bounds).centroid
rotate_point = centre.x, centre.y
else:
rotate_point = rot_point
new_ctrl_point_geom = affinity.rotate(
self.assigned_control_point,
angle,
rotate_point, # pyright: ignore [reportArgumentType]
use_radians,
)
new_ctrl_point = new_ctrl_point_geom.x, new_ctrl_point_geom.y
return Geometry(
geom=affinity.rotate(self.geom, angle, rot_point, use_radians), # pyright: ignore [reportArgumentType]
material=self.material,
control_points=new_ctrl_point,
tol=self.tol,
)
def mirror_section(
self,
axis: str = "x",
mirror_point: tuple[float, float] | str = "center",
) -> Geometry:
"""Mirrors the geometry about a point on either the x or y-axis.
Args:
axis: Axis about which to mirror the geometry, ``"x"`` or ``"y"``. Defaults
to ``"x"``.
mirror_point: Point about which to mirror the geometry (``x``, ``y``). If no
point is provided, mirrors the geometry about the center of the shape's
bounding box. Defaults to ``"center"``.
Returns:
New Geometry object mirrored on ``axis`` about ``mirror_point``
Example:
The following example mirrors a 200PFC section about the y-axis:
.. plot::
:include-source: True
:caption: A 200PFC section mirrored about the y-axis and the point
``(0, 0)``
from sectionproperties.pre.library import channel_section
geom = channel_section(d=200, b=75, t_f=12, t_w=6, r=12, n_r=8)
geom.mirror_section(axis="y", mirror_point=(0, 0)).plot_geometry()
"""
x_mirror = 1.0
y_mirror = 1.0
m_pt: tuple[float, float] | str
if mirror_point != "center" and not isinstance(mirror_point, str):
x, y = mirror_point
m_pt = (x, y)
else:
m_pt = mirror_point
if axis == "x":
x_mirror = -x_mirror
elif axis == "y":
y_mirror = -y_mirror
mirrored_geom = affinity.scale(
self.geom,
xfact=y_mirror,
yfact=x_mirror,
zfact=1.0,
origin=m_pt, # pyright: ignore [reportArgumentType]
)
new_ctrl_point: tuple[float, float] | None = None
if self.assigned_control_point:
new_ctrl_point_geom = affinity.scale(
self.assigned_control_point,
xfact=y_mirror,
yfact=x_mirror,
zfact=1.0,
origin=mirror_point, # pyright: ignore [reportArgumentType]
)
new_ctrl_point = new_ctrl_point_geom.x, new_ctrl_point_geom.y
return Geometry(
geom=mirrored_geom,
material=self.material,
control_points=new_ctrl_point,
tol=self.tol,
)
def split_section(
self,
point_i: tuple[float, float],
point_j: tuple[float, float] | None = None,
vector: tuple[float, float] | npt.NDArray[np.float64] | None = None,
) -> tuple[list[Geometry], list[Geometry]]:
"""Splits geometry about a line.
Splits, or bisects, the geometry about a line, as defined by two points on the
line or by one point on the line and a vector. Either ``point_j`` or ``vector``
must be given. If ``point_j`` is given, ``vector`` is ignored.
Returns a tuple of two lists each containing new Geometry instances representing
the ``"top"`` and ``"bottom"`` portions, respectively, of the bisected geometry.
If the line is a vertical line then the ``"right"`` and ``"left"`` portions,
respectively, are returned.
Args:
point_i: A tuple of (``x``, ``y``) coordinates to define a first point on
the line
point_j: A tuple of (``x``, ``y``) coordinates to define a second point on
the line. Defaults to ``None``.
vector: A tuple or numpy array of (``x``, ``y``) components to define the
line direction. Defaults to ``None``.
Raises:
ValueError: Line definition is invalid
Returns:
A tuple of lists containing Geometry objects that are bisected about the
line defined by the two given points. The first item in the tuple represents
the geometries on the ``"top"`` of the line (or to the ``"right"`` of the
line, if vertical) and the second item represents the geometries to the
``"bottom"`` of the line (or to the ``"left"`` of the line, if vertical).
Example:
The following example splits a 200PFC section about the x-axis at ``y=100``:
.. plot::
:include-source: True
:caption: A 200PFC section split about the y-axis.
from sectionproperties.pre.library import channel_section
geom = channel_section(d=200, b=75, t_f=12, t_w=6, r=12, n_r=8)
top_geoms, bot_geoms = geom.split_section(
point_i=(0, 100),
point_j=(1, 100),
)
(top_geoms[0] + bot_geoms[0]).plot_geometry()
"""
if point_j:
vector = np.array(
[
point_j[0] - point_i[0],
point_j[1] - point_i[1],
]
)
elif vector is not None:
vector = np.array(vector)
else:
msg = "Either a second point or a vector must be given to define the line."
raise ValueError(msg)
bounds = self.calculate_extents()
line_segment = bisect.create_line_segment(
point_on_line=point_i,
vector=vector,
bounds=bounds,
)
top_right_polys, bottom_left_polys = bisect.group_top_and_bottom_polys(
polys=split(self.geom, line_segment),
line=line_segment,
)
# Create new Geometrys from polys, preserve original material assignments
top_right_geoms = [Geometry(poly, self.material) for poly in top_right_polys]
bottom_left_geoms = [
Geometry(poly, self.material) for poly in bottom_left_polys
]
return top_right_geoms, bottom_left_geoms
def offset_perimeter(
self,
amount: float = 0.0,
where: str = "exterior",
resolution: int = 12,
) -> Geometry | CompoundGeometry:
"""Dilates or erodes the section perimeter by a discrete amount.
Args:
amount: Distance to offset the section by. A negative value "erodes" the
section. A positive value "dilates" the section. Defaults to ``0.0``.
where: One of either ``"exterior"``, ``"interior"``, or ``"all"`` to specify
which edges of the geometry to offset. If geometry has no interiors,
then this parameter has no effect. Defaults to ``"exterior"``.
resolution: Number of segments used to approximate a quarter circle around a
point. Defaults to ``12``.
Raises:
ValueError: ``where`` is invalid
ValueError: Attempted to offset internally where there are no holes
RuntimeError: If geometry generation fails
Returns:
Geometry object translated to new alignment
Example:
The following example erodes a 200PFC section by 2 mm:
.. plot::
:include-source: True
:caption: A 200PFC eroded by 2 mm.
from sectionproperties.pre.library import channel_section
geom = channel_section(d=200, b=75, t_f=12, t_w=6, r=12, n_r=8)
geom.offset_perimeter(amount=-2.0).plot_geometry()
"""
if self.geom.interiors and where == "interior":
exterior_polygon = Polygon(self.geom.exterior)
for interior in self.geom.interiors:
buffered_interior = buffer_polygon(
Polygon(interior), amount, resolution
)
exterior_polygon = exterior_polygon - buffered_interior
if isinstance(exterior_polygon, MultiPolygon):
return CompoundGeometry(
geoms=[
Geometry(poly, self.material) for poly in exterior_polygon.geoms
]
)
elif not isinstance(exterior_polygon, Polygon):
msg = "Geometry generation failed."
raise RuntimeError(msg)
# Check to see if assigned_control_point is still valid
if self.assigned_control_point and exterior_polygon.contains(
self.assigned_control_point
):
return Geometry(
geom=exterior_polygon,
material=self.material,
control_points=self.control_points[0],
tol=self.tol,
)
return Geometry(
geom=exterior_polygon,
material=self.material,
tol=self.tol,
)
elif not self.geom.interiors and where == "interior":
msg = "Cannot buffer interior of Geometry object if it has no holes."
raise ValueError(msg)