Skip to content

gridshell

GridShellGenerator

Bases: BaseGenerator

Randomly samples and form-finds a gridshell over a (rectangular, circular, or polygonal) boundary.

Shares its mesh-construction logic with CableNetGenerator ("standard", "singularity", and "opening" patterns), but equilibrates the shell with Laplacian smoothing followed by Thrust Network Analysis under prescribed target force densities, rather than the Force Density Method.

Source code in src/torch_structure/generators/gridshell.py
  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
class GridShellGenerator(BaseGenerator):
    """Randomly samples and form-finds a gridshell over a (rectangular, circular, or polygonal) boundary.

    Shares its mesh-construction logic with [CableNetGenerator][torch_structure.generators.cablenet.CableNetGenerator]
    (``"standard"``, ``"singularity"``, and ``"opening"`` patterns), but
    equilibrates the shell with Laplacian smoothing followed by Thrust
    Network Analysis under prescribed target force densities, rather than
    the Force Density Method.
    """

    def __init__(self, **overrides):
        super().__init__(**overrides)
        self.max_attempts = 100
        self.node_attrs = {
            "pattern_coords": torch.empty((0, 2), dtype=torch.float),
            "is_support": torch.empty((0, 1), dtype=torch.bool),
            "is_boundary": torch.empty((0, 1), dtype=torch.bool),
        }
        self.edge_attrs = {
            "is_boundary_edge": torch.empty((0, 1), dtype=torch.bool),
            "is_diagonal_edge": torch.empty((0, 1), dtype=torch.bool),
            "is_opening_edge": torch.empty((0, 1), dtype=torch.bool),
            "ring": torch.empty((0, 1), dtype=torch.int),
        }
        self.default_attrs = {
            "is_diagonal_edge": torch.tensor(False),
            "is_opening_edge": torch.tensor(False),
            "ring": torch.tensor(torch.nan),
        }

    def validate_input(
        self,
        n,
        boundary_density,
        pattern,
        diagonals,
        centroid_support,
        unsupported_boundaries,
        rectangle,
        square,
        curve_boundaries,
        circle,
        q_target_field,
        q_target_boundary,
        opening_radius,
        boundary_support_list,
        boundary_curvature_list,
        rectangle_width,
        rectangle_height,
        square_size,
        corner_angle_list,
    ):
        """Validate the boundary/pattern parameters; raises ``ValueError`` if they are inconsistent."""
        if pattern not in ["standard", "singularity", "opening"]:
            raise ValueError(f"Invalid pattern: {pattern}")
        if rectangle and n != 4:
            raise ValueError("Rectangle pattern requires n=4.")
        if square and not rectangle:
            raise ValueError("Square pattern requires rectangle=True.")
        if circle and pattern not in ["singularity", "opening"]:
            raise ValueError("Circle requires pattern='singularity' or 'opening'.")
        if circle and (square or rectangle):
            raise ValueError("Circle is incompatible with square or rectangle")
        if pattern == "opening" and not centroid_support:
            raise ValueError("Opening pattern requires centroid support.")

    def sample_input(
        self,
        n=None,
        boundary_density=None,
        pattern=None,
        diagonals=None,
        centroid_support=None,
        unsupported_boundaries=True,
        rectangle=False,
        square=False,
        curve_boundaries=True,
        circle=False,
        q_target_field=None,
        q_target_boundary=None,
        opening_radius=None,
        boundary_support_list=None,
        boundary_curvature_list=None,
        rectangle_width=None,
        rectangle_height=None,
        square_size=None,
        corner_angle_list=None,
    ):
        """Sample any unspecified generation parameters, deriving dependent defaults where relevant.

        Each parameter defaults to ``None``, meaning "sample randomly"; an
        explicit value passed via ``overrides`` (see
        [BaseGenerator][torch_structure.generators.base_generator.BaseGenerator])
        is left unchanged. Returns a dict of all resolved parameters, to be
        passed to [generate][torch_structure.generators.gridshell.GridShellGenerator.generate].
        """
        if n is None:
            if rectangle or square:
                n = 4
            else:
                n = np.random.randint(3, 7)
        if boundary_density is None:
            boundary_density = np.random.randint(3, 8)
        if centroid_support is None:
            centroid_support = np.random.choice([True, False], p=[0.3, 0.7])
        if pattern is None:
            pattern = (
                np.random.choice(["standard", "singularity", "opening"])
                if centroid_support
                else "standard"
            )
        if diagonals is None:
            diagonals = (
                np.random.choice([True, False]) if pattern == "standard" else False
            )
        if q_target_field is None:
            q_target_field = np.random.uniform(-15.0, -25.0)
        if q_target_boundary is None:
            q_target_boundary = np.random.uniform(-80.0, -120.0)
        if opening_radius is None:
            if pattern == "opening":
                opening_radius = np.random.rand() * 0.05 + 0.1
            else:
                opening_radius = np.nan
        if boundary_support_list is None:
            if unsupported_boundaries:
                boundary_support_list = np.random.choice(
                    [True, False], size=n, p=[0.5, 0.5]
                )
            else:
                boundary_support_list = [True] * n
        if boundary_curvature_list is None:
            if curve_boundaries:
                boundary_curvature_list = np.empty(n)
                boundary_curvature_list[boundary_support_list] = (
                    np.random.rand(boundary_support_list.sum()) - 0.5
                )
                boundary_curvature_list[~boundary_support_list] = (
                    np.random.rand((~boundary_support_list).sum()) * 0.2 + 0.3
                )
            else:
                boundary_curvature_list = np.zeros(n)
        if rectangle_width is None:
            if rectangle:
                rectangle_width = torch.rand(1) * 0.9 + 0.1
            else:
                rectangle_width = torch.nan
        if rectangle_height is None:
            if rectangle:
                rectangle_height = torch.rand(1) * 0.9 + 0.1
            else:
                rectangle_height = torch.nan
        if square_size is None:
            if square:
                square_size = torch.rand(1) * 0.9 + 0.1
            else:
                square_size = torch.nan
        if corner_angle_list is None:
            min_angle = torch.tensor(math.pi) / 8
            corner_angle_list = []
            while len(corner_angle_list) < n:
                angle = (torch.rand(1) * 2 * math.pi).item()
                # Check if the new angle is far enough from all others
                if all(
                    abs((angle - a + math.pi) % (2 * math.pi) - math.pi) >= min_angle
                    for a in corner_angle_list
                ):
                    corner_angle_list.append(angle)
            corner_angle_list.sort()

        input = {
            "n": n,
            "boundary_density": boundary_density,
            "pattern": pattern,
            "diagonals": torch.tensor(diagonals),
            "centroid_support": torch.tensor(centroid_support),
            "unsupported_boundaries": torch.tensor(unsupported_boundaries),
            "rectangle": torch.tensor(rectangle),
            "square": torch.tensor(square),
            "curve_boundaries": torch.tensor(curve_boundaries),
            "circle": torch.tensor(circle),
            "q_target_field": torch.tensor(q_target_field, dtype=torch.float),
            "q_target_boundary": torch.tensor(q_target_boundary, dtype=torch.float),
            "opening_radius": torch.tensor(opening_radius, dtype=torch.float),
            "boundary_support_list": torch.tensor(
                boundary_support_list, dtype=torch.bool
            ),
            "boundary_curvature_list": torch.tensor(
                boundary_curvature_list, dtype=torch.float
            ),
            "rectangle_width": torch.tensor(rectangle_width, dtype=torch.float),
            "rectangle_height": torch.tensor(rectangle_height, dtype=torch.float),
            "square_size": torch.tensor(square_size, dtype=torch.float),
            "corner_angle_list": torch.tensor(corner_angle_list, dtype=torch.float),
        }

        return input

    def generate(
        self,
        n,
        boundary_density,
        pattern,
        diagonals,
        centroid_support,
        unsupported_boundaries,
        rectangle,
        square,
        curve_boundaries,
        circle,
        q_target_field,
        q_target_boundary,
        opening_radius,
        boundary_support_list,
        boundary_curvature_list,
        rectangle_width,
        rectangle_height,
        square_size,
        corner_angle_list,
    ):
        """Build the boundary, mesh, and (for "opening") central ring, then form-find with Laplacian smoothing + TNA.

        Returns:
            StructData: the form-found gridshell.

        Raises:
            InvalidSampleError: if the resulting geometry's z-extent is out
                of bounds, or if any element is in tension.
        """
        graph = StructData(
            node_attrs=self.node_attrs,
            edge_attrs=self.edge_attrs,
            default_attrs=self.default_attrs,
        )

        if rectangle:
            if square:
                corner_points = self.sample_rectangle(width=square_size, square=True)
            else:
                corner_points = self.sample_rectangle(
                    width=rectangle_width, height=rectangle_height, square=False
                )
        elif circle:
            corner_points = self.sample_unit_circle(
                n, angles=torch.linspace(0, 2 * math.pi, n + 1)[:-1]
            )
        else:
            corner_points = self.sample_unit_circle(n, angles=corner_angle_list)
        looped_corner_points = corner_points + [corner_points[0]]
        centroid = self.polygon_centroid(looped_corner_points)
        if pattern in ["standard", "singularity"]:
            graph.add_node(
                "centroid",
                pattern_coords=centroid,
                is_support=centroid_support,
                is_boundary=torch.tensor(False),
            )
        elif pattern == "opening":
            angles = torch.zeros(n)
            for i in range(n):
                angles[i] = torch.arctan2(
                    corner_points[i][1] - centroid[1], corner_points[i][0] - centroid[0]
                )
            circle_angles = self.compute_optimal_rotation(angles)
            for i in range(n):
                pattern_coord = (
                    torch.tensor(
                        [torch.cos(circle_angles[i]), torch.sin(circle_angles[i])]
                    )
                    * opening_radius
                    + centroid
                )
                graph.add_node(
                    f"opening_{i}",
                    pattern_coords=pattern_coord,
                    is_support=centroid_support,
                    is_boundary=torch.tensor(True),
                )

        # add corner points
        for i, point in enumerate(corner_points):
            graph.add_node(
                f"corner_{i}",
                pattern_coords=point,
                is_support=torch.tensor(True),
                is_boundary=torch.tensor(True),
            )

        # add mesh skeleton points
        for i in range(n):
            is_support = boundary_support_list[i]
            start_boundary, end_boundary = (
                looped_corner_points[i],
                looped_corner_points[i + 1],
            )
            center_boundary = 0.5 * (start_boundary + end_boundary)
            curvature_param = boundary_curvature_list[i]
            control_point = center_boundary + curvature_param * (
                centroid - center_boundary
            )

            # add external boundary points
            if circle:
                boundary_curve = self.circular_arc(
                    start_boundary, end_boundary, centroid, boundary_density * 2 + 3
                )[1:-1]
            else:
                boundary_curve = self.quadratic_bezier(
                    start_boundary,
                    control_point,
                    end_boundary,
                    boundary_density * 2 + 3,
                )[1:-1]
            prev_node = f"corner_{i}"

            for j, point in enumerate(boundary_curve):
                next_node = f"boundary_{i}_{j}"
                graph.add_node(
                    next_node,
                    pattern_coords=point,
                    is_support=is_support,
                    is_boundary=torch.tensor(True),
                )
                if not is_support:
                    graph.add_edge(
                        prev_node, next_node, is_boundary_edge=torch.tensor(True)
                    )
                prev_node = next_node
            if not is_support:
                graph.add_edge(
                    next_node,
                    f"corner_{(i + 1) % n}",
                    is_boundary_edge=torch.tensor(True),
                )

            # add internal boundary points
            if pattern == "standard":
                internal_boundary = self.nd_linspace(
                    boundary_curve[len(boundary_curve) // 2],
                    centroid,
                    boundary_density + 2,
                )[1:-1]
                prev_node = f"boundary_{i}_{len(boundary_curve) // 2}"
                for j, point in enumerate(internal_boundary):
                    next_node = f"skeleton_{i}_{j}"
                    graph.add_node(
                        next_node,
                        pattern_coords=point,
                        is_support=torch.tensor(False),
                        is_boundary=torch.tensor(False),
                    )
                    graph.add_edge(
                        prev_node, next_node, is_boundary_edge=torch.tensor(False)
                    )
                    prev_node = next_node
                graph.add_edge(
                    next_node, "centroid", is_boundary_edge=torch.tensor(False)
                )
            elif pattern == "singularity":
                internal_boundary = self.nd_linspace(
                    corner_points[i], centroid, boundary_density + 2
                )[1:-1]
                prev_node = f"corner_{i}"
                for j, point in enumerate(internal_boundary):
                    next_node = f"skeleton_{i}_{j}"
                    graph.add_node(
                        next_node,
                        pattern_coords=point,
                        is_support=torch.tensor(False),
                        is_boundary=torch.tensor(False),
                    )
                    graph.add_edge(
                        prev_node, next_node, is_boundary_edge=torch.tensor(False)
                    )
                    prev_node = next_node
                graph.add_edge(
                    next_node, "centroid", is_boundary_edge=torch.tensor(False)
                )
            elif pattern == "opening":
                internal_boundary = self.nd_linspace(
                    corner_points[i],
                    graph.nodes[f"opening_{i}"]["pattern_coords"],
                    boundary_density + 2,
                )[1:-1]
                prev_node = f"corner_{i}"
                for j, point in enumerate(internal_boundary):
                    next_node = f"skeleton_{i}_{j}"
                    graph.add_node(
                        next_node,
                        pattern_coords=point,
                        is_support=torch.tensor(False),
                        is_boundary=torch.tensor(False),
                    )
                    graph.add_edge(
                        prev_node, next_node, is_boundary_edge=torch.tensor(False)
                    )
                    prev_node = next_node
                graph.add_edge(
                    next_node, f"opening_{i}", is_boundary_edge=torch.tensor(False)
                )
                opening_boundary = self.circular_arc(
                    graph.nodes[f"opening_{i}"]["pattern_coords"],
                    graph.nodes[f"opening_{(i + 1) % n}"]["pattern_coords"],
                    centroid,
                    2 * boundary_density + 3,
                )[1:-1]
                prev_node = f"opening_{i}"
                for j, point in enumerate(opening_boundary):
                    next_node = f"opening_skeleton_{i}_{j}"
                    graph.add_node(
                        next_node,
                        pattern_coords=point,
                        is_support=centroid_support,
                        is_boundary=torch.tensor(True),
                    )
                    graph.add_edge(
                        prev_node,
                        next_node,
                        is_boundary_edge=torch.tensor(False),
                        is_opening_edge=torch.tensor(True),
                    )
                    prev_node = next_node
                graph.add_edge(
                    next_node,
                    f"opening_{(i + 1) % n}",
                    is_boundary_edge=torch.tensor(False),
                    is_opening_edge=torch.tensor(True),
                )
            else:
                raise ValueError(f"Invalid pattern: {pattern}")

        # add sub quad meshes
        for i in range(n):
            boundary_1 = [f"skeleton_{i}_{j}" for j in range(boundary_density)]
            boundary_2 = [
                f"boundary_{(i + 1) % n}_{j}" for j in range(0, boundary_density)
            ]
            boundary_3 = [
                f"skeleton_{(i + 1) % n}_{j}" for j in range(boundary_density)
            ]
            boundary_4 = list(
                reversed(
                    [
                        f"boundary_{i}_{j}"
                        for j in range(boundary_density + 1, 2 * boundary_density + 1)
                    ]
                )
            )
            boundary_5 = [
                f"boundary_{i}_{j}" for j in range(0, 2 * boundary_density + 1)
            ]

            # add nodes
            if pattern == "standard":
                for j in range(boundary_density):
                    for k in range(boundary_density):
                        line_1 = self.calculate_line(
                            graph.nodes[boundary_1[j]]["pattern_coords"],
                            graph.nodes[boundary_2[j]]["pattern_coords"],
                        )
                        line_2 = self.calculate_line(
                            graph.nodes[boundary_3[k]]["pattern_coords"],
                            graph.nodes[boundary_4[k]]["pattern_coords"],
                        )
                        intersection = self.line_intersection(line_1, line_2)
                        graph.add_node(
                            f"quad_{i}_{j}_{k}",
                            pattern_coords=intersection,
                            is_support=torch.tensor(False),
                            is_boundary=torch.tensor(False),
                        )
            elif pattern == "singularity":
                for j in range(boundary_density):
                    for k in range(2 * boundary_density + 1):
                        line_1 = self.calculate_line(
                            graph.nodes[boundary_1[j]]["pattern_coords"],
                            graph.nodes[boundary_3[j]]["pattern_coords"],
                        )
                        line_2 = self.calculate_line(
                            graph.nodes[boundary_5[k]]["pattern_coords"], centroid
                        )
                        intersection = self.line_intersection(line_1, line_2)
                        graph.add_node(
                            f"quad_{i}_{j}_{k}",
                            pattern_coords=intersection,
                            is_support=torch.tensor(False),
                            is_boundary=torch.tensor(False),
                        )
            elif pattern == "opening":
                boundary_opening = [
                    f"opening_skeleton_{i}_{j}" for j in range(2 * boundary_density + 1)
                ]
                for j in range(boundary_density):
                    for k in range(2 * boundary_density + 1):
                        line_1 = self.calculate_line(
                            graph.nodes[boundary_1[j]]["pattern_coords"],
                            graph.nodes[boundary_3[j]]["pattern_coords"],
                        )
                        line_2 = self.calculate_line(
                            graph.nodes[boundary_5[k]]["pattern_coords"],
                            graph.nodes[boundary_opening[k]]["pattern_coords"],
                        )
                        intersection = self.line_intersection(line_1, line_2)
                        graph.add_node(
                            f"quad_{i}_{j}_{k}",
                            pattern_coords=intersection,
                            is_support=torch.tensor(False),
                            is_boundary=torch.tensor(False),
                        )
            else:
                raise ValueError(f"Invalid pattern: {pattern}")

            # add edges in first direction
            if pattern == "standard":
                for j in range(boundary_density):
                    prev_node = boundary_2[j]
                    for k in range(boundary_density):
                        next_node = f"quad_{i}_{j}_{k}"
                        graph.add_edge(
                            prev_node, next_node, is_boundary_edge=torch.tensor(False)
                        )
                        prev_node = next_node
                    graph.add_edge(
                        prev_node, boundary_1[j], is_boundary_edge=torch.tensor(False)
                    )
            elif pattern == "singularity":
                for j in range(2 * boundary_density + 1):
                    prev_node = boundary_5[j]
                    for k in range(boundary_density):
                        next_node = f"quad_{i}_{k}_{j}"
                        graph.add_edge(
                            prev_node, next_node, is_boundary_edge=torch.tensor(False)
                        )
                        prev_node = next_node
                    graph.add_edge(
                        prev_node,
                        "centroid",
                        is_boundary_edge=torch.tensor(False),
                    )
            elif pattern == "opening":
                for j in range(2 * boundary_density + 1):
                    prev_node = boundary_5[j]
                    for k in range(boundary_density):
                        next_node = f"quad_{i}_{k}_{j}"
                        graph.add_edge(
                            prev_node, next_node, is_boundary_edge=torch.tensor(False)
                        )
                        prev_node = next_node
                    graph.add_edge(
                        prev_node,
                        boundary_opening[j],
                        is_boundary_edge=torch.tensor(False),
                    )
            else:
                raise ValueError(f"Invalid pattern: {pattern}")

            # add edges in second direction
            if pattern == "standard":
                for j in range(boundary_density):
                    prev_node = boundary_4[j]
                    for k in range(boundary_density):
                        next_node = f"quad_{i}_{k}_{j}"
                        graph.add_edge(
                            prev_node, next_node, is_boundary_edge=torch.tensor(False)
                        )
                        prev_node = next_node
                    graph.add_edge(
                        prev_node, boundary_3[j], is_boundary_edge=torch.tensor(False)
                    )
            elif pattern in ["singularity", "opening"]:
                for j in range(boundary_density):
                    prev_node = boundary_1[j]
                    for k in range(2 * boundary_density + 1):
                        next_node = f"quad_{i}_{j}_{k}"
                        graph.add_edge(
                            prev_node,
                            next_node,
                            is_boundary_edge=torch.tensor(False),
                            ring=torch.tensor(j),
                        )
                        prev_node = next_node
                    graph.add_edge(
                        prev_node,
                        boundary_3[j],
                        is_boundary_edge=torch.tensor(False),
                        ring=torch.tensor(j),
                    )
            else:
                raise ValueError(f"Invalid pattern: {pattern}")

            # add diagonal edges
            if diagonals:
                if pattern != "standard":
                    raise ValueError(
                        "Diagonals are only supported for the standard pattern."
                    )
                prev_node = f"corner_{(i + 1) % n}"
                for j in range(boundary_density):
                    next_node = f"quad_{i}_{j}_{j}"
                    graph.add_edge(
                        prev_node,
                        next_node,
                        is_boundary_edge=torch.tensor(False),
                        is_diagonal_edge=torch.tensor(True),
                    )
                    prev_node = next_node
                graph.add_edge(
                    prev_node,
                    "centroid",
                    is_boundary_edge=torch.tensor(False),
                    is_diagonal_edge=torch.tensor(True),
                )

        load = torch.zeros((graph.num_nodes, 3), dtype=torch.float)
        load[~graph.is_support.view(-1)] = torch.tensor(
            [0.0, 0.0, -1.0], dtype=torch.float
        )
        graph.load = load

        graph.coords = torch.cat(
            [graph.pattern_coords, torch.zeros((graph.pattern_coords.shape[0], 1))],
            dim=1,
        )

        # Compute distance to centroid
        graph.centroid_distance = torch.linalg.norm(
            graph.pattern_coords - centroid, dim=1, keepdim=True
        )

        graph.xy_laplacian_smoothing(is_fixed=graph.is_boundary, verbose=False)
        q_target = q_target_field * torch.ones(graph.num_edges)
        q_target[graph.is_boundary_edge.view(-1)] = q_target_boundary
        graph.q_target = q_target.unsqueeze(1)

        graph = graph.tna(verbose=False)

        if graph.bbox[0, 2] < 0 or graph.bbox[1, 2] > 3.0:
            raise InvalidSampleError(
                f"Z-coordinates out of bounds: ({graph.bbox[0, 2]}, {graph.bbox[1, 2]})"
            )

        if graph.force_density.max() > 0.0:
            raise InvalidSampleError(f"Tension element(s) present: {graph.force_density.max()}")

        return graph

    def is_internal_edge(self, u, v):
        """Check if both nodes of the edge are not on the outer boundary."""
        return self.is_internal_node(u) or self.is_internal_node(v)

    def is_internal_node(self, node):
        """Check if a node is internal (not on the outer boundary)."""
        x, y = node
        return 0 < x < self.n_cell_x and 0 < y < self.n_cell_y

    @staticmethod
    def calculate_line(p1, p2):
        """
        Calculate the line equation (Ax + By + C = 0) from two points.

        Args:
            p1: Tuple of (x1, y1), the first point.
            p2: Tuple of (x2, y2), the second point.

        Returns:
            A tuple (A, B, C) representing the line equation.
        """
        x1, y1 = p1
        x2, y2 = p2

        # Ensure the points are not the same
        if (x1, y1) == (x2, y2):
            raise ValueError("Two points must be distinct to define a line.")

        # Line equation: (y2 - y1)x - (x2 - x1)y + (x2*y1 - x1*y2) = 0
        A = y2 - y1
        B = -(x2 - x1)
        C = x2 * y1 - x1 * y2

        return A, B, C

    @staticmethod
    def line_intersection(line1, line2):
        """
        Calculate the intersection point of two lines.

        Args:
            line1: A tuple (A1, B1, C1) for the first line equation (A1x + B1y + C1 = 0).
            line2: A tuple (A2, B2, C2) for the second line equation (A2x + B2y + C2 = 0).

        Returns:
            A tuple (x, y) representing the intersection point, or None if the lines are parallel.
        """
        A1, B1, C1 = line1
        A2, B2, C2 = line2

        # Calculate the determinant
        det = A1 * B2 - A2 * B1

        # If determinant is zero, lines are parallel or coincident
        if det == 0:
            return None

        # Use Cramer's rule to find the intersection point
        x = (B1 * C2 - B2 * C1) / det
        y = (A2 * C1 - A1 * C2) / det

        return torch.tensor([x, y])

    @staticmethod
    def quadratic_bezier(p0, p1, p2, num_points=100):
        """
        Generates a quadratic Bezier curve.

        Parameters:
            p0 (tuple): The starting point (x0, y0).
            p1 (tuple): The control point (x1, y1).
            p2 (tuple): The ending point (x2, y2).
            num_points (int): Number of points to calculate on the curve.

        Returns:
            list of tuple: Points on the Bezier curve.
        """
        t_values = torch.linspace(0, 1, num_points)
        curve = []

        for t in t_values:
            x = (1 - t) ** 2 * p0[0] + 2 * (1 - t) * t * p1[0] + t**2 * p2[0]
            y = (1 - t) ** 2 * p0[1] + 2 * (1 - t) * t * p1[1] + t**2 * p2[1]
            curve.append(torch.tensor([x, y]))

        return curve

    @staticmethod
    def circular_arc(p0, p1, p2, num_points=100):
        """
        Generates a section of a circle from p0 to p1, using p2 as the center.

        Parameters:
            p0 (tuple): The starting point (x0, y0).
            p1 (tuple): The ending point (x1, y1).
            p2 (tuple): The center of the circle (cx, cy).
            num_points (int): Number of points to calculate on the arc.

        Returns:
            list of tuple: Points on the circular arc.
        """
        # Compute radius from center to p0
        radius = torch.linalg.norm(p0 - p2)

        # Compute angles of p0 and p1 relative to the center
        angle0 = torch.arctan2(p0[1] - p2[1], p0[0] - p2[0])
        angle1 = torch.arctan2(p1[1] - p2[1], p1[0] - p2[0])

        # Ensure angles are in the correct order for a continuous arc
        if angle1 < angle0:
            angle1 += 2 * torch.pi  # Ensure counterclockwise motion

        # Generate arc points
        t_values = torch.linspace(angle0, angle1, num_points)
        arc = []

        for t in t_values:
            x = p2[0] + radius * torch.cos(t)
            y = p2[1] + radius * torch.sin(t)
            arc.append(torch.tensor([x, y]))

        return arc

    @staticmethod
    def compute_optimal_rotation(polygon_angles):
        """
        Evenly space points around a circle and rotate them to best align with ``polygon_angles``.

        Parameters:
            polygon_angles (torch.Tensor): angular positions (radians) of the
                polygon's corners around the centroid.

        Returns:
            torch.Tensor: evenly spaced angles, rotated by the least-squares
            optimal shift to align with ``polygon_angles``.
        """
        circle_angles = torch.linspace(0.0, 2 * math.pi, len(polygon_angles) + 1)[:-1]
        angular_differences = polygon_angles - circle_angles
        theta_shift = torch.arctan2(
            torch.sum(torch.sin(angular_differences)),
            torch.sum(torch.cos(angular_differences)),
        )
        return circle_angles + theta_shift

    @staticmethod
    def polygon_centroid(vertices):
        """
        Calculates the centroid of a polygon.

        Parameters:
            vertices (list of tuple): List of (x, y) coordinates of the polygon vertices.
                                    The polygon should be closed (first vertex == last vertex).

        Returns:
            tuple: (Cx, Cy) coordinates of the centroid.
        """

        n = len(vertices)
        A = 0  # Signed area
        Cx = 0  # Centroid x-coordinate
        Cy = 0  # Centroid y-coordinate

        for i in range(n - 1):
            x0, y0 = vertices[i]
            x1, y1 = vertices[i + 1]
            cross = x0 * y1 - x1 * y0
            A += cross
            Cx += (x0 + x1) * cross
            Cy += (y0 + y1) * cross

        A *= 0.5
        Cx /= 6 * A
        Cy /= 6 * A

        return torch.tensor([Cx, Cy])

    @staticmethod
    def sample_rectangle(width, height=None, square=False):
        """
        Randomly samples a rectangle with a minimum aspect ratio of 1:2.

        Returns:
            list of tuple: List of (x, y) coordinates of the rectangle vertices.
        """
        if square:
            height = width

        x0, y0 = -0.5 * width, -0.5 * height
        x1, y1 = 0.5 * width, 0.5 * height

        return [
            torch.tensor([x0, y0]),
            torch.tensor([x1, y0]),
            torch.tensor([x1, y1]),
            torch.tensor([x0, y1]),
        ]

    @staticmethod
    def sample_unit_circle(n, angles=None):
        """
        Randomly samples n points on a unit circle, ensuring a minimum angle between points.

        Parameters:
            n (int): Number of points to sample.
            min_angle (float): Minimum angular separation between points (in radians).

        Returns:
            list of tuple: Randomly sampled and sorted points on the unit circle.
        """
        if n == 0:
            return []

        points = [
            torch.tensor([torch.cos(angle), torch.sin(angle)]) for angle in angles
        ]
        return points

    @staticmethod
    def nd_linspace(start: torch.tensor, end: torch.tensor, num_points: int):
        """Linearly interpolate ``num_points`` points (inclusive) between two n-dimensional points."""
        t = torch.linspace(0, 1, num_points).view(-1, 1)
        return start + t * (end - start)

calculate_line(p1, p2) staticmethod

Calculate the line equation (Ax + By + C = 0) from two points.

Parameters:

Name Type Description Default
p1

Tuple of (x1, y1), the first point.

required
p2

Tuple of (x2, y2), the second point.

required

Returns:

Type Description

A tuple (A, B, C) representing the line equation.

Source code in src/torch_structure/generators/gridshell.py
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
@staticmethod
def calculate_line(p1, p2):
    """
    Calculate the line equation (Ax + By + C = 0) from two points.

    Args:
        p1: Tuple of (x1, y1), the first point.
        p2: Tuple of (x2, y2), the second point.

    Returns:
        A tuple (A, B, C) representing the line equation.
    """
    x1, y1 = p1
    x2, y2 = p2

    # Ensure the points are not the same
    if (x1, y1) == (x2, y2):
        raise ValueError("Two points must be distinct to define a line.")

    # Line equation: (y2 - y1)x - (x2 - x1)y + (x2*y1 - x1*y2) = 0
    A = y2 - y1
    B = -(x2 - x1)
    C = x2 * y1 - x1 * y2

    return A, B, C

circular_arc(p0, p1, p2, num_points=100) staticmethod

Generates a section of a circle from p0 to p1, using p2 as the center.

Parameters:

Name Type Description Default
p0 tuple

The starting point (x0, y0).

required
p1 tuple

The ending point (x1, y1).

required
p2 tuple

The center of the circle (cx, cy).

required
num_points int

Number of points to calculate on the arc.

100

Returns:

Type Description

list of tuple: Points on the circular arc.

Source code in src/torch_structure/generators/gridshell.py
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
@staticmethod
def circular_arc(p0, p1, p2, num_points=100):
    """
    Generates a section of a circle from p0 to p1, using p2 as the center.

    Parameters:
        p0 (tuple): The starting point (x0, y0).
        p1 (tuple): The ending point (x1, y1).
        p2 (tuple): The center of the circle (cx, cy).
        num_points (int): Number of points to calculate on the arc.

    Returns:
        list of tuple: Points on the circular arc.
    """
    # Compute radius from center to p0
    radius = torch.linalg.norm(p0 - p2)

    # Compute angles of p0 and p1 relative to the center
    angle0 = torch.arctan2(p0[1] - p2[1], p0[0] - p2[0])
    angle1 = torch.arctan2(p1[1] - p2[1], p1[0] - p2[0])

    # Ensure angles are in the correct order for a continuous arc
    if angle1 < angle0:
        angle1 += 2 * torch.pi  # Ensure counterclockwise motion

    # Generate arc points
    t_values = torch.linspace(angle0, angle1, num_points)
    arc = []

    for t in t_values:
        x = p2[0] + radius * torch.cos(t)
        y = p2[1] + radius * torch.sin(t)
        arc.append(torch.tensor([x, y]))

    return arc

compute_optimal_rotation(polygon_angles) staticmethod

Evenly space points around a circle and rotate them to best align with polygon_angles.

Parameters:

Name Type Description Default
polygon_angles Tensor

angular positions (radians) of the polygon's corners around the centroid.

required

Returns:

Type Description

torch.Tensor: evenly spaced angles, rotated by the least-squares

optimal shift to align with polygon_angles.

Source code in src/torch_structure/generators/gridshell.py
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
@staticmethod
def compute_optimal_rotation(polygon_angles):
    """
    Evenly space points around a circle and rotate them to best align with ``polygon_angles``.

    Parameters:
        polygon_angles (torch.Tensor): angular positions (radians) of the
            polygon's corners around the centroid.

    Returns:
        torch.Tensor: evenly spaced angles, rotated by the least-squares
        optimal shift to align with ``polygon_angles``.
    """
    circle_angles = torch.linspace(0.0, 2 * math.pi, len(polygon_angles) + 1)[:-1]
    angular_differences = polygon_angles - circle_angles
    theta_shift = torch.arctan2(
        torch.sum(torch.sin(angular_differences)),
        torch.sum(torch.cos(angular_differences)),
    )
    return circle_angles + theta_shift

generate(n, boundary_density, pattern, diagonals, centroid_support, unsupported_boundaries, rectangle, square, curve_boundaries, circle, q_target_field, q_target_boundary, opening_radius, boundary_support_list, boundary_curvature_list, rectangle_width, rectangle_height, square_size, corner_angle_list)

Build the boundary, mesh, and (for "opening") central ring, then form-find with Laplacian smoothing + TNA.

Returns:

Name Type Description
StructData

the form-found gridshell.

Raises:

Type Description
InvalidSampleError

if the resulting geometry's z-extent is out of bounds, or if any element is in tension.

Source code in src/torch_structure/generators/gridshell.py
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
def generate(
    self,
    n,
    boundary_density,
    pattern,
    diagonals,
    centroid_support,
    unsupported_boundaries,
    rectangle,
    square,
    curve_boundaries,
    circle,
    q_target_field,
    q_target_boundary,
    opening_radius,
    boundary_support_list,
    boundary_curvature_list,
    rectangle_width,
    rectangle_height,
    square_size,
    corner_angle_list,
):
    """Build the boundary, mesh, and (for "opening") central ring, then form-find with Laplacian smoothing + TNA.

    Returns:
        StructData: the form-found gridshell.

    Raises:
        InvalidSampleError: if the resulting geometry's z-extent is out
            of bounds, or if any element is in tension.
    """
    graph = StructData(
        node_attrs=self.node_attrs,
        edge_attrs=self.edge_attrs,
        default_attrs=self.default_attrs,
    )

    if rectangle:
        if square:
            corner_points = self.sample_rectangle(width=square_size, square=True)
        else:
            corner_points = self.sample_rectangle(
                width=rectangle_width, height=rectangle_height, square=False
            )
    elif circle:
        corner_points = self.sample_unit_circle(
            n, angles=torch.linspace(0, 2 * math.pi, n + 1)[:-1]
        )
    else:
        corner_points = self.sample_unit_circle(n, angles=corner_angle_list)
    looped_corner_points = corner_points + [corner_points[0]]
    centroid = self.polygon_centroid(looped_corner_points)
    if pattern in ["standard", "singularity"]:
        graph.add_node(
            "centroid",
            pattern_coords=centroid,
            is_support=centroid_support,
            is_boundary=torch.tensor(False),
        )
    elif pattern == "opening":
        angles = torch.zeros(n)
        for i in range(n):
            angles[i] = torch.arctan2(
                corner_points[i][1] - centroid[1], corner_points[i][0] - centroid[0]
            )
        circle_angles = self.compute_optimal_rotation(angles)
        for i in range(n):
            pattern_coord = (
                torch.tensor(
                    [torch.cos(circle_angles[i]), torch.sin(circle_angles[i])]
                )
                * opening_radius
                + centroid
            )
            graph.add_node(
                f"opening_{i}",
                pattern_coords=pattern_coord,
                is_support=centroid_support,
                is_boundary=torch.tensor(True),
            )

    # add corner points
    for i, point in enumerate(corner_points):
        graph.add_node(
            f"corner_{i}",
            pattern_coords=point,
            is_support=torch.tensor(True),
            is_boundary=torch.tensor(True),
        )

    # add mesh skeleton points
    for i in range(n):
        is_support = boundary_support_list[i]
        start_boundary, end_boundary = (
            looped_corner_points[i],
            looped_corner_points[i + 1],
        )
        center_boundary = 0.5 * (start_boundary + end_boundary)
        curvature_param = boundary_curvature_list[i]
        control_point = center_boundary + curvature_param * (
            centroid - center_boundary
        )

        # add external boundary points
        if circle:
            boundary_curve = self.circular_arc(
                start_boundary, end_boundary, centroid, boundary_density * 2 + 3
            )[1:-1]
        else:
            boundary_curve = self.quadratic_bezier(
                start_boundary,
                control_point,
                end_boundary,
                boundary_density * 2 + 3,
            )[1:-1]
        prev_node = f"corner_{i}"

        for j, point in enumerate(boundary_curve):
            next_node = f"boundary_{i}_{j}"
            graph.add_node(
                next_node,
                pattern_coords=point,
                is_support=is_support,
                is_boundary=torch.tensor(True),
            )
            if not is_support:
                graph.add_edge(
                    prev_node, next_node, is_boundary_edge=torch.tensor(True)
                )
            prev_node = next_node
        if not is_support:
            graph.add_edge(
                next_node,
                f"corner_{(i + 1) % n}",
                is_boundary_edge=torch.tensor(True),
            )

        # add internal boundary points
        if pattern == "standard":
            internal_boundary = self.nd_linspace(
                boundary_curve[len(boundary_curve) // 2],
                centroid,
                boundary_density + 2,
            )[1:-1]
            prev_node = f"boundary_{i}_{len(boundary_curve) // 2}"
            for j, point in enumerate(internal_boundary):
                next_node = f"skeleton_{i}_{j}"
                graph.add_node(
                    next_node,
                    pattern_coords=point,
                    is_support=torch.tensor(False),
                    is_boundary=torch.tensor(False),
                )
                graph.add_edge(
                    prev_node, next_node, is_boundary_edge=torch.tensor(False)
                )
                prev_node = next_node
            graph.add_edge(
                next_node, "centroid", is_boundary_edge=torch.tensor(False)
            )
        elif pattern == "singularity":
            internal_boundary = self.nd_linspace(
                corner_points[i], centroid, boundary_density + 2
            )[1:-1]
            prev_node = f"corner_{i}"
            for j, point in enumerate(internal_boundary):
                next_node = f"skeleton_{i}_{j}"
                graph.add_node(
                    next_node,
                    pattern_coords=point,
                    is_support=torch.tensor(False),
                    is_boundary=torch.tensor(False),
                )
                graph.add_edge(
                    prev_node, next_node, is_boundary_edge=torch.tensor(False)
                )
                prev_node = next_node
            graph.add_edge(
                next_node, "centroid", is_boundary_edge=torch.tensor(False)
            )
        elif pattern == "opening":
            internal_boundary = self.nd_linspace(
                corner_points[i],
                graph.nodes[f"opening_{i}"]["pattern_coords"],
                boundary_density + 2,
            )[1:-1]
            prev_node = f"corner_{i}"
            for j, point in enumerate(internal_boundary):
                next_node = f"skeleton_{i}_{j}"
                graph.add_node(
                    next_node,
                    pattern_coords=point,
                    is_support=torch.tensor(False),
                    is_boundary=torch.tensor(False),
                )
                graph.add_edge(
                    prev_node, next_node, is_boundary_edge=torch.tensor(False)
                )
                prev_node = next_node
            graph.add_edge(
                next_node, f"opening_{i}", is_boundary_edge=torch.tensor(False)
            )
            opening_boundary = self.circular_arc(
                graph.nodes[f"opening_{i}"]["pattern_coords"],
                graph.nodes[f"opening_{(i + 1) % n}"]["pattern_coords"],
                centroid,
                2 * boundary_density + 3,
            )[1:-1]
            prev_node = f"opening_{i}"
            for j, point in enumerate(opening_boundary):
                next_node = f"opening_skeleton_{i}_{j}"
                graph.add_node(
                    next_node,
                    pattern_coords=point,
                    is_support=centroid_support,
                    is_boundary=torch.tensor(True),
                )
                graph.add_edge(
                    prev_node,
                    next_node,
                    is_boundary_edge=torch.tensor(False),
                    is_opening_edge=torch.tensor(True),
                )
                prev_node = next_node
            graph.add_edge(
                next_node,
                f"opening_{(i + 1) % n}",
                is_boundary_edge=torch.tensor(False),
                is_opening_edge=torch.tensor(True),
            )
        else:
            raise ValueError(f"Invalid pattern: {pattern}")

    # add sub quad meshes
    for i in range(n):
        boundary_1 = [f"skeleton_{i}_{j}" for j in range(boundary_density)]
        boundary_2 = [
            f"boundary_{(i + 1) % n}_{j}" for j in range(0, boundary_density)
        ]
        boundary_3 = [
            f"skeleton_{(i + 1) % n}_{j}" for j in range(boundary_density)
        ]
        boundary_4 = list(
            reversed(
                [
                    f"boundary_{i}_{j}"
                    for j in range(boundary_density + 1, 2 * boundary_density + 1)
                ]
            )
        )
        boundary_5 = [
            f"boundary_{i}_{j}" for j in range(0, 2 * boundary_density + 1)
        ]

        # add nodes
        if pattern == "standard":
            for j in range(boundary_density):
                for k in range(boundary_density):
                    line_1 = self.calculate_line(
                        graph.nodes[boundary_1[j]]["pattern_coords"],
                        graph.nodes[boundary_2[j]]["pattern_coords"],
                    )
                    line_2 = self.calculate_line(
                        graph.nodes[boundary_3[k]]["pattern_coords"],
                        graph.nodes[boundary_4[k]]["pattern_coords"],
                    )
                    intersection = self.line_intersection(line_1, line_2)
                    graph.add_node(
                        f"quad_{i}_{j}_{k}",
                        pattern_coords=intersection,
                        is_support=torch.tensor(False),
                        is_boundary=torch.tensor(False),
                    )
        elif pattern == "singularity":
            for j in range(boundary_density):
                for k in range(2 * boundary_density + 1):
                    line_1 = self.calculate_line(
                        graph.nodes[boundary_1[j]]["pattern_coords"],
                        graph.nodes[boundary_3[j]]["pattern_coords"],
                    )
                    line_2 = self.calculate_line(
                        graph.nodes[boundary_5[k]]["pattern_coords"], centroid
                    )
                    intersection = self.line_intersection(line_1, line_2)
                    graph.add_node(
                        f"quad_{i}_{j}_{k}",
                        pattern_coords=intersection,
                        is_support=torch.tensor(False),
                        is_boundary=torch.tensor(False),
                    )
        elif pattern == "opening":
            boundary_opening = [
                f"opening_skeleton_{i}_{j}" for j in range(2 * boundary_density + 1)
            ]
            for j in range(boundary_density):
                for k in range(2 * boundary_density + 1):
                    line_1 = self.calculate_line(
                        graph.nodes[boundary_1[j]]["pattern_coords"],
                        graph.nodes[boundary_3[j]]["pattern_coords"],
                    )
                    line_2 = self.calculate_line(
                        graph.nodes[boundary_5[k]]["pattern_coords"],
                        graph.nodes[boundary_opening[k]]["pattern_coords"],
                    )
                    intersection = self.line_intersection(line_1, line_2)
                    graph.add_node(
                        f"quad_{i}_{j}_{k}",
                        pattern_coords=intersection,
                        is_support=torch.tensor(False),
                        is_boundary=torch.tensor(False),
                    )
        else:
            raise ValueError(f"Invalid pattern: {pattern}")

        # add edges in first direction
        if pattern == "standard":
            for j in range(boundary_density):
                prev_node = boundary_2[j]
                for k in range(boundary_density):
                    next_node = f"quad_{i}_{j}_{k}"
                    graph.add_edge(
                        prev_node, next_node, is_boundary_edge=torch.tensor(False)
                    )
                    prev_node = next_node
                graph.add_edge(
                    prev_node, boundary_1[j], is_boundary_edge=torch.tensor(False)
                )
        elif pattern == "singularity":
            for j in range(2 * boundary_density + 1):
                prev_node = boundary_5[j]
                for k in range(boundary_density):
                    next_node = f"quad_{i}_{k}_{j}"
                    graph.add_edge(
                        prev_node, next_node, is_boundary_edge=torch.tensor(False)
                    )
                    prev_node = next_node
                graph.add_edge(
                    prev_node,
                    "centroid",
                    is_boundary_edge=torch.tensor(False),
                )
        elif pattern == "opening":
            for j in range(2 * boundary_density + 1):
                prev_node = boundary_5[j]
                for k in range(boundary_density):
                    next_node = f"quad_{i}_{k}_{j}"
                    graph.add_edge(
                        prev_node, next_node, is_boundary_edge=torch.tensor(False)
                    )
                    prev_node = next_node
                graph.add_edge(
                    prev_node,
                    boundary_opening[j],
                    is_boundary_edge=torch.tensor(False),
                )
        else:
            raise ValueError(f"Invalid pattern: {pattern}")

        # add edges in second direction
        if pattern == "standard":
            for j in range(boundary_density):
                prev_node = boundary_4[j]
                for k in range(boundary_density):
                    next_node = f"quad_{i}_{k}_{j}"
                    graph.add_edge(
                        prev_node, next_node, is_boundary_edge=torch.tensor(False)
                    )
                    prev_node = next_node
                graph.add_edge(
                    prev_node, boundary_3[j], is_boundary_edge=torch.tensor(False)
                )
        elif pattern in ["singularity", "opening"]:
            for j in range(boundary_density):
                prev_node = boundary_1[j]
                for k in range(2 * boundary_density + 1):
                    next_node = f"quad_{i}_{j}_{k}"
                    graph.add_edge(
                        prev_node,
                        next_node,
                        is_boundary_edge=torch.tensor(False),
                        ring=torch.tensor(j),
                    )
                    prev_node = next_node
                graph.add_edge(
                    prev_node,
                    boundary_3[j],
                    is_boundary_edge=torch.tensor(False),
                    ring=torch.tensor(j),
                )
        else:
            raise ValueError(f"Invalid pattern: {pattern}")

        # add diagonal edges
        if diagonals:
            if pattern != "standard":
                raise ValueError(
                    "Diagonals are only supported for the standard pattern."
                )
            prev_node = f"corner_{(i + 1) % n}"
            for j in range(boundary_density):
                next_node = f"quad_{i}_{j}_{j}"
                graph.add_edge(
                    prev_node,
                    next_node,
                    is_boundary_edge=torch.tensor(False),
                    is_diagonal_edge=torch.tensor(True),
                )
                prev_node = next_node
            graph.add_edge(
                prev_node,
                "centroid",
                is_boundary_edge=torch.tensor(False),
                is_diagonal_edge=torch.tensor(True),
            )

    load = torch.zeros((graph.num_nodes, 3), dtype=torch.float)
    load[~graph.is_support.view(-1)] = torch.tensor(
        [0.0, 0.0, -1.0], dtype=torch.float
    )
    graph.load = load

    graph.coords = torch.cat(
        [graph.pattern_coords, torch.zeros((graph.pattern_coords.shape[0], 1))],
        dim=1,
    )

    # Compute distance to centroid
    graph.centroid_distance = torch.linalg.norm(
        graph.pattern_coords - centroid, dim=1, keepdim=True
    )

    graph.xy_laplacian_smoothing(is_fixed=graph.is_boundary, verbose=False)
    q_target = q_target_field * torch.ones(graph.num_edges)
    q_target[graph.is_boundary_edge.view(-1)] = q_target_boundary
    graph.q_target = q_target.unsqueeze(1)

    graph = graph.tna(verbose=False)

    if graph.bbox[0, 2] < 0 or graph.bbox[1, 2] > 3.0:
        raise InvalidSampleError(
            f"Z-coordinates out of bounds: ({graph.bbox[0, 2]}, {graph.bbox[1, 2]})"
        )

    if graph.force_density.max() > 0.0:
        raise InvalidSampleError(f"Tension element(s) present: {graph.force_density.max()}")

    return graph

is_internal_edge(u, v)

Check if both nodes of the edge are not on the outer boundary.

Source code in src/torch_structure/generators/gridshell.py
655
656
657
def is_internal_edge(self, u, v):
    """Check if both nodes of the edge are not on the outer boundary."""
    return self.is_internal_node(u) or self.is_internal_node(v)

is_internal_node(node)

Check if a node is internal (not on the outer boundary).

Source code in src/torch_structure/generators/gridshell.py
659
660
661
662
def is_internal_node(self, node):
    """Check if a node is internal (not on the outer boundary)."""
    x, y = node
    return 0 < x < self.n_cell_x and 0 < y < self.n_cell_y

line_intersection(line1, line2) staticmethod

Calculate the intersection point of two lines.

Parameters:

Name Type Description Default
line1

A tuple (A1, B1, C1) for the first line equation (A1x + B1y + C1 = 0).

required
line2

A tuple (A2, B2, C2) for the second line equation (A2x + B2y + C2 = 0).

required

Returns:

Type Description

A tuple (x, y) representing the intersection point, or None if the lines are parallel.

Source code in src/torch_structure/generators/gridshell.py
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
@staticmethod
def line_intersection(line1, line2):
    """
    Calculate the intersection point of two lines.

    Args:
        line1: A tuple (A1, B1, C1) for the first line equation (A1x + B1y + C1 = 0).
        line2: A tuple (A2, B2, C2) for the second line equation (A2x + B2y + C2 = 0).

    Returns:
        A tuple (x, y) representing the intersection point, or None if the lines are parallel.
    """
    A1, B1, C1 = line1
    A2, B2, C2 = line2

    # Calculate the determinant
    det = A1 * B2 - A2 * B1

    # If determinant is zero, lines are parallel or coincident
    if det == 0:
        return None

    # Use Cramer's rule to find the intersection point
    x = (B1 * C2 - B2 * C1) / det
    y = (A2 * C1 - A1 * C2) / det

    return torch.tensor([x, y])

nd_linspace(start, end, num_points) staticmethod

Linearly interpolate num_points points (inclusive) between two n-dimensional points.

Source code in src/torch_structure/generators/gridshell.py
872
873
874
875
876
@staticmethod
def nd_linspace(start: torch.tensor, end: torch.tensor, num_points: int):
    """Linearly interpolate ``num_points`` points (inclusive) between two n-dimensional points."""
    t = torch.linspace(0, 1, num_points).view(-1, 1)
    return start + t * (end - start)

polygon_centroid(vertices) staticmethod

Calculates the centroid of a polygon.

Parameters:

Name Type Description Default
vertices list of tuple

List of (x, y) coordinates of the polygon vertices. The polygon should be closed (first vertex == last vertex).

required

Returns:

Name Type Description
tuple

(Cx, Cy) coordinates of the centroid.

Source code in src/torch_structure/generators/gridshell.py
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
@staticmethod
def polygon_centroid(vertices):
    """
    Calculates the centroid of a polygon.

    Parameters:
        vertices (list of tuple): List of (x, y) coordinates of the polygon vertices.
                                The polygon should be closed (first vertex == last vertex).

    Returns:
        tuple: (Cx, Cy) coordinates of the centroid.
    """

    n = len(vertices)
    A = 0  # Signed area
    Cx = 0  # Centroid x-coordinate
    Cy = 0  # Centroid y-coordinate

    for i in range(n - 1):
        x0, y0 = vertices[i]
        x1, y1 = vertices[i + 1]
        cross = x0 * y1 - x1 * y0
        A += cross
        Cx += (x0 + x1) * cross
        Cy += (y0 + y1) * cross

    A *= 0.5
    Cx /= 6 * A
    Cy /= 6 * A

    return torch.tensor([Cx, Cy])

quadratic_bezier(p0, p1, p2, num_points=100) staticmethod

Generates a quadratic Bezier curve.

Parameters:

Name Type Description Default
p0 tuple

The starting point (x0, y0).

required
p1 tuple

The control point (x1, y1).

required
p2 tuple

The ending point (x2, y2).

required
num_points int

Number of points to calculate on the curve.

100

Returns:

Type Description

list of tuple: Points on the Bezier curve.

Source code in src/torch_structure/generators/gridshell.py
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
@staticmethod
def quadratic_bezier(p0, p1, p2, num_points=100):
    """
    Generates a quadratic Bezier curve.

    Parameters:
        p0 (tuple): The starting point (x0, y0).
        p1 (tuple): The control point (x1, y1).
        p2 (tuple): The ending point (x2, y2).
        num_points (int): Number of points to calculate on the curve.

    Returns:
        list of tuple: Points on the Bezier curve.
    """
    t_values = torch.linspace(0, 1, num_points)
    curve = []

    for t in t_values:
        x = (1 - t) ** 2 * p0[0] + 2 * (1 - t) * t * p1[0] + t**2 * p2[0]
        y = (1 - t) ** 2 * p0[1] + 2 * (1 - t) * t * p1[1] + t**2 * p2[1]
        curve.append(torch.tensor([x, y]))

    return curve

sample_input(n=None, boundary_density=None, pattern=None, diagonals=None, centroid_support=None, unsupported_boundaries=True, rectangle=False, square=False, curve_boundaries=True, circle=False, q_target_field=None, q_target_boundary=None, opening_radius=None, boundary_support_list=None, boundary_curvature_list=None, rectangle_width=None, rectangle_height=None, square_size=None, corner_angle_list=None)

Sample any unspecified generation parameters, deriving dependent defaults where relevant.

Each parameter defaults to None, meaning "sample randomly"; an explicit value passed via overrides (see BaseGenerator) is left unchanged. Returns a dict of all resolved parameters, to be passed to generate.

Source code in src/torch_structure/generators/gridshell.py
 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
def sample_input(
    self,
    n=None,
    boundary_density=None,
    pattern=None,
    diagonals=None,
    centroid_support=None,
    unsupported_boundaries=True,
    rectangle=False,
    square=False,
    curve_boundaries=True,
    circle=False,
    q_target_field=None,
    q_target_boundary=None,
    opening_radius=None,
    boundary_support_list=None,
    boundary_curvature_list=None,
    rectangle_width=None,
    rectangle_height=None,
    square_size=None,
    corner_angle_list=None,
):
    """Sample any unspecified generation parameters, deriving dependent defaults where relevant.

    Each parameter defaults to ``None``, meaning "sample randomly"; an
    explicit value passed via ``overrides`` (see
    [BaseGenerator][torch_structure.generators.base_generator.BaseGenerator])
    is left unchanged. Returns a dict of all resolved parameters, to be
    passed to [generate][torch_structure.generators.gridshell.GridShellGenerator.generate].
    """
    if n is None:
        if rectangle or square:
            n = 4
        else:
            n = np.random.randint(3, 7)
    if boundary_density is None:
        boundary_density = np.random.randint(3, 8)
    if centroid_support is None:
        centroid_support = np.random.choice([True, False], p=[0.3, 0.7])
    if pattern is None:
        pattern = (
            np.random.choice(["standard", "singularity", "opening"])
            if centroid_support
            else "standard"
        )
    if diagonals is None:
        diagonals = (
            np.random.choice([True, False]) if pattern == "standard" else False
        )
    if q_target_field is None:
        q_target_field = np.random.uniform(-15.0, -25.0)
    if q_target_boundary is None:
        q_target_boundary = np.random.uniform(-80.0, -120.0)
    if opening_radius is None:
        if pattern == "opening":
            opening_radius = np.random.rand() * 0.05 + 0.1
        else:
            opening_radius = np.nan
    if boundary_support_list is None:
        if unsupported_boundaries:
            boundary_support_list = np.random.choice(
                [True, False], size=n, p=[0.5, 0.5]
            )
        else:
            boundary_support_list = [True] * n
    if boundary_curvature_list is None:
        if curve_boundaries:
            boundary_curvature_list = np.empty(n)
            boundary_curvature_list[boundary_support_list] = (
                np.random.rand(boundary_support_list.sum()) - 0.5
            )
            boundary_curvature_list[~boundary_support_list] = (
                np.random.rand((~boundary_support_list).sum()) * 0.2 + 0.3
            )
        else:
            boundary_curvature_list = np.zeros(n)
    if rectangle_width is None:
        if rectangle:
            rectangle_width = torch.rand(1) * 0.9 + 0.1
        else:
            rectangle_width = torch.nan
    if rectangle_height is None:
        if rectangle:
            rectangle_height = torch.rand(1) * 0.9 + 0.1
        else:
            rectangle_height = torch.nan
    if square_size is None:
        if square:
            square_size = torch.rand(1) * 0.9 + 0.1
        else:
            square_size = torch.nan
    if corner_angle_list is None:
        min_angle = torch.tensor(math.pi) / 8
        corner_angle_list = []
        while len(corner_angle_list) < n:
            angle = (torch.rand(1) * 2 * math.pi).item()
            # Check if the new angle is far enough from all others
            if all(
                abs((angle - a + math.pi) % (2 * math.pi) - math.pi) >= min_angle
                for a in corner_angle_list
            ):
                corner_angle_list.append(angle)
        corner_angle_list.sort()

    input = {
        "n": n,
        "boundary_density": boundary_density,
        "pattern": pattern,
        "diagonals": torch.tensor(diagonals),
        "centroid_support": torch.tensor(centroid_support),
        "unsupported_boundaries": torch.tensor(unsupported_boundaries),
        "rectangle": torch.tensor(rectangle),
        "square": torch.tensor(square),
        "curve_boundaries": torch.tensor(curve_boundaries),
        "circle": torch.tensor(circle),
        "q_target_field": torch.tensor(q_target_field, dtype=torch.float),
        "q_target_boundary": torch.tensor(q_target_boundary, dtype=torch.float),
        "opening_radius": torch.tensor(opening_radius, dtype=torch.float),
        "boundary_support_list": torch.tensor(
            boundary_support_list, dtype=torch.bool
        ),
        "boundary_curvature_list": torch.tensor(
            boundary_curvature_list, dtype=torch.float
        ),
        "rectangle_width": torch.tensor(rectangle_width, dtype=torch.float),
        "rectangle_height": torch.tensor(rectangle_height, dtype=torch.float),
        "square_size": torch.tensor(square_size, dtype=torch.float),
        "corner_angle_list": torch.tensor(corner_angle_list, dtype=torch.float),
    }

    return input

sample_rectangle(width, height=None, square=False) staticmethod

Randomly samples a rectangle with a minimum aspect ratio of 1:2.

Returns:

Type Description

list of tuple: List of (x, y) coordinates of the rectangle vertices.

Source code in src/torch_structure/generators/gridshell.py
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
@staticmethod
def sample_rectangle(width, height=None, square=False):
    """
    Randomly samples a rectangle with a minimum aspect ratio of 1:2.

    Returns:
        list of tuple: List of (x, y) coordinates of the rectangle vertices.
    """
    if square:
        height = width

    x0, y0 = -0.5 * width, -0.5 * height
    x1, y1 = 0.5 * width, 0.5 * height

    return [
        torch.tensor([x0, y0]),
        torch.tensor([x1, y0]),
        torch.tensor([x1, y1]),
        torch.tensor([x0, y1]),
    ]

sample_unit_circle(n, angles=None) staticmethod

Randomly samples n points on a unit circle, ensuring a minimum angle between points.

Parameters:

Name Type Description Default
n int

Number of points to sample.

required
min_angle float

Minimum angular separation between points (in radians).

required

Returns:

Type Description

list of tuple: Randomly sampled and sorted points on the unit circle.

Source code in src/torch_structure/generators/gridshell.py
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
@staticmethod
def sample_unit_circle(n, angles=None):
    """
    Randomly samples n points on a unit circle, ensuring a minimum angle between points.

    Parameters:
        n (int): Number of points to sample.
        min_angle (float): Minimum angular separation between points (in radians).

    Returns:
        list of tuple: Randomly sampled and sorted points on the unit circle.
    """
    if n == 0:
        return []

    points = [
        torch.tensor([torch.cos(angle), torch.sin(angle)]) for angle in angles
    ]
    return points

validate_input(n, boundary_density, pattern, diagonals, centroid_support, unsupported_boundaries, rectangle, square, curve_boundaries, circle, q_target_field, q_target_boundary, opening_radius, boundary_support_list, boundary_curvature_list, rectangle_width, rectangle_height, square_size, corner_angle_list)

Validate the boundary/pattern parameters; raises ValueError if they are inconsistent.

Source code in src/torch_structure/generators/gridshell.py
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
def validate_input(
    self,
    n,
    boundary_density,
    pattern,
    diagonals,
    centroid_support,
    unsupported_boundaries,
    rectangle,
    square,
    curve_boundaries,
    circle,
    q_target_field,
    q_target_boundary,
    opening_radius,
    boundary_support_list,
    boundary_curvature_list,
    rectangle_width,
    rectangle_height,
    square_size,
    corner_angle_list,
):
    """Validate the boundary/pattern parameters; raises ``ValueError`` if they are inconsistent."""
    if pattern not in ["standard", "singularity", "opening"]:
        raise ValueError(f"Invalid pattern: {pattern}")
    if rectangle and n != 4:
        raise ValueError("Rectangle pattern requires n=4.")
    if square and not rectangle:
        raise ValueError("Square pattern requires rectangle=True.")
    if circle and pattern not in ["singularity", "opening"]:
        raise ValueError("Circle requires pattern='singularity' or 'opening'.")
    if circle and (square or rectangle):
        raise ValueError("Circle is incompatible with square or rectangle")
    if pattern == "opening" and not centroid_support:
        raise ValueError("Opening pattern requires centroid support.")