-
Notifications
You must be signed in to change notification settings - Fork 92
/
geometry.py
2056 lines (1786 loc) · 86.8 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
from __future__ import annotations
from ntpath import join
from typing import List, Optional, Union, Tuple, List, Any
import copy
import math
import pathlib
import more_itertools
import numpy as np
from shapely.geometry import (
Polygon,
MultiPolygon,
LineString,
LinearRing,
Point,
box,
GeometryCollection,
)
from shapely.ops import split, unary_union
import shapely
import matplotlib
import matplotlib.pyplot as plt
import sectionproperties.pre.pre as pre
import sectionproperties.pre.bisect_section as bisect
import sectionproperties.post.post as post
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.
:cvar geom: a Polygon object that defines the geometry
:vartype geom: :class:`shapely.geometry.Polygon`
:cvar material: Optional, a Material to associate with this geometry
:vartype material: Optional[:class:`~sectionproperties.pre.Material`]
:cvar control_point: Optional, 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 :func:`shapely.geometry.Polygon.representative_point`.
:cvar tol: Optional, default is 12. 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.
"""
def __init__(
self,
geom: shapely.geometry.Polygon,
material: pre.Material = pre.DEFAULT_MATERIAL,
control_points: Optional[Union[Point, List[float, float]]] = None,
tol=12,
):
"""Inits the Geometry class."""
if isinstance(geom, MultiPolygon):
raise ValueError(f"Use CompoundGeometry(...) for a MultiPolygon object.")
if not isinstance(geom, Polygon):
raise ValueError(
f"Argument is not a valid shapely.geometry.Polygon object: {repr(geom)}"
)
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 # Represents 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 = []
self.shift = []
self.points = []
self.facets = []
self.holes = []
self.perimeter = []
self._recovery_points = []
self.compile_geometry()
def _repr_svg_(self):
print("sectionproperties.pre.geometry.Geometry")
print(f"object at: {hex(id(self))}")
print(f"Material: {self.material.name}")
return self.geom._repr_svg_()
def assign_control_point(self, control_point: List[float, float]):
"""
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 shapely.geometry.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.
:cvar control_points: An *(x, y)* coordinate that describes the distinct, contiguous,
region of a single material within the geometry.
Exactly one point is required for each geometry with a distinct material.
:vartype control_point: list[float, float]
"""
return Geometry(self.geom, self.material, control_point)
@staticmethod
def from_points(
points: List[List[float]],
facets: List[List[int]],
control_points: List[List[float]],
holes: Optional[List[List[float]]] = None,
material: Optional[pre.Material] = pre.DEFAULT_MATERIAL,
):
"""
An interface for the creation of Geometry objects through the definition of points,
facets, and holes.
:cvar points: List of points *(x, y)* defining the vertices of the section geometry.
If facets are not provided, it is a assumed the that the list of points are ordered
around the perimeter, either clockwise or anti-clockwise.
:vartype points: list[list[float, float]]
:cvar facets: A list of *(start, end)* indexes 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.
:vartype facets: list[list[int, int]]
:cvar 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 CompoundGeometry.from_points()
:vartype control_point: list[float, float]
:cvar holes: Optional. 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.
:vartype holes: list[list[float, float]]
:cvar material: Optional. A :class:`~sectionproperties.pre.pre.Material` object
that is to be assigned. If not given, then the
:class:`~sectionproperties.pre.pre.DEFAULT_MATERIAL` will be used.
:vartype materials: :class:`~sectionproperties.pre.pre.Material`
"""
if len(control_points) != 1:
raise ValueError(
"Control points for Geometry instances must have exactly "
"one x, y coordinate and entered as a list of list of float, e.g. [[0.1, 3.4]]."
"CompoundGeometry.from_points() can accept multiple control points\n"
f"Control points received: {control_points}"
)
if holes is None:
holes = []
prev_facet = []
# Initialize the total number of accumulators needed
# Always an exterior, plus, a separate accumulator for each interior region
exterior = []
interiors = [[] 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
active_list.append(points[i_idx])
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 (
i_idx != prev_j_idx and holes
): # If there is a break in the chain of edges...
if (
active_list == exterior
): # ...and we are still accumulating on the exterior...
active_list = interiors[
interior_counter
] # ... then move to the interior accumulator
else: # ...or if we are already in the interior accumulator...
interior_counter += (
1 # ...then start the next interior accumulator for a new hole.
)
active_list = interiors[interior_counter]
active_list.append(points[i_idx])
else:
active_list.append(
points[i_idx]
) # Only need i_idx b/c shapely auto-closes polygons
prev_facet = facet
exterior_geometry = Polygon(exterior)
interior_polys = [Polygon(interior) for interior in interiors]
interior_geometry = MultiPolygon(interior_polys)
geometry = Geometry(
exterior_geometry - interior_geometry, material, control_points
)
return geometry
@staticmethod
def from_dxf(
dxf_filepath: Union[str, pathlib.Path],
) -> Union[Geometry, CompoundGeometry]:
"""
An interface for the creation of Geometry objects from CAD .dxf files.
:cvar dxf_filepath: A path-like object for the dxf file
:vartype dxf_filepath: Union[str, pathlib.Path]
"""
return load_dxf(dxf_filepath)
@classmethod
def from_3dm(cls, filepath: Union[str, pathlib.Path], **kwargs) -> Geometry:
"""Class method to create a `Geometry` from the objects in a Rhino `.3dm` file.
:param filepath:
File path to the rhino `.3dm` file.
:type filepath: Union[str, pathlib.Path]
:param kwargs:
See below.
: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.
:return:
A Geometry object.
:rtype: :class:`~sectionproperties.pre.geometry.Geometry`
:Keyword Arguments:
* *refine_num* (``int, optional``) --
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* (``numpy.ndarray, optional``) --
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* (``numpy.ndarray, optional``) --
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* (``float, optional``) --
The distance to the Shapely plane.
Default is 0.
* *project* (``boolean, optional``) --
Controls if the breps are projected onto the plane in the direction of the Shapley plane's normal.
Default is True.
* *parallel* (``boolean, optional``) --
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.
"""
try:
import sectionproperties.pre.rhino as rhino_importer # type: ignore
except ImportError as e:
print(e)
print(
"There is something wrong with your rhino library installation. "
"Please report this error at https://github.com/robbievanleeuwen/section-properties/issues"
)
return
geom = None
list_poly = rhino_importer.load_3dm(filepath, **kwargs)
if len(list_poly) == 1:
geom = cls(geom=list_poly[0])
else:
raise RuntimeError(
f"Multiple surfaces extracted from the file. "
f"Either use CompoundGeometry or extract individual surfaces manually via pre.rhino."
)
return geom
@classmethod
def from_rhino_encoding(cls, r3dm_brep: str, **kwargs) -> Geometry:
"""Load an encoded single surface planer brep.
:param r3dm_brep:
A Rhino3dm.Brep encoded as a string.
:type r3dm_brep: str
:param kwargs:
See below.
:return:
A Geometry object found in the encoded string.
:rtype: :class:`~sectionproperties.pre.geometry.Geometry`
:Keyword Arguments:
* *refine_num* (``int, optional``) --
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* (``numpy.ndarray, optional``) --
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* (``numpy.ndarray, optional``) --
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* (``float, optional``) --
The distance to the Shapely plane.
Default is 0.
* *project* (``boolean, optional``) --
Controls if the breps are projected onto the plane in the direction of the Shapley plane's normal.
Default is True.
* *parallel* (``boolean, optional``) --
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.
"""
try:
import sectionproperties.pre.rhino as rhino_importer # type: ignore
except ImportError as e:
print(e)
print(
"There is something wrong with your rhino library installation. "
"Please report this error at https://github.com/robbievanleeuwen/section-properties/issues"
)
return
return cls(geom=rhino_importer.load_brep_encoding(r3dm_brep, **kwargs)[0])
def create_facets_and_control_points(self):
self.perimeter = None
self.perimeter = list(range(len(self.geom.exterior.coords)))
self.holes = []
self.points = []
self.facets = []
self.points, self.facets = create_points_and_facets(self.geom, self.tol)
if not self.assigned_control_point:
self.control_points = tuple(self.geom.representative_point().coords)
else:
self.control_points = tuple(self.assigned_control_point.coords)
for hole in self.geom.interiors:
hole_polygon = Polygon(hole)
self.holes += tuple(hole_polygon.representative_point().coords)
return
def compile_geometry(self): # Alias
"""
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: Union[float, List[float]], coarse: bool = False):
"""Creates a quadratic triangular mesh from the Geometry object.
:param mesh_sizes: A float describing the maximum mesh element area to be used
within the Geometry-object finite-element mesh.
:type mesh_sizes: Union[float, List[float]]
:param bool coarse: If set to True, will create a coarse mesh (no area or
quality constraints)
:return: Geometry-object with mesh data stored in .mesh attribute. Returned
Geometry-object is self, not a new instance.
:rtype: :class:`~sectionproperties.pre.geometry.Geometry`
The following example creates a circular cross-section with a diameter of 50 with 64
points, and generates a mesh with a maximum triangular area of 2.5::
import sectionproperties.pre.library.primitive_sections as primitive_sections
geometry = primitive_sections.circular_section(d=50, n=64)
geometry = geometry.create_mesh(mesh_sizes=2.5)
.. figure:: ../images/sections/circle_mesh.png
:align: center
:scale: 75 %
Mesh generated from the above geometry.
"""
if isinstance(mesh_sizes, (list, tuple)) and len(mesh_sizes) == 1:
mesh_size = mesh_sizes[0]
elif isinstance(mesh_sizes, (float, int)):
mesh_size = [mesh_sizes]
else:
raise ValueError(
"Argument 'mesh_sizes' for a Geometry must be either "
f"a float, or a list of float with length of 1, not {mesh_sizes}."
)
self.mesh = pre.create_mesh(
self.points, self.facets, self.holes, self.control_points, mesh_size, coarse
)
return self
def align_to(
self,
other: Union[Geometry, Tuple[float, float]],
on: str,
inner: bool = False,
) -> Geometry:
"""
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.
:param other: Either another Geometry or a tuple representing an
*(x,y)* coordinate point that 'self' should align to.
:type other: Union[:class:`~sectionproperties.pre.geometry.Geometry`, Tuple[float, float]]
:param on: A str of either "left", "right", "bottom", or "top" indicating which
side of 'other' that self should be aligned to.
:param inner: Default False. 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.
:type inner: bool
:return: Geometry object translated to alignment location
:rtype: :class:`~sectionproperties.pre.geometry.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]
align_to_geometry = isinstance(other, (Geometry, CompoundGeometry))
if align_to_geometry:
align_to_idx = other_as_geom_map[on]
else:
align_to_idx = other_as_point_map[on]
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]
if align_to_geometry:
other_extents = other.calculate_extents()
else:
other_extents = other
align_to_coord = other_extents[align_to_idx]
offset = align_to_coord - self_align_coord
# offset = align_to_coord - self_align_coord
arg = "x_offset"
if on in ["top", "bottom"]:
arg = "y_offset"
kwargs = {arg: offset}
new_geom = self.shift_section(**kwargs)
return new_geom
def align_center(
self, align_to: Optional[Union[Geometry, Tuple[float, float]]] = None
):
"""
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.
:param align_to: Another Geometry to align to or None (default is None)
:type align_to: Optional[Union[:class:`~sectionproperties.pre.geometry.Geometry`, Tuple[float, float]]]
:return: Geometry object translated to new alignment
:rtype: :class:`~sectionproperties.pre.geometry.Geometry`
"""
cx, cy = list(self.geom.centroid.coords)[0]
# 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 = list(align_to.geom.centroid.coords)[0]
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,
): # align_to not subscriptable, incorrect length, etc.
raise ValueError(
f"align_to must be either a Geometry object or an x, y coordinate, not {align_to}."
)
new_geom = self.shift_section(x_offset=shift_x, y_offset=shift_y)
return new_geom
def shift_section(
self,
x_offset=0.0,
y_offset=0.0,
):
"""
Returns a new Geometry object translated by 'x_offset' and 'y_offset'.
:param x_offset: Distance in x-direction by which to shift the geometry.
:type x_offset: float
:param y_offset: Distance in y-direction by which to shift the geometry.
:type y_offset: float
:return: New Geometry-object shifted by 'x_offset' and 'y_offset'
:rtype: :class:`~sectionproperties.pre.geometry.Geometry`
"""
# Move assigned control point
new_ctrl_point = None
if self.assigned_control_point:
new_ctrl_point = shapely.affinity.translate(
self.assigned_control_point, x_offset, y_offset
).coords[0]
new_geom = Geometry(
shapely.affinity.translate(self.geom, x_offset, y_offset),
self.material,
new_ctrl_point,
)
return new_geom
def rotate_section(
self,
angle: float,
rot_point: Union[List[float], str] = "center",
use_radians: bool = False,
):
"""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.
:param float angle: Angle (degrees by default) by which to rotate the section. A positive angle leads
to a counter-clockwise rotation.
:param rot_point: Optional. Point *(x, y)* about which to rotate the section. If not provided, will rotate
about the center of the geometry's bounding box. Default = 'center'.
:type rot_point: list[float, float]
:param use_radians: Boolean to indicate whether 'angle' is in degrees or radians. If True, 'angle' is interpreted as radians.
:return: New Geometry-object rotated by 'angle' about 'rot_point'
:rtype: :class:`~sectionproperties.pre.geometry.Geometry`
The following example rotates a 200UB25 section clockwise by 30 degrees::
import sectionproperties.pre.library.steel_sections as steel_sections
geometry = steel_sections.i_section(d=203, b=133, t_f=7.8, t_w=5.8, r=8.9, n_r=8)
new_geometry = geometry.rotate_section(angle=-30)
"""
new_ctrl_point = None
if self.assigned_control_point:
rotate_point = rot_point
if rot_point == "center":
rotate_point = box(*self.geom.bounds).centroid
new_ctrl_point = shapely.affinity.rotate(
self.assigned_control_point, angle, rotate_point, use_radians
).coords[0]
new_geom = Geometry(
shapely.affinity.rotate(self.geom, angle, rot_point, use_radians),
self.material,
new_ctrl_point,
)
return new_geom
def mirror_section(
self, axis: str = "x", mirror_point: Union[List[float], str] = "center"
):
"""Mirrors the geometry about a point on either the x or y-axis.
:param string axis: Axis about which to mirror the geometry, *'x'* or *'y'*
:param mirror_point: Point about which to mirror the geometry *(x, y)*.
If no point is provided, mirrors the geometry about the centroid of the shape's bounding box.
Default = 'center'.
:type mirror_point: Union[list[float, float], str]
:return: New Geometry-object mirrored on 'axis' about 'mirror_point'
:rtype: :class:`~sectionproperties.pre.geometry.Geometry`
The following example mirrors a 200PFC section about the y-axis and the point (0, 0)::
import sectionproperties.pre.library.steel_sections as steel_sections
geometry = steel_sections.channel_section(d=200, b=75, t_f=12, t_w=6, r=12, n_r=8)
new_geometry = geometry.mirror_section(axis='y', mirror_point=[0, 0])
"""
x_mirror = 1
y_mirror = 1
if mirror_point != "center":
x, y = mirror_point
mirror_point = (x, y, 0)
if axis == "x":
x_mirror = -x_mirror
elif axis == "y":
y_mirror = -y_mirror
mirrored_geom = shapely.affinity.scale(
self.geom, xfact=y_mirror, yfact=x_mirror, zfact=1.0, origin=mirror_point
)
new_ctrl_point = None
if self.assigned_control_point:
new_ctrl_point = shapely.affinity.scale(
self.assigned_control_point,
xfact=y_mirror,
yfact=x_mirror,
zfact=1.0,
origin=mirror_point,
).coords[0]
new_geom = Geometry(mirrored_geom, self.material, new_ctrl_point)
return new_geom
def split_section(
self,
point_i: Tuple[float, float],
point_j: Optional[Tuple[float, float]] = None,
vector: Union[Optional[Tuple[float, float]], np.ndarray] = None,
) -> Tuple[List[Geometry], List[Geometry]]:
"""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.
:param point_i: A tuple of *(x, y)* coordinates to define a first point on the line
:type point_i: Tuple[float, float]
:param point_j: Optional. A tuple of *(x, y)* coordinates to define a second point on the line
:type point_j: Tuple[float, float]
:param vector: Optional. A tuple or numpy ndarray of *(x, y)* components to define the line direction.
:type vector: Union[Tuple[float, float], numpy.ndarray]
:return: 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).
:rtype: Tuple[List[Geometry], List[Geometry]]
The following example splits a 200PFC section about the y-axis::
import sectionproperties.pre.library.steel_sections as steel_sections
from shapely.geometry import LineString
geometry = steel_sections.channel_section(d=200, b=75, t_f=12, t_w=6, r=12, n_r=8)
right_geom, left_geom = geometry.split_section((0, 0), (0, 1))
"""
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)
elif not point_j and not vector:
raise ValueError(
"Either a second point or a vector must be given to define the line."
)
bounds = self.calculate_extents()
line_segment = bisect.create_line_segment(point_i, vector, bounds)
top_right_polys, bottom_left_polys = bisect.group_top_and_bottom_polys(
split(self.geom, line_segment), line_segment
)
# Create new Geometry instances 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, where: str = "exterior", resolution: float = 12
):
"""Dilates or erodes the section perimeter by a discrete amount.
:param amount: Distance to offset the section by. A -ve value "erodes" the section.
A +ve value "dilates" the section.
:type amount: float
:param 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.
Default is "exterior".
:type where: str
:param resolution: Number of segments used to approximate a quarter circle around a point
:type resolution: float
:return: Geometry object translated to new alignment
:rtype: :class:`~sectionproperties.pre.geometry.Geometry`
The following example erodes a 200PFC section by 2 mm::
import sectionproperties.pre.library.steel_sections as steel_sections
geometry = sections.channel_section(d=200, b=75, t_f=12, t_w=6, r=12, n_r=8)
new_geometry = geometry.offset_perimeter(amount=-2)
"""
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(
[Geometry(poly, self.material) for poly in exterior_polygon]
)
# 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(exterior_polygon, self.material, self.control_points[0])
return Geometry(exterior_polygon, self.material)
elif not self.geom.interiors and where == "interior":
raise ValueError(
"Cannot buffer interior of Geometry object if it has no holes."
)
elif where == "exterior":
exterior_polygon = Polygon(self.geom.exterior)
buffered_exterior = buffer_polygon(exterior_polygon, amount, resolution)
for interior in self.geom.interiors:
interior_poly = Polygon(interior)
buffered_exterior = buffered_exterior - interior_poly
if isinstance(buffered_exterior, MultiPolygon):
return CompoundGeometry(
[Geometry(poly, self.material) for poly in buffered_exterior.geoms]
)
# Check to see if assigned_control_point is still valid
if self.assigned_control_point and buffered_exterior.contains(
self.assigned_control_point
):
return Geometry(
buffered_exterior, self.material, self.control_points[0]
)
return Geometry(buffered_exterior, self.material)
elif where == "all":
buffered_geom = buffer_polygon(self.geom, amount, resolution)
if isinstance(buffered_geom, MultiPolygon):
compound_geom = CompoundGeometry(
[Geometry(poly, self.material) for poly in buffered_geom]
)
return compound_geom
# Check to see if assigned_control_point is still valid
if self.assigned_control_point and buffered_geom.contains(
self.assigned_control_point
):
single_geom = Geometry(
buffered_geom, self.material, self.control_points[0]
)
return single_geom
return Geometry(buffered_geom, self.material)
def shift_points(
self,
point_idxs: Union[int, List[int]],
dx: float = 0,
dy: float = 0,
abs_x: Optional[float] = None,
abs_y: Optional[float] = None,
) -> Geometry:
"""
Translates one (or many points) in the geometry by either a relative amount or
to a new absolute location. Returns a new Geometry representing the original
with the selected point(s) shifted to the new location.
Points are identified by their index, their relative location within the points
list found in ``self.points``. You can call ``self.plot_geometry(labels="points")`` to
see a plot with the points labeled to find the appropriate point indexes.
:param point_idxs: An integer representing an index location or a list of integer
index locations.
:type point_idxs: Union[int, List[int]]
:param dx: The number of units in the x-direction to shift the point(s) by
:type dx: float
:param dy: The number of units in the y-direction to shift the point(s) by
:type dy: float
:param abs_x: Absolute x-coordinate in coordinate system to shift the
point(s) to. If abs_x is provided, dx is ignored. If providing a list
to point_idxs, all points will be moved to this absolute location.
:type abs_x: Optional[float]
:param abs_y: Absolute y-coordinate in coordinate system to shift the
point(s) to. If abs_y is provided, dy is ignored. If providing a list
to point_idxs, all points will be moved to this absolute location.
:type abs_y: Optional[float]
:return: Geometry object with selected points translated to the new location.
:rtype: :class:`~sectionproperties.pre.geometry.Geometry`
The following example expands the sides of a rectangle, one point at a time,
to make it a square::
import sectionproperties.pre.library.primitive_sections as primitive_sections
geometry = primitive_sections.rectangular_section(d=200, b=150)
# Using relative shifting
one_pt_shifted_geom = geometry.shift_points(point_idxs=1, dx=50)
# Using absolute relocation
both_pts_shift_geom = one_pt_shift_geom.shift_points(point_idxs=2, abs_x=200)
"""
current_points = copy.copy(self.points)
current_facets = copy.copy(self.facets)
current_holes = copy.copy(self.holes)
current_material = copy.copy(self.material)
current_control_points = copy.copy(self.control_points)
if isinstance(point_idxs, int):
point_idxs = [point_idxs]
new_x, new_y = None, None
for point_idx in point_idxs:
current_x, current_y = current_points[point_idx]
new_x = abs_x if abs_x else current_x + dx
new_y = abs_y if abs_y else current_y + dy
current_points[point_idx] = (new_x, new_y)
new_geom = Geometry.from_points(
current_points,
current_facets,
current_control_points,
current_holes,
material=current_material,
)
if self.assigned_control_point and new_geom.geom.contains(
self.assigned_control_point
):
new_geom = Geometry.from_points(
current_points,
current_facets,
current_control_points[0],
current_holes,
current_material,
)
return new_geom
def plot_geometry(
self,
labels=["control_points"],
title="Cross-Section Geometry",
cp=True,
legend=True,
**kwargs,
):
"""Plots the geometry defined by the input section.
:param labels: A list of str which indicate which labels to plot. Can be one
or a combination of "points", "facets", "control_points", or an empty list
to indicate no labels. Default is ["control_points"]
:type labels: list[str]
:param string title: Plot title
:param bool cp: If set to True, plots the control points
:param bool legend: If set to True, plots the legend
:param kwargs: Passed to :func:`~sectionproperties.post.post.plotting_context`
:return: Matplotlib axes object
:rtype: :class:`matplotlib.axes`
The following example creates a CHS discretised with 64 points, with a diameter of 48 and
thickness of 3.2, and plots the geometry::
import sectionproperties.pre.library.steel_sections as steel_sections
geometry = steel_sections.circular_hollow_section(d=48, t=3.2, n=64)
geometry.plot_geometry()
.. figure:: ../images/sections/chs_geometry.png
:align: center
:scale: 75 %
Geometry generated by the above example.
"""
# create plot and setup the plot
with post.plotting_context(title=title, **kwargs) as (fig, ax):
# plot the points and facets
for (i, f) in enumerate(self.facets):
if i == 0:
label = "Points & Facets"
else:
label = None
ax.plot(
[self.points[f[0]][0], self.points[f[1]][0]],
[self.points[f[0]][1], self.points[f[1]][1]],
"ko-",
markersize=2,
linewidth=1.5,
label=label,
)
# plot the holes
for (i, h) in enumerate(self.holes):
if i == 0:
label = "Holes"
else:
label = None
ax.plot(h[0], h[1], "rx", markersize=5, markeredgewidth=1, label=label)
if cp:
# plot the control points
for (i, cp) in enumerate(self.control_points):
if i == 0:
label = "Control Points"
else:
label = None
ax.plot(cp[0], cp[1], "bo", markersize=5, label=label)
# display the labels
for label in labels:
# plot control_point labels
if label == "control_points":
for (i, pt) in enumerate(self.control_points):
ax.annotate(str(i), xy=pt, color="b")
# plot point labels
if label == "points":
for (i, pt) in enumerate(self.points):
ax.annotate(str(i), xy=pt, color="r")
# plot facet labels
if label == "facets":
for (i, fct) in enumerate(self.facets):
pt1 = self.points[fct[0]]
pt2 = self.points[fct[1]]
xy = [(pt1[0] + pt2[0]) / 2, (pt1[1] + pt2[1]) / 2]
ax.annotate(str(i), xy=xy, color="b")
# plot hole labels
if label == "holes":
for (i, pt) in enumerate(self.holes):
ax.annotate(str(i), xy=pt, color="r")
# display the legend
if legend:
ax.legend(loc="center left", bbox_to_anchor=(1, 0.5))
return ax
def calculate_extents(self):
"""Calculates the minimum and maximum x and y-values amongst the list of points;
the points that describe the bounding box of the Geometry instance.
:return: Minimum and maximum x and y-values *(x_min, x_max, y_min, y_max)*
:rtype: tuple(float, float, float, float)
"""
min_x, min_y, max_x, max_y = self.geom.bounds
return (min_x, max_x, min_y, max_y)
def calculate_perimeter(self):
"""Calculates the exterior perimeter of the geometry.