gds-fdtd 0.3.0__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
gds_fdtd/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """gds_fdtd Top-level package imports."""
2
+ from . import core, lyprocessor, simprocessor
3
+
4
+ __author__ = """Mustafa Hammood"""
5
+ __email__ = "mustafa@siepic.com"
6
+ __version__ = "0.3.0"
gds_fdtd/core.py ADDED
@@ -0,0 +1,575 @@
1
+ """
2
+ gds_fdtd simulation toolbox.
3
+
4
+ Core objects module.
5
+ @author: Mustafa Hammood, 2025
6
+ """
7
+
8
+ import pya
9
+ import logging
10
+ import numpy as np
11
+ import matplotlib.pyplot as plt
12
+ from shapely.geometry import Point
13
+ from shapely.geometry.polygon import Polygon
14
+ import yaml
15
+
16
+ c0_um = 299792458000000.0 # speed of light in um/s
17
+
18
+ def is_point_inside_polygon(
19
+ point: list[float, float], polygon_points: list[list[float, float]]
20
+ ) -> bool:
21
+ """Test if a point inside a polygon using Shapely.
22
+
23
+ Args:
24
+ point (list): Point for test [x, y]
25
+ polygon_points (list): List of points defining a polygon [[x1, y1], [x2,y2], ..]
26
+
27
+ Returns:
28
+ bool: Test result.
29
+ """
30
+
31
+ # Create a Shapely Point object for the given coordinate
32
+ point = Point(point)
33
+
34
+ # Create a Shapely Polygon object from the list of polygon points
35
+ polygon = Polygon(polygon_points)
36
+
37
+ # Check if the point is inside the polygon
38
+ return point.within(polygon) or polygon.touches(point)
39
+
40
+
41
+ class layout:
42
+ def __init__(self, name: str, ly: pya.Layout, cell: pya.Cell):
43
+ self.name = name
44
+ self.ly = ly
45
+ self.cell = cell
46
+
47
+ @property
48
+ def dbu(self) -> float:
49
+ return self.ly.dbu
50
+
51
+
52
+ def calculate_polygon_extension(
53
+ center: list[float, float], width: float, direction: float, buffer: float = 4.0
54
+ ) -> list[list[float, float]]:
55
+ """
56
+ Calculate the polygon extension for a port.
57
+
58
+ Args:
59
+ center (list[float, float]): Center of the port [x, y]. Convention is in microns.
60
+ width (float): Width of the port. Convention is in microns.
61
+ direction (float): Direction of the port in degrees. Convention is in degrees.
62
+ buffer (float): Buffer distance from the port. Convention is in microns.
63
+
64
+ Returns:
65
+ list[list[float, float]]: Polygon extension
66
+ """
67
+ if direction == 0:
68
+ return [
69
+ [center[0], center[1] + width / 2],
70
+ [center[0] + buffer, center[1] + width / 2],
71
+ [center[0] + buffer, center[1] - width / 2],
72
+ [center[0], center[1] - width / 2],
73
+ ]
74
+ elif direction == 180:
75
+ return [
76
+ [center[0], center[1] + width / 2],
77
+ [center[0] - buffer, center[1] + width / 2],
78
+ [center[0] - buffer, center[1] - width / 2],
79
+ [center[0], center[1] - width / 2],
80
+ ]
81
+ elif direction == 90:
82
+ return [
83
+ [center[0] - width / 2, center[1]],
84
+ [center[0] - width / 2, center[1] + buffer],
85
+ [center[0] + width / 2, center[1] + buffer],
86
+ [center[0] + width / 2, center[1]],
87
+ ]
88
+ elif direction == 270:
89
+ return [
90
+ [center[0] - width / 2, center[1]],
91
+ [center[0] - width / 2, center[1] - buffer],
92
+ [center[0] + width / 2, center[1] - buffer],
93
+ [center[0] + width / 2, center[1]],
94
+ ]
95
+
96
+
97
+ class port:
98
+ """
99
+ Represents an optical port object in a component.
100
+
101
+ A port defines a connection point with properties like position, width, and direction.
102
+
103
+ Attributes:
104
+ name (str): Name of the port, typically containing a numeric identifier.
105
+ center (list[float, float, float]): 3D coordinates of the port center [x, y, z]. Convention is in microns.
106
+ width (float): Width of the port. Convention is in microns.
107
+ direction (float): Direction of the port. Convention is in degrees. Directions supported are 0, 90, 180, 270.
108
+ height (float): Height of the port, assigned during component initialization. Convention is in microns.
109
+ material (str): Material of the port, assigned during component initialization.
110
+ """
111
+
112
+ def __init__(
113
+ self,
114
+ name: str,
115
+ center: list[float, float, float],
116
+ width: float,
117
+ direction: float,
118
+ ):
119
+ """
120
+ Initialize a port object.
121
+
122
+ Args:
123
+ name (str): Name of the port, typically containing a numeric identifier.
124
+ center (list[float, float, float]): 3D coordinates of the port center [x, y, z].
125
+ width (float): Width of the port in microns.
126
+ direction (float): Direction of the port in degrees.
127
+ """
128
+ self.name = name
129
+ self.center = center
130
+ self.width = width
131
+ self.direction = direction
132
+ # initialize height as none
133
+ # will be assigned upon component __init__
134
+ # TODO: feels like a better way to do this..
135
+ self.height = None
136
+ self.material = None
137
+
138
+ if self.direction not in [0, 90, 180, 270]:
139
+ raise ValueError(
140
+ f"Invalid direction: {self.direction}. Supported directions are 0, 90, 180, 270."
141
+ )
142
+
143
+ @property
144
+ def x(self) -> float:
145
+ """
146
+ Get the x-coordinate of the port center.
147
+
148
+ Returns:
149
+ float: x-coordinate in microns.
150
+ """
151
+ return self.center[0]
152
+
153
+ @property
154
+ def y(self) -> float:
155
+ """
156
+ Get the y-coordinate of the port center.
157
+
158
+ Returns:
159
+ float: y-coordinate in microns.
160
+ """
161
+ return self.center[1]
162
+
163
+ @property
164
+ def z(self) -> float:
165
+ """
166
+ Get the z-coordinate of the port center.
167
+
168
+ Returns:
169
+ float: z-coordinate in microns.
170
+ """
171
+ return self.center[2]
172
+
173
+ @property
174
+ def idx(self) -> int:
175
+ """
176
+ Extract the index of the port from its name.
177
+
178
+ The index is extracted by taking the digits in the name in reverse order.
179
+ For example, "port42" would yield an index of 24.
180
+
181
+ Returns:
182
+ int: The extracted port index.
183
+ """
184
+ return int("".join(char for char in reversed(self.name) if char.isdigit()))
185
+
186
+ def polygon_extension(self, buffer: float = 4.0) -> list[list[float, float]]:
187
+ """
188
+ Calculate the polygon extension for this port.
189
+
190
+ This creates a rectangular polygon extending from the port in the direction
191
+ specified by the port's direction attribute.
192
+
193
+ Args:
194
+ buffer (float, optional): Buffer distance from the port in microns. Defaults to 4.0.
195
+
196
+ Returns:
197
+ list[list[float, float]]: Polygon extension as a list of [x,y] coordinates.
198
+ """
199
+ return calculate_polygon_extension(
200
+ self.center, self.width, self.direction, buffer
201
+ )
202
+
203
+
204
+ class structure:
205
+ """
206
+ Represents a physical structure in the component with geometric and material properties.
207
+
208
+ This class defines a 3D structure with a 2D polygon base extruded vertically,
209
+ including material properties and sidewall angle for fabrication realism.
210
+ """
211
+
212
+ def __init__(
213
+ self,
214
+ name: str,
215
+ polygon: list[list[float, float]],
216
+ z_base: float,
217
+ z_span: float,
218
+ material: str,
219
+ sidewall_angle: float = 90.0,
220
+ ):
221
+ """
222
+ Initialize a structure with geometric and material properties.
223
+
224
+ Args:
225
+ name (str): Unique identifier for the structure.
226
+ polygon (list[list[float, float]]): 2D polygon defining the structure's horizontal cross-section,
227
+ formatted as [[x1,y1], [x2,y2], ...].
228
+ z_base (float): Base z-coordinate in microns where the structure begins.
229
+ z_span (float): Vertical height/thickness of the structure in microns.
230
+ material (str): Material identifier for the structure.
231
+ sidewall_angle (float, optional): Angle of the sidewalls in degrees, where 90.0 means vertical walls.
232
+ Defaults to 90.0.
233
+ """
234
+ self.name = name
235
+ self.polygon = polygon # polygon should be in the form of list of list of 2 pts, i.e. [[0,0],[0,1],[1,1]]
236
+ self.z_base = z_base
237
+ self.z_span = z_span
238
+ self.material = material
239
+ self.sidewall_angle = sidewall_angle
240
+
241
+
242
+ class region:
243
+ """
244
+ Represents a 3D region defined by a 2D polygon and vertical extent.
245
+
246
+ This class defines a region with vertices in the x-y plane and a vertical
247
+ extent defined by z_center and z_span.
248
+ """
249
+
250
+ def __init__(self, vertices: list[list[float]], z_center: float, z_span: float):
251
+ """
252
+ Initialize a region with vertices and vertical dimensions.
253
+
254
+ Args:
255
+ vertices (list[list[float]]): List of [x,y] coordinates defining the region's polygon.
256
+ z_center (float): Center z-coordinate of the region in microns.
257
+ z_span (float): Vertical extent/thickness of the region in microns.
258
+ """
259
+ self.vertices = vertices
260
+ self.z_center = z_center
261
+ self.z_span = z_span
262
+
263
+ @property
264
+ def x(self) -> list[float]:
265
+ """
266
+ Get all x-coordinates of the vertices.
267
+
268
+ Returns:
269
+ list[float]: List of x-coordinates.
270
+ """
271
+ return [i[0] for i in self.vertices]
272
+
273
+ @property
274
+ def y(self) -> list[float]:
275
+ """
276
+ Get all y-coordinates of the vertices.
277
+
278
+ Returns:
279
+ list[float]: List of y-coordinates.
280
+ """
281
+ return [i[1] for i in self.vertices]
282
+
283
+ @property
284
+ def x_span(self) -> float:
285
+ """
286
+ Calculate the span (width) of the region in the x-direction.
287
+
288
+ Returns:
289
+ float: Width of the region in microns.
290
+ """
291
+ return abs(min(self.x) - max(self.x))
292
+
293
+ @property
294
+ def y_span(self) -> float:
295
+ """
296
+ Calculate the span (height) of the region in the y-direction.
297
+
298
+ Returns:
299
+ float: Height of the region in microns.
300
+ """
301
+ return abs(min(self.y) - max(self.y))
302
+
303
+ @property
304
+ def x_center(self) -> float:
305
+ """
306
+ Calculate the center x-coordinate of the region.
307
+
308
+ Returns:
309
+ float: Center x-coordinate in microns.
310
+ """
311
+ return (min(self.x) + max(self.x)) / 2
312
+
313
+ @property
314
+ def y_center(self) -> float:
315
+ """
316
+ Calculate the center y-coordinate of the region.
317
+
318
+ Returns:
319
+ float: Center y-coordinate in microns.
320
+ """
321
+ return (min(self.y) + max(self.y)) / 2
322
+
323
+ @property
324
+ def x_min(self) -> float:
325
+ """
326
+ Get the minimum x-coordinate of the region.
327
+
328
+ Returns:
329
+ float: Minimum x-coordinate in microns.
330
+ """
331
+ return min(self.x)
332
+
333
+ @property
334
+ def x_max(self) -> float:
335
+ """
336
+ Get the maximum x-coordinate of the region.
337
+
338
+ Returns:
339
+ float: Maximum x-coordinate in microns.
340
+ """
341
+ return max(self.x)
342
+
343
+ @property
344
+ def y_min(self) -> float:
345
+ """
346
+ Get the minimum y-coordinate of the region.
347
+
348
+ Returns:
349
+ float: Minimum y-coordinate in microns.
350
+ """
351
+ return min(self.y)
352
+
353
+ @property
354
+ def y_max(self) -> float:
355
+ """
356
+ Get the maximum y-coordinate of the region.
357
+
358
+ Returns:
359
+ float: Maximum y-coordinate in microns.
360
+ """
361
+ return max(self.y)
362
+
363
+
364
+
365
+ def initialize_ports_z(ports: list["port"], structures: list["structure"]) -> None:
366
+ """
367
+ Initialize the z-coordinate, height, and material of ports based on their position within structures.
368
+
369
+ This function checks if each port is located within any structure and sets the port's z-coordinate,
370
+ height, and material accordingly.
371
+
372
+ Args:
373
+ ports (list["port"]): List of port objects to initialize.
374
+ structures (list["structure"]): List of structure objects to check against.
375
+
376
+ Returns:
377
+ None
378
+ """
379
+ # iterate through each port
380
+ for p in ports:
381
+ # check if port location is within any structure
382
+ for s in structures:
383
+ # TODO: hack: if s is a list then it's not a box/clad region, find a better way to identify this..
384
+ if type(s) == list:
385
+ for poly in s:
386
+ if is_point_inside_polygon(p.center[:2], poly.polygon):
387
+ p.center[2] = s[0].z_base + s[0].z_span / 2
388
+ p.height = s[0].z_span
389
+ p.material = s[0].material
390
+ if p.height == None:
391
+ logging.warning(f"Cannot find height for port {p.name}")
392
+ return
393
+ class component:
394
+ """
395
+ A component consisting of structures, ports, and boundaries.
396
+
397
+ This class represents a complete photonic component that can be simulated
398
+ or exported to GDS format.
399
+ """
400
+
401
+ def __init__(self, name: str, structures: list[structure], ports: list[port], bounds: list[region]):
402
+ """
403
+ Initialize a photonic component.
404
+
405
+ Args:
406
+ name: The name of the component.
407
+ structures: List of structures (geometries) in the component.
408
+ ports: List of ports for input/output connections.
409
+ bounds: Boundaries of the component.
410
+ """
411
+ self.name = name
412
+ self.structures = structures
413
+ self.ports = ports
414
+ self.bounds = bounds
415
+ initialize_ports_z(ports = self.ports, structures = self.structures) # initialize ports z center and z span
416
+
417
+ def export_gds(self, export_dir: str = None, dbu: float = 0.001, layer: list = [1, 0]) -> None:
418
+ """
419
+ Export the component to a GDS file.
420
+
421
+ Args:
422
+ export_dir: Directory to export the GDS file to. Defaults to current working directory.
423
+ dbu: Database unit in microns. Defaults to 0.001 (1 nm).
424
+ layer: GDS layer specification as [layer_number, datatype]. Defaults to [1, 0].
425
+ """
426
+ import os
427
+ import klayout.db as pya
428
+
429
+ layout = pya.Layout()
430
+ layout.dbu = dbu # Set the database unit to 0.001 um
431
+ top_cell = layout.create_cell(self.name)
432
+ layer_info = pya.LayerInfo(layer[0], layer[1])
433
+ layer = layout.layer(layer_info)
434
+
435
+ for polygon in [s[0].polygon for s in self.structures if isinstance(s, list)]:
436
+ pya_polygon = pya.Polygon(
437
+ [
438
+ pya.Point(int(point[0] / layout.dbu), int(point[1] / layout.dbu))
439
+ for point in polygon
440
+ ]
441
+ )
442
+ top_cell.shapes(layer).insert(pya_polygon)
443
+
444
+ if export_dir is None:
445
+ export_dir = os.getcwd()
446
+ layout.write(os.path.join(export_dir, f"{self.name}.gds"))
447
+ return
448
+
449
+
450
+ class s_parameters:
451
+ def __init__(self, entries=None):
452
+ if entries is None:
453
+ self._entries = []
454
+ else:
455
+ self._entries = entries
456
+ return
457
+
458
+ @property
459
+ def S(self):
460
+ return dict(zip([i.label for i in self._entries], self._entries))
461
+
462
+ def add_param(self, sparam):
463
+ self._entries.append(sparam)
464
+
465
+ def entries_in_mode(self, mode_in=0, mode_out=0):
466
+ entries = []
467
+ for s in self._entries:
468
+ if s.mode_in == mode_in and s.mode_out == mode_out:
469
+ entries.append(s)
470
+ return entries
471
+
472
+ def entries_in_ports(self, input_entries=None, idx_in=0, idx_out=0):
473
+ entries = []
474
+ if input_entries == None:
475
+ input_entries = self._entries
476
+
477
+ for s in input_entries:
478
+ if s.idx_in == idx_in and s.idx_out == idx_out:
479
+ entries.append(s)
480
+ return entries
481
+
482
+ def plot(self):
483
+ fig, ax = plt.subplots(1, 1)
484
+ ax.set_xlabel("Wavelength [microns]")
485
+ ax.set_ylabel("Transmission [dB]")
486
+ for i in self._entries:
487
+ logging.info("Mode amplitudes in each port: \n")
488
+ mag = [10 * np.log10(abs(i) ** 2) for i in i.s]
489
+ phase = [np.angle(i) ** 2 for i in i.s]
490
+ ax.plot(1e6 * c0_um / i.freq, mag, label=i.label)
491
+ ax.legend()
492
+ fig.show()
493
+ return fig, ax
494
+
495
+ class sparam:
496
+ def __init__(self, idx_in, idx_out, mode_in, mode_out, freq, s):
497
+ self.idx_in = idx_in
498
+ self.idx_out = idx_out
499
+ self.mode_in = mode_in
500
+ self.mode_out = mode_out
501
+ self.freq = freq
502
+ self.s = s
503
+
504
+ @property
505
+ def label(self):
506
+ return f"S{self.idx_out}{self.idx_in}_idx{self.mode_out}{self.mode_in}"
507
+
508
+ def plot(self):
509
+ fig, ax = plt.subplots(1, 1)
510
+ ax.plot((1e-6 * c0_um) / np.array(self.freq), 10 * np.log10(self.s**2))
511
+ ax.set_xlabel("Wavelength [um]")
512
+ ax.set_ylabel("Transmission [dB]")
513
+ ax.set_title("Frequency vs S")
514
+ fig.show()
515
+ return fig, ax
516
+
517
+ def parse_yaml_tech(file_path):
518
+ with open(file_path, "r") as file:
519
+ data = yaml.safe_load(file)
520
+
521
+ technology = data.get("technology", {})
522
+ parsed_data = {
523
+ "name": technology.get("name", "Unknown"),
524
+ "substrate": [],
525
+ "superstrate": [],
526
+ "pinrec": [],
527
+ "devrec": [],
528
+ "device": [],
529
+ }
530
+
531
+ # Parsing substrate layer
532
+ substrate = technology.get("substrate", {})
533
+ parsed_data["substrate"].append(
534
+ {
535
+ "z_base": substrate.get("z_base"),
536
+ "z_span": substrate.get("z_span"),
537
+ "material": substrate.get("material"),
538
+ }
539
+ )
540
+
541
+ # Parsing superstrate layer
542
+ superstrate = technology.get("superstrate", {})
543
+ parsed_data["superstrate"].append(
544
+ {
545
+ "z_base": superstrate.get("z_base"),
546
+ "z_span": superstrate.get("z_span"),
547
+ "material": superstrate.get("material"),
548
+ }
549
+ )
550
+
551
+ # Parsing pinrec layers
552
+ parsed_data["pinrec"] = [
553
+ {"layer": list(pinrec.get("layer"))} # Convert to list
554
+ for pinrec in technology.get("pinrec", [])
555
+ ]
556
+
557
+ # Parsing devrec layers
558
+ parsed_data["devrec"] = [
559
+ {"layer": list(devrec.get("layer"))} # Convert to list
560
+ for devrec in technology.get("devrec", [])
561
+ ]
562
+
563
+ # Parsing device layers
564
+ parsed_data["device"] = [
565
+ {
566
+ "layer": list(device.get("layer")), # Convert to list
567
+ "z_base": device.get("z_base"),
568
+ "z_span": device.get("z_span"),
569
+ "material": device.get("material"),
570
+ "sidewall_angle": device.get("sidewall_angle"),
571
+ }
572
+ for device in technology.get("device", [])
573
+ ]
574
+
575
+ return parsed_data