-
Notifications
You must be signed in to change notification settings - Fork 187
/
path.py
1498 lines (1233 loc) · 48 KB
/
path.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
"""You can define a path with a list of points combined with a cross-section.
A path can be extruded using any CrossSection returning a Component
The CrossSection defines the layer numbers, widths and offsets
Adapted from PHIDL https://github.com/amccaugh/phidl/ by Adam McCaughan
"""
from __future__ import annotations
import hashlib
import math
import warnings
from collections.abc import Callable
import numpy as np
from numpy import mod, pi
from gdsfactory.cell import cell
from gdsfactory.component import Component
from gdsfactory.component_layout import (
_GeometryHelper,
_parse_move,
_reflect_points,
_rotate_points,
)
from gdsfactory.cross_section import CrossSection, Section, Transition
from gdsfactory.typings import (
ComponentSpec,
Coordinates,
CrossSectionSpec,
Float2,
LayerSpec,
WidthTypes,
)
def _simplify(points, tolerance):
import shapely.geometry as sg
ls = sg.LineString(points)
ls_simple = ls.simplify(tolerance=tolerance)
return np.asarray(ls_simple.coords)
class Path(_GeometryHelper):
"""Path object for smooth Paths. You can extrude a Path with a CrossSection \
to create a Component.
Parameters:
path: array-like[N][2], Path, or list of Paths.
"""
def __init__(self, path=None) -> None:
"""Creates an empty path."""
self.points = np.array([[0, 0]], dtype=np.float64)
self.start_angle = 0
self.end_angle = 0
self.info = {}
if path is not None:
# If array[N][2]
if (
(np.asarray(path, dtype=object).ndim == 2)
and np.issubdtype(np.array(path).dtype, np.number)
and (np.shape(path)[1] == 2)
):
self.points = np.array(path, dtype=np.float64)
nx1, ny1 = self.points[1] - self.points[0]
self.start_angle = np.arctan2(ny1, nx1) / np.pi * 180
nx2, ny2 = self.points[-1] - self.points[-2]
self.end_angle = np.arctan2(ny2, nx2) / np.pi * 180
elif isinstance(path, Path):
self.points = np.array(path.points, dtype=np.float64)
self.start_angle = path.start_angle
self.end_angle = path.end_angle
self.info = {}
elif np.asarray(path, dtype=object).size > 1:
self.append(path)
else:
raise ValueError(
"Path() the `path` argument must be either blank, a path Object, "
"an array-like[N][2] list of points, or a list of these"
)
def __repr__(self) -> str:
"""Returns path points."""
return (
f"Path(start_angle={self.start_angle}, "
f"end_angle={self.end_angle}, "
f"points={self.points})"
)
def __len__(self) -> int:
"""Returns path points."""
return len(self.points)
def __iadd__(self, path_or_points) -> Path:
"""Adds points to current path."""
return self.append(path_or_points)
def __add__(self, path) -> Path:
"""Returns new path concatenating current and new path."""
new = self.copy()
return new.append(path)
@property
def bbox(self):
"""Returns the bounding box of the Path."""
bbox = [
(np.min(self.points[:, 0]), np.min(self.points[:, 1])),
(np.max(self.points[:, 0]), np.max(self.points[:, 1])),
]
return np.array(bbox)
def append(self, path):
"""Attach Path to the end of this Path.
The input path automatically rotates and translates such that it continues
smoothly from the previous segment.
Args:
path: Path, array-like[N][2], or list of Paths. The input path that will be appended.
"""
# If appending another Path, load relevant variables
if isinstance(path, Path):
start_angle = path.start_angle
end_angle = path.end_angle
points = path.points
# If array[N][2]
elif (
(np.asarray(path, dtype=object).ndim == 2)
and np.issubdtype(np.array(path).dtype, np.number)
and (np.shape(path)[1] == 2)
):
points = np.asfarray(path)
nx1, ny1 = points[1] - points[0]
start_angle = np.arctan2(ny1, nx1) / np.pi * 180
nx2, ny2 = points[-1] - points[-2]
end_angle = np.arctan2(ny2, nx2) / np.pi * 180
# If list of Paths or arrays
elif isinstance(path, list | tuple):
for p in path:
self.append(p)
return self
else:
raise ValueError(
"Path.append() the `path` argument must be either "
"a Path object, an array-like[N][2] list of points, or a list of these"
)
# Connect beginning of new points with old points
points = _rotate_points(points, angle=self.end_angle - start_angle)
points += self.points[-1, :] - points[0, :]
# Update end angle
self.end_angle = mod(end_angle + self.end_angle - start_angle, 360)
# Concatenate old points + new points
self.points = np.vstack([self.points, points[1:]])
return self
def offset(self, offset: float | Callable[..., float] = 0):
"""Offsets Path so that it follows the Path centerline plus an offset.
The offset can either be a fixed value, or a function
of the form my_offset(t) where t goes from 0->1
Args:
offset: int or float, callable. Magnitude of the offset
"""
if offset == 0:
points = self.points
start_angle = self.start_angle
end_angle = self.end_angle
elif callable(offset):
# Compute lengths
dx = np.diff(self.points[:, 0])
dy = np.diff(self.points[:, 1])
lengths = np.cumsum(np.sqrt((dx) ** 2 + (dy) ** 2))
lengths = np.concatenate([[0], lengths])
# Create list of offset points and perform offset
points = self._centerpoint_offset_curve(
self.points,
offset_distance=offset(lengths / lengths[-1]),
start_angle=self.start_angle,
end_angle=self.end_angle,
)
# Numerically compute start and end angles
tol = 1e-6
ds = tol / lengths[-1]
ny1 = offset(ds) - offset(0)
start_angle = np.arctan2(-ny1, tol) / np.pi * 180 + self.start_angle
# start_angle = np.round(start_angle, decimals=6)
ny2 = offset(1) - offset(1 - ds)
end_angle = np.arctan2(-ny2, tol) / np.pi * 180 + self.end_angle
# end_angle = np.round(end_angle, decimals=6)
else: # Offset is just a number
points = self._centerpoint_offset_curve(
self.points,
offset_distance=offset,
start_angle=self.start_angle,
end_angle=self.end_angle,
)
start_angle = self.start_angle
end_angle = self.end_angle
self.points = points
self.start_angle = start_angle
self.end_angle = end_angle
return self
def move(self, origin=(0, 0), destination=None, axis=None):
"""Moves the Path from the origin point to the destination.
Both origin and destination can be 1x2 array-like or a Port.
Args:
origin : array-like[2], Port Origin point of the move.
destination : array-like[2], Port Destination point of the move.
axis : {'x', 'y'} Direction of move.
"""
dx, dy = _parse_move(origin, destination, axis)
self.points += np.array([dx, dy])
return self
def rotate(self, angle: float = 45, center: Float2 | None = (0, 0)):
"""Rotates all Polygons in the Component around the specified center point.
If no center point specified will rotate around (0,0).
Args:
angle: Angle to rotate the Component in degrees.
center: array-like[2] or None. component of the Component.
"""
if angle == 0:
return self
self.points = _rotate_points(self.points, angle, center)
if self.start_angle is not None:
self.start_angle = mod(self.start_angle + angle, 360)
if self.end_angle is not None:
self.end_angle = mod(self.end_angle + angle, 360)
return self
def mirror(self, p1: Float2 = (0, 1), p2: Float2 = (0, 0)):
"""Mirrors the Path across the line formed between the two specified points.
``points`` may be input as either single points [1,2]
or array-like[N][2], and will return in kind.
Args:
p1: First point of the line.
p2: Second point of the line.
"""
self.points = _reflect_points(self.points, p1, p2)
angle = np.arctan2((p2[1] - p1[1]), (p2[0] - p1[0])) * 180 / pi
if self.start_angle is not None:
self.start_angle = mod(2 * angle - self.start_angle, 360)
if self.end_angle is not None:
self.end_angle = mod(2 * angle - self.end_angle, 360)
return self
def _centerpoint_offset_curve(
self, points, offset_distance, start_angle, end_angle
):
"""Creates a offset curve (but does not account for cusps etc)\
by computing the centerpoint offset of the supplied x and y points."""
new_points = np.array(points, dtype=np.float64)
dx = np.diff(points[:, 0])
dy = np.diff(points[:, 1])
theta = np.arctan2(dy, dx)
theta = np.concatenate([theta[:1], theta, theta[-1:]])
theta_mid = (np.pi + theta[1:] + theta[:-1]) / 2 # Mean angle between segments
dtheta_int = np.pi + theta[:-1] - theta[1:] # Internal angle between segments
offset_distance = offset_distance / np.sin(dtheta_int / 2)
new_points[:, 0] -= offset_distance * np.cos(theta_mid)
new_points[:, 1] -= offset_distance * np.sin(theta_mid)
if start_angle is not None:
new_points[0, :] = points[0, :] + (
np.sin(start_angle * np.pi / 180) * offset_distance[0],
-np.cos(start_angle * np.pi / 180) * offset_distance[0],
)
if end_angle is not None:
new_points[-1, :] = points[-1, :] + (
np.sin(end_angle * np.pi / 180) * offset_distance[-1],
-np.cos(end_angle * np.pi / 180) * offset_distance[-1],
)
return new_points
def _parametric_offset_curve(self, points, offset_distance, start_angle, end_angle):
"""Creates a parametric offset (does not account for cusps etc) \
by using gradient of the supplied x and y points."""
x = points[:, 0]
y = points[:, 1]
dxdt = np.gradient(x)
dydt = np.gradient(y)
if start_angle is not None:
dxdt[0] = np.cos(start_angle * np.pi / 180)
dydt[0] = np.sin(start_angle * np.pi / 180)
if end_angle is not None:
dxdt[-1] = np.cos(end_angle * np.pi / 180)
dydt[-1] = np.sin(end_angle * np.pi / 180)
x_offset = x + offset_distance * dydt / np.sqrt(dxdt**2 + dydt**2)
y_offset = y - offset_distance * dxdt / np.sqrt(dydt**2 + dxdt**2)
return np.array([x_offset, y_offset]).T
def length(self) -> float:
"""Return cumulative length."""
x = self.points[:, 0]
y = self.points[:, 1]
dx = np.diff(x)
dy = np.diff(y)
return np.sum(np.sqrt((dx) ** 2 + (dy) ** 2))
def curvature(self):
"""Calculates Path curvature.
The curvature is numerically computed so areas where the curvature
jumps instantaneously (such as between an arc and a straight segment)
will be slightly interpolated, and sudden changes in point density
along the curve can cause discontinuities.
Returns:
s: array-like[N] The arc-length of the Path
K: array-like[N] The curvature of the Path
"""
x = self.points[:, 0]
y = self.points[:, 1]
dx = np.diff(x)
dy = np.diff(y)
ds = np.sqrt((dx) ** 2 + (dy) ** 2)
s = np.cumsum(ds)
theta = np.arctan2(dy, dx)
# Fix discontinuities arising from np.arctan2
dtheta = np.diff(theta)
dtheta[np.where(dtheta > np.pi)] += -2 * np.pi
dtheta[np.where(dtheta < -np.pi)] += 2 * np.pi
theta = np.concatenate([[0], np.cumsum(dtheta)]) + theta[0]
K = np.gradient(theta, s, edge_order=2)
return s, K
def hash_geometry(self, precision: float = 1e-4) -> str:
"""Computes an SHA1 hash of the points in the Path and the start_angle and end_angle.
Args:
precision: Rounding precision for the the objects in the Component. For instance, \
a precision of 1e-2 will round a point at (0.124, 1.748) to (0.12, 1.75)
Returns:
str Hash result in the form of an SHA1 hex digest string.
.. code::
hash(
hash(First layer information: [layer1, datatype1]),
hash(Polygon 1 on layer 1 points: [(x1,y1),(x2,y2),(x3,y3)] ),
hash(Polygon 2 on layer 1 points: [(x1,y1),(x2,y2),(x3,y3),(x4,y4)] ),
hash(Polygon 3 on layer 1 points: [(x1,y1),(x2,y2),(x3,y3)] ),
hash(Second layer information: [layer2, datatype2]),
hash(Polygon 1 on layer 2 points: [(x1,y1),(x2,y2),(x3,y3),(x4,y4)] ),
hash(Polygon 2 on layer 2 points: [(x1,y1),(x2,y2),(x3,y3)] ),
)
"""
# A random offset which fixes common rounding errors intrinsic
# to floating point math. Example: with a precision of 0.1, the
# floating points 7.049999 and 7.050001 round to different values
# (7.0 and 7.1), but offset values (7.220485 and 7.220487) don't
magic_offset = 0.17048614
final_hash = hashlib.sha1()
points = (
np.ascontiguousarray(
(self.points / precision) + magic_offset, dtype=np.float64
)
.round()
.astype(np.int64)
)
final_hash.update(points)
angles = (
(
np.ascontiguousarray(
(self.start_angle, self.end_angle), dtype=np.float64
)
/ precision
)
.round()
.astype(np.int64)
)
final_hash.update(angles)
return final_hash.hexdigest()
@classmethod
def __get_validators__(cls):
"""For pydantic."""
yield cls._validate
@classmethod
def _validate(cls, v, validation_info):
"""Pydantic Path validator."""
assert isinstance(v, Path), f"TypeError, Got {type(v)}, expecting Path"
return v
def to_dict(self) -> dict[str, str]:
return dict(hash=self.hash_geometry())
def plot(self) -> None:
"""Plot path in matplotlib.
.. plot::
:include-source:
import gdsfactory as gf
p = gf.path.euler(radius=10)
p.plot()
"""
from gdsfactory.quickplotter import quickplot
return quickplot(self)
def extrude(
self,
cross_section: CrossSectionSpec | None = None,
layer: LayerSpec | None = None,
width: float | None = None,
simplify: float | None = None,
) -> Component:
"""Returns Component by extruding a Path with a CrossSection.
A path can be extruded using any CrossSection returning a Component
The CrossSection defines the layer numbers, widths and offsets.
Args:
cross_section: to extrude.
layer: optional layer.
width: optional width in um.
simplify: Tolerance value for the simplification algorithm. \
All points that can be removed without changing the resulting polygon\
by more than the value listed here will be removed.
.. plot::
:include-source:
import gdsfactory as gf
p = gf.path.euler(radius=10)
c = p.extrude(layer=(1, 0), width=0.5)
c.plot()
"""
return extrude(
p=self,
cross_section=cross_section,
layer=layer,
width=width,
simplify=simplify,
)
def copy(self):
"""Returns a copy of the Path."""
p = Path()
p.info = self.info.copy()
p.points = np.array(self.points)
p.start_angle = self.start_angle
p.end_angle = self.end_angle
return p
PathFactory = Callable[..., Path]
def _sinusoidal_transition(y1, y2):
dy = y2 - y1
def sine(t):
return y1 + (1 - np.cos(np.pi * t)) / 2 * dy
return sine
def _parabolic_transition(y1, y2):
dy = y2 - y1
def parabolic(t):
return y1 + np.sqrt(t) * dy
return parabolic
def _linear_transition(y1, y2):
dy = y2 - y1
def linear(t):
return y1 + t * dy
return linear
def transition_exponential(y1, y2, exp=0.5):
"""Returns the function for an exponential transition.
Args:
y1: start width in um.
y2: end width in um.
exp: exponent.
"""
return lambda t: y1 + (y2 - y1) * t**exp
adiabatic_polyfit_TE1550SOI_220nm = np.array(
[
1.02478963e-09,
-8.65556534e-08,
3.32415694e-06,
-7.68408985e-05,
1.19282177e-03,
-1.31366332e-02,
1.05721429e-01,
-6.31057637e-01,
2.80689677e00,
-9.26867694e00,
2.24535191e01,
-3.90664800e01,
4.71899278e01,
-3.74726005e01,
1.77381560e01,
-1.12666286e00,
]
)
def transition_adiabatic(
w1: float,
w2: float,
neff_w,
wavelength: float = 1.55,
alpha: float = 1,
max_length: float = 200,
num_points_ODE: int = 2000,
):
"""Returns the points for an optimal adiabatic transition for well-guided modes.
Args:
w1: start width in um.
w2: end width in um.
neff_w: a callable that returns the effective index as a function of width. \
By default, use a compact model of neff(y) for fundamental 1550 nm TE \
mode of 220nm-thick core with 3.45 index, fully clad with 1.44 index.\
Many coefficients are needed to capture the behaviour.
wavelength: wavelength, in same units as widths
alpha: parameter that scales the rate of width change
- closer to 0 means longer and more adiabatic;
- 1 is the intuitive limit beyond which higher order modes are excited;
- [2] reports good performance up to 1.4 for fundamental TE in SOI (for multiple core thicknesses)
max_length: maximum length in um.
num_points_ODE: number of samplings points for the ODE solve.
References:
[1] Burns, W. K., et al. "Optical waveguide parabolic coupling horns."
Appl. Phys. Lett., vol. 30, no. 1, 1 Jan. 1977, pp. 28-30, doi:10.1063/1.89199.
[2] Fu, Yunfei, et al. "Efficient adiabatic silicon-on-insulator waveguide taper."
Photonics Res., vol. 2, no. 3, 1 June 2014, pp. A41-A44, doi:10.1364/PRJ.2.000A41.
"""
from scipy.integrate import odeint
# Define ODE
def dWdx(w, x, neff_w, wavelength, alpha):
return alpha * wavelength / (neff_w(w) * w)
# Parse input
if w2 < w1:
wmin = w2
wmax = w1
order = -1
else:
wmin = w1
wmax = w2
order = 1
# Solve ODE
x = np.linspace(0, max_length, num_points_ODE)
sol = odeint(dWdx, wmin, x, args=(neff_w, wavelength, alpha))
# Extract optimal curve
xs = x[np.where(sol[:, 0] < wmax)]
ws = sol[:, 0][np.where(sol[:, 0] < wmax)]
return xs, ws[::order]
def transition(
cross_section1: CrossSectionSpec,
cross_section2: CrossSectionSpec,
width_type: WidthTypes = "sine",
) -> Transition:
"""Returns a smoothly-transitioning between two CrossSections.
Only cross-sectional elements that have the `name` (as in X.add(..., name = 'wg') )
parameter specified in both input CrosSections will be created.
Port names will be cloned from the input CrossSections in reverse.
Args:
cross_section1: First CrossSection.
cross_section2: Second CrossSection.
width_type: sine or linear. type of width transition used if any widths \
are different between the two input CrossSections.
"""
from gdsfactory.pdk import get_cross_section, get_layer
X1 = get_cross_section(cross_section1)
X2 = get_cross_section(cross_section2)
layers1 = {get_layer(section.layer) for section in X1.sections}
layers2 = {get_layer(section.layer) for section in X2.sections}
layers1.add(get_layer(X1.layer))
layers2.add(get_layer(X2.layer))
has_common_layers = bool(layers1.intersection(layers2))
if not has_common_layers:
raise ValueError(
f"transition() found no common layers X1 {layers1} and X2 {layers2}"
)
return Transition(
cross_section1=X1,
cross_section2=X2,
width_type=width_type,
)
@cell
def along_path(
p: Path,
component: ComponentSpec,
spacing: float,
padding: float,
) -> Component:
"""Returns Component containing many copies of `component` along `p`.
Places as many copies of `component` along each segment of `p` as possible
under the given constraints. `spacing` is always followed precisely, but
actual `padding` may exceed the provided value to place components evenly.
Args:
p: Path to place components along.
component: Component to repeat along the path. The unrotated version of \
this object should be oriented for placement on a horizontal line.
spacing: distance between component placements.
padding: minimum distance from the path start to the first component.
"""
from gdsfactory.pdk import get_component
component = get_component(component)
length = p.length()
number = (length - 2 * padding) // spacing + 1
c = Component()
cum_dist = 0
next_component = (length - (number - 1) * spacing) / 2
stop = length - next_component
# Prepare in advance the rotation angle for each segment
angle_list = [
np.rad2deg(
np.arctan2(
(p.points[i + 1] - p.points[i])[1], (p.points[i + 1] - p.points[i])[0]
)
)
for i in range(len(p.points) - 1)
]
for i, start_pt in enumerate(p.points[:-1]):
end_pt = p.points[i + 1]
segment_vector = end_pt - start_pt
segment_length = np.linalg.norm(segment_vector)
unit_vector = segment_vector / segment_length
# Get the pre-calculated angle for this segment
angle = angle_list[i]
while next_component <= cum_dist + segment_length and next_component <= stop:
added_dist = next_component - cum_dist
offset = added_dist * unit_vector
component_ref = c << component
component_ref.rotate(angle).move(start_pt + offset)
next_component += spacing
cum_dist += segment_length
return c
def _get_named_sections(sections: tuple[Section, ...]) -> dict[str, Section]:
from gdsfactory.pdk import get_layer
named_sections = {}
for section in sections:
name = section.name or get_layer(section.layer)
if name in named_sections:
raise ValueError(
f"Duplicate name or layer '{name}' of section used for cross-section in transition. Cross-sections with multiple Sections for a single layer must have unique names for each section"
)
named_sections[name] = section
return named_sections
@cell
def extrude(
p: Path,
cross_section: CrossSectionSpec | None = None,
layer: LayerSpec | None = None,
width: float | None = None,
simplify: float | None = None,
) -> Component:
"""Returns Component extruding a Path with a cross_section.
A path can be extruded using any CrossSection returning a Component
The CrossSection defines the layer numbers, widths and offsets
Args:
p: a path is a list of points (arc, straight, euler).
cross_section: to extrude.
layer: optional layer to extrude.
width: optional width to extrude.
simplify: Tolerance value for the simplification algorithm. \
All points that can be removed without changing the resulting polygon \
by more than the value listed here will be removed.
"""
from gdsfactory.pdk import (
get_cross_section,
get_layer,
)
if cross_section is None and layer is None:
raise ValueError("CrossSection or layer needed")
if cross_section is not None and layer is not None:
raise ValueError("Define only CrossSection or layer")
if layer is not None and width is None:
raise ValueError("Need to define layer width")
elif width:
s = Section(
width=width,
layer=layer,
port_names=("o1", "o2"),
port_types=("optical", "optical"),
)
cross_section = CrossSection(sections=(s,))
xsection_points = []
c = Component()
x = get_cross_section(cross_section)
if isinstance(x, Transition):
return extrude_transition(
p,
transition=x,
)
layer = layer or x.layer
layer = get_layer(layer)
for section in x.sections:
p_sec = p.copy()
port_names = section.port_names
port_types = section.port_types
hidden = section.hidden
offset = section.offset
width = section.width
width_function = section.width_function
offset_function = section.offset_function
layer = section.layer
if isinstance(width, int | float) and isinstance(offset, int | float):
xsection_points.append([width, offset])
if section.insets and section.insets != (0, 0):
p_pts = p_sec.points
new_x_start = p.xmin + section.insets[0]
new_x_stop = p.xmax - section.insets[1]
if new_x_start > np.max(p_pts[:, 0]) or new_x_stop < np.min(p_pts[:, 0]):
warnings.warn(
f"Cannot apply delay to Section '{section.name}', delay results in points outside of original path.",
stacklevel=3,
)
continue
new_start_idx = np.argwhere(p_pts[:, 0] > new_x_start)[0, 0]
new_stop_idx = np.argwhere(p_pts[:, 0] < new_x_stop)[-1, 0]
new_start_point = [new_x_start, p_pts[new_start_idx, 1]]
new_stop_point = [new_x_stop, p_pts[new_stop_idx, 1]]
p_sec = Path(
[new_start_point, *p_pts[new_start_idx:new_stop_idx], new_stop_point]
)
if callable(offset_function):
p_sec.offset(offset_function)
offset = 0
end_angle = p_sec.end_angle
start_angle = p_sec.start_angle
points = p_sec.points
if callable(width_function):
# Compute lengths
dx = np.diff(p_sec.points[:, 0])
dy = np.diff(p_sec.points[:, 1])
lengths = np.cumsum(np.sqrt(dx**2 + dy**2))
lengths = np.concatenate([[0], lengths])
width = width_function(lengths / lengths[-1])
dy = offset + width / 2
points1 = p_sec._centerpoint_offset_curve(
points,
offset_distance=dy,
start_angle=start_angle,
end_angle=end_angle,
)
dy = offset - width / 2
points2 = p_sec._centerpoint_offset_curve(
points,
offset_distance=dy,
start_angle=start_angle,
end_angle=end_angle,
)
if isinstance(simplify, bool):
raise ValueError("simplify argument must be a number (e.g. 1e-3) or None")
with_simplify = section.simplify or simplify
if with_simplify:
points1 = _simplify(points1, tolerance=with_simplify)
points2 = _simplify(points2, tolerance=with_simplify)
# Join points together
points_poly = np.concatenate([points1, points2[::-1, :]])
if not hidden and p_sec.length() > 1e-3:
c.add_polygon(points_poly, layer=layer)
# Add port_names if they were specified
if port_names[0] is not None:
port_width = width if np.isscalar(width) else width[0]
port_orientation = (p_sec.start_angle + 180) % 360
center = points[0]
face = [points1[0], points2[0]]
face = [_rotated_delta(point, center, port_orientation) for point in face]
c.add_port(
name=port_names[0],
layer=layer,
port_type=port_types[0],
width=port_width,
orientation=port_orientation,
center=center,
cross_section=x,
)
if port_names[1] is not None:
port_width = width if np.isscalar(width) else width[-1]
port_orientation = (p_sec.end_angle) % 360
center = points[-1]
face = [points1[-1], points2[-1]]
face = [_rotated_delta(point, center, port_orientation) for point in face]
c.add_port(
name=port_names[1],
layer=layer,
port_type=port_types[1],
width=port_width,
center=center,
orientation=port_orientation,
cross_section=x,
)
c.info["length"] = float(np.round(p.length(), 3))
for via in x.components_along_path:
if via.offset:
points_offset = p._centerpoint_offset_curve(
points,
offset_distance=via.offset,
start_angle=start_angle,
end_angle=end_angle,
)
_p = Path(points_offset)
else:
_p = p
_ = c << along_path(
p=_p, component=via.component, spacing=via.spacing, padding=via.padding
)
return c
@cell
def extrude_transition(
p: Path,
transition: Transition,
) -> Component:
"""Extrudes a path along a transition.
Args:
p: path to extrude.
transition: transition to extrude along.
"""
from gdsfactory.pdk import get_cross_section, get_layer
c = Component()
x1 = get_cross_section(transition.cross_section1)
x2 = get_cross_section(transition.cross_section2)
width_type = transition.width_type
# if named, prefer name over layer
named_sections1 = _get_named_sections(x1.sections)
named_sections2 = _get_named_sections(x2.sections)
names1 = list(named_sections1.keys())
names2 = list(named_sections2.keys())
common_sections = set(names1).intersection(names2)
if len(common_sections) == 0:
raise ValueError(
f"transition() found no common layers X1 {names1} and X2 {names2}"
)
for section_name in common_sections:
section1 = named_sections1[section_name]
section2 = named_sections2[section_name]
port_names = section1.port_names
port_types = section1.port_types
p_sec = p.copy()
offset1 = section1.offset
offset2 = section2.offset
width1 = section1.width
width2 = section2.width
if callable(offset1):
offset1 = offset1(1)
if callable(offset2):
offset2 = offset2(0)
if callable(width1):
width1 = width1(1)
if callable(width2):
width2 = width2(0)
offset = _sinusoidal_transition(offset1, offset2)
if width_type == "linear":
width = _linear_transition(width1, width2)
elif width_type == "sine":
width = _sinusoidal_transition(width1, width2)
elif width_type == "parabolic":
width = _parabolic_transition(width1, width2)
else:
raise ValueError(
f"width_type={width_type!r} must be {'sine','linear','parabolic'}"
)
if section1.layer != section2.layer:
hidden = True
layer1 = get_layer(section1.layer)
layer2 = get_layer(section2.layer)
layer = (layer1, layer2)
else:
hidden = False
layer = get_layer(section1.layer)
p_sec.offset(offset)
offset = 0
end_angle = p_sec.end_angle
start_angle = p_sec.start_angle
points = p_sec.points
if callable(width):
# Compute lengths
dx = np.diff(p_sec.points[:, 0])
dy = np.diff(p_sec.points[:, 1])
lengths = np.cumsum(np.sqrt(dx**2 + dy**2))
lengths = np.concatenate([[0], lengths])
width = width(lengths / lengths[-1])
dy = offset + width / 2
points1 = p_sec._centerpoint_offset_curve(
points,
offset_distance=dy,
start_angle=start_angle,
end_angle=end_angle,