-
Notifications
You must be signed in to change notification settings - Fork 183
/
component.py
1509 lines (1234 loc) · 49.2 KB
/
component.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
import datetime
import hashlib
import itertools
import pathlib
import tempfile
import uuid
import warnings
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
import gdspy
import numpy as np
import yaml
from numpy import int64
from omegaconf import DictConfig, OmegaConf
from phidl.device_layout import CellArray, Device, Label, _parse_layer
from typing_extensions import Literal
from gdsfactory.component_reference import ComponentReference, Coordinate, SizeInfo
from gdsfactory.config import CONF, logger
from gdsfactory.cross_section import CrossSection
from gdsfactory.layers import LAYER_COLORS, LayerColor, LayerColors
from gdsfactory.port import (
Port,
auto_rename_ports,
auto_rename_ports_counter_clockwise,
auto_rename_ports_layer_orientation,
auto_rename_ports_orientation,
map_ports_layer_to_orientation,
map_ports_to_orientation_ccw,
map_ports_to_orientation_cw,
select_ports,
)
from gdsfactory.serialization import clean_dict
from gdsfactory.snap import snap_to_grid
Plotter = Literal["holoviews", "matplotlib", "qt"]
Axis = Literal["x", "y"]
class MutabilityError(ValueError):
pass
mutability_error_message = """
You cannot modify a Component after creation as it will affect all of its instances.
Create a new Component and add a reference to it.
For example:
# BAD
c = gf.components.bend_euler()
c.add_ref(gf.components.mzi())
# GOOD
c = gf.Component()
c.add_ref(gf.components.bend_euler())
c.add_ref(gf.components.mzi())
"""
PathType = Union[str, Path]
Float2 = Tuple[float, float]
Layer = Tuple[int, int]
Layers = Tuple[Layer, ...]
LayerSpec = Union[str, int, Layer, None]
tmp = pathlib.Path(tempfile.TemporaryDirectory().name) / "gdsfactory"
tmp.mkdir(exist_ok=True, parents=True)
_timestamp2019 = datetime.datetime.fromtimestamp(1572014192.8273)
MAX_NAME_LENGTH = 32
class Component(Device):
"""A Component is like an empty canvas, where you can add polygons,
references to other Components and ports (to connect to other components).
- get/write YAML metadata
- get ports by type (optical, electrical ...)
- set data_analysis and test_protocols
Args:
name: component_name. Use @cell decorator for auto-naming.
version: component version.
changelog: changes from the last version.
Keyword Args:
with_uuid: adds unique identifier.
Properties:
info: dictionary that includes
- derived properties
- external metadata (test_protocol, docs, ...)
- simulation_settings
- function_name
- name: for the component
settings:
full: full settings passed to the function to create component.
changed: changed settings.
default: default component settings.
child: dict info from the children, if any.
"""
def __init__(
self,
name: str = "Unnamed",
version: str = "0.0.1",
changelog: str = "",
**kwargs,
) -> None:
self.__ports__ = {}
self.aliases = {}
self.uid = str(uuid.uuid4())[:8]
if "with_uuid" in kwargs or name == "Unnamed":
name += f"_{self.uid}"
super().__init__(name=name, exclude_from_current=True)
self.name = name # overwrite PHIDL's incremental naming convention
self.info: Dict[str, Any] = {}
self.settings: Dict[str, Any] = {}
self._locked = False
self.get_child_name = False
self.version = version
self.changelog = changelog
def __lshift__(self, element):
"""Convenience operator equivalent to add_ref()."""
return self.add_ref(element)
def unlock(self) -> None:
"""only do this if you know what you are doing."""
self._locked = False
def lock(self) -> None:
"""Makes sure components can't add new elements or move existing ones.
Components lock automatically when going into the CACHE to ensure one
component does not change others
"""
self._locked = True
@classmethod
def __get_validators__(cls):
yield cls.validate
@classmethod
def validate(cls, v):
"""pydantic assumes component is valid if:
- name characters < MAX_NAME_LENGTH
- is not empty (has references or polygons)
"""
MAX_NAME_LENGTH = 100
assert isinstance(
v, Component
), f"TypeError, Got {type(v)}, expecting Component"
assert (
len(v.name) <= MAX_NAME_LENGTH
), f"name `{v.name}` {len(v.name)} > {MAX_NAME_LENGTH} "
return v
def add_label(
self,
text: str = "hello",
position: Tuple[float, float] = (0.0, 0.0),
magnification: Optional[float] = None,
rotation: Optional[float] = None,
anchor: str = "o",
layer="TEXT",
) -> Label:
"""Adds Label to the Component.
Args:
text: Label text.
position: x-, y-coordinates of the Label location.
magnification:int, float, or None Magnification factor for the Label text.
rotation: Angle rotation of the Label text.
anchor: {'n', 'e', 's', 'w', 'o', 'ne', 'nw', ...}
Position of the anchor relative to the text.
layer: Specific layer(s) to put Label on.
"""
from gdsfactory.pdk import get_layer
layer = get_layer(layer)
gds_layer, gds_datatype = layer
if type(text) is not str:
text = text
label = Label(
text=text,
position=position,
anchor=anchor,
magnification=magnification,
rotation=rotation,
layer=gds_layer,
texttype=gds_datatype,
)
self.add(label)
return label
@property
def bbox(self):
"""Returns the bounding box of the ComponentReference.
it snaps to 3 decimals in um (0.001um = 1nm precision)
"""
bbox = self.get_bounding_box()
if bbox is None:
bbox = ((0, 0), (0, 0))
return np.round(bbox, 3)
@property
def ports_layer(self) -> Dict[str, str]:
"""Returns a mapping from layer0_layer1_E0: portName"""
return map_ports_layer_to_orientation(self.ports)
def port_by_orientation_cw(self, key: str, **kwargs):
"""Returns port by indexing them clockwise"""
m = map_ports_to_orientation_cw(self.ports, **kwargs)
if key not in m:
raise KeyError(f"{key} not in {list(m.keys())}")
key2 = m[key]
return self.ports[key2]
def port_by_orientation_ccw(self, key: str, **kwargs):
"""Returns port by indexing them clockwise"""
m = map_ports_to_orientation_ccw(self.ports, **kwargs)
if key not in m:
raise KeyError(f"{key} not in {list(m.keys())}")
key2 = m[key]
return self.ports[key2]
def get_ports_xsize(self, **kwargs) -> float:
"""Returns xdistance from east to west ports.
Keyword Args:
layer: port GDS layer.
prefix: with in port name.
orientation: in degrees.
width: port width.
layers_excluded: List of layers to exclude.
port_type: optical, electrical, ...
"""
ports_cw = self.get_ports_list(clockwise=True, **kwargs)
ports_ccw = self.get_ports_list(clockwise=False, **kwargs)
return snap_to_grid(ports_ccw[0].x - ports_cw[0].x)
def get_ports_ysize(self, **kwargs) -> float:
"""Returns ydistance from east to west ports.
Keyword Args:
layer: port GDS layer.
prefix: with in port name.
orientation: in degrees.
width: port width (um).
layers_excluded: List of layers to exclude.
port_type: optical, electrical, ...
"""
ports_cw = self.get_ports_list(clockwise=True, **kwargs)
ports_ccw = self.get_ports_list(clockwise=False, **kwargs)
return snap_to_grid(ports_ccw[0].y - ports_cw[0].y)
def plot_netlist(self, with_labels: bool = True, font_weight: str = "normal"):
"""Plots a netlist graph with networkx.
Args:
with_labels: add label to each node.
font_weight: normal, bold.
"""
import matplotlib.pyplot as plt
import networkx as nx
plt.figure()
netlist = self.get_netlist()
connections = netlist["connections"]
placements = netlist["placements"]
G = nx.Graph()
G.add_edges_from(
[
(",".join(k.split(",")[:-1]), ",".join(v.split(",")[:-1]))
for k, v in connections.items()
]
)
pos = {k: (v["x"], v["y"]) for k, v in placements.items()}
labels = {k: ",".join(k.split(",")[:1]) for k in placements.keys()}
nx.draw(
G,
with_labels=with_labels,
font_weight=font_weight,
labels=labels,
pos=pos,
)
return G
def get_netlist_yaml(self) -> str:
"""Return YAML netlist."""
return OmegaConf.to_yaml(self.get_netlist())
def write_netlist(self, filepath: str) -> None:
"""Write netlist in YAML"""
netlist = self.get_netlist()
OmegaConf.save(netlist, filepath)
def write_netlist_dot(self, filepath: Optional[str] = None) -> None:
"""Write netlist graph in DOT format."""
from networkx.drawing.nx_agraph import write_dot
filepath = filepath or f"{self.name}.dot"
G = self.plot_netlist()
write_dot(G, filepath)
def get_netlist(self, **kwargs) -> DictConfig:
"""Returns netlist dict config (instances, placements, connections, ports)
Keyword Args:
component: to extract netlist.
full_settings: True returns all, false changed settings.
layer_label: label to read instanceNames from (if any).
tolerance: tolerance in nm to consider two ports connected.
Returns:
instances: Dict of instance name and settings.
connections: Dict of Instance1Name,portName: Instace2Name,portName.
placements: Dict of instance names and placements (x, y, rotation).
port: Dict portName: ComponentName,port.
name: name of component.
"""
from gdsfactory.get_netlist import get_netlist
return get_netlist(component=self, **kwargs)
def get_netlist_dict(self, **kwargs) -> Dict[str, Any]:
return OmegaConf.to_container(self.get_netlist(**kwargs))
def get_netlist_recursive(self, **kwargs) -> Dict[str, DictConfig]:
"""Returns recursive netlist for a component and subcomponents.
Keyword Args:
component: to extract netlist.
component_suffix: suffix to append to each component name.
useful if to save and reload a back-annotated netlist.
get_netlist_func: function to extract individual netlists.
full_settings: True returns all, false changed settings.
layer_label: label to read instanceNames from (if any).
tolerance: tolerance in nm to consider two ports connected.
Returns:
Dictionary of netlists, keyed by the name of each component.
"""
from gdsfactory.get_netlist import get_netlist_recursive
return get_netlist_recursive(component=self, **kwargs)
def assert_ports_on_grid(self, nm: int = 1) -> None:
"""Asserts that all ports are on grid."""
for port in self.ports.values():
port.assert_on_grid(nm=nm)
def get_ports_dict(self, **kwargs) -> Dict[str, Port]:
"""Returns a dict of ports.
Keyword Args:
layer: port GDS layer.
prefix: for example "E" for east, "W" for west ...
"""
return select_ports(self.ports, **kwargs)
def get_ports_list(self, **kwargs) -> List[Port]:
"""Returns list of ports.
Keyword Args:
layer: select ports with GDS layer.
prefix: select ports with port name.
orientation: select ports with orientation in degrees.
width: select ports with port width.
layers_excluded: List of layers to exclude.
port_type: select ports with port_type (optical, electrical, vertical_te).
clockwise: if True, sort ports clockwise, False: counter-clockwise.
"""
return list(select_ports(self.ports, **kwargs).values())
def ref(
self,
position: Coordinate = (0, 0),
port_id: Optional[str] = None,
rotation: int = 0,
h_mirror: bool = False,
v_mirror: bool = False,
) -> "ComponentReference":
"""Returns Component reference.
Args:
position: x, y position.
port_id: name of the port.
rotation: in degrees.
h_mirror: horizontal mirror using y axis (x, 1) (1, 0).
This is the most common mirror.
v_mirror: vertical mirror using x axis (1, y) (0, y).
"""
_ref = ComponentReference(self)
if port_id and port_id not in self.ports:
raise ValueError(f"port {port_id} not in {self.ports.keys()}")
origin = self.ports[port_id].center if port_id else (0, 0)
if h_mirror:
_ref.reflect_h(port_id)
if v_mirror:
_ref.reflect_v(port_id)
if rotation != 0:
_ref.rotate(rotation, origin)
_ref.move(origin, position)
return _ref
def ref_center(self, position=(0, 0)):
"""returns a reference of the component centered at (x=0, y=0)"""
si = self.size_info
yc = si.south + si.height / 2
xc = si.west + si.width / 2
center = (xc, yc)
_ref = ComponentReference(self)
_ref.move(center, position)
return _ref
def __repr__(self) -> str:
return f"{self.name}: uid {self.uid}, ports {list(self.ports.keys())}, aliases {list(self.aliases.keys())}, {len(self.polygons)} polygons, {len(self.references)} references"
def pprint(self) -> None:
"""Prints component info."""
# print(OmegaConf.to_yaml(self.to_dict()))
print(yaml.dump(self.to_dict()))
def pprint_ports(self) -> None:
"""Prints component netlists."""
ports_list = self.get_ports_list()
for port in ports_list:
print(port)
@property
def metadata_child(self) -> DictConfig:
"""Returns metadata from child if any,
Otherwise returns component own metadata
Great to access the children metadata at the bottom
of the hierarchy.
"""
settings = dict(self.settings)
while settings.get("child"):
settings = settings.get("child")
return DictConfig(dict(settings))
@property
def metadata(self) -> DictConfig:
return DictConfig(dict(self.settings))
def add_port(
self,
name: Optional[Union[str, int, object]] = None,
center: Optional[Tuple[float, float]] = None,
width: Optional[float] = None,
orientation: Optional[float] = None,
port: Optional[Port] = None,
layer: LayerSpec = None,
port_type: str = "optical",
cross_section: Optional[CrossSection] = None,
) -> Port:
"""Add port to component.
You can copy an existing port like add_port(port = existing_port) or
create a new port add_port(myname, mycenter, mywidth, myorientation).
You can also copy an existing port
with a new name add_port(port = existing_port, name = new_name)
Args:
name: port name.
center: x, y.
width: in um.
orientation: in deg.
port: optional port.
layer: port layer.
port_type: optical, electrical, vertical_dc, vertical_te, vertical_tm.
cross_section: port cross_section.
"""
from gdsfactory.pdk import get_layer
layer = get_layer(layer)
if port:
if not isinstance(port, Port):
raise ValueError(f"add_port() needs a Port, got {type(port)}")
p = port.copy(new_uid=True)
if name is not None:
p.name = name
p.parent = self
elif isinstance(name, Port):
p = name.copy(new_uid=True)
p.parent = self
name = p.name
else:
if width is None:
raise ValueError("Port needs width parameter (um).")
if center is None:
raise ValueError("Port needs center parameter (x, y) um.")
half_width = width / 2
half_width_correct = snap_to_grid(half_width, nm=1)
if not np.isclose(half_width, half_width_correct):
warnings.warn(
f"port width = {width} will create off-grid points.\n"
f"You can fix it by changing width to {2*half_width_correct}\n"
f"port {name}, {center} {orientation} deg",
stacklevel=3,
)
p = Port(
name=name,
center=(snap_to_grid(center[0]), snap_to_grid(center[1])),
width=snap_to_grid(width),
orientation=orientation,
parent=self,
layer=layer,
port_type=port_type,
cross_section=cross_section,
)
if name is not None:
p.name = name
if p.name in self.ports:
raise ValueError(f"add_port() Port name {p.name!r} exists in {self.name!r}")
self.ports[p.name] = p
return p
def add_ports(
self, ports: Union[List[Port], Dict[str, Port]], prefix: str = ""
) -> None:
"""Add a list or dict of ports.
you can include a prefix to add to the new port names to avoid name conflicts.
Args:
ports: list or dict of ports.
prefix: to prepend to each port name.
"""
ports = ports if isinstance(ports, list) else ports.values()
for port in list(ports):
name = f"{prefix}{port.name}" if prefix else port.name
self.add_port(name=name, port=port)
def snap_ports_to_grid(self, nm: int = 1) -> None:
for port in self.ports.values():
port.snap_to_grid(nm=nm)
def remove_layers(
self,
layers: Union[List[Tuple[int, int]], Tuple[int, int]] = (),
include_labels: bool = True,
invert_selection: bool = False,
recursive: bool = True,
) -> "Component":
"""Remove a list of layers and returns the same Component.
Args:
layers: list of layers to remove.
include_labels: remove labels on those layers.
invert_selection: removes all layers except layers specified.
recursive: operate on the cells included in this cell.
"""
from gdsfactory.pdk import get_layer
layers = [_parse_layer(get_layer(layer)) for layer in layers]
all_D = list(self.get_dependencies(recursive))
all_D += [self]
for D in all_D:
for polygonset in D.polygons:
polygon_layers = zip(polygonset.layers, polygonset.datatypes)
polygons_to_keep = [(pl in layers) for pl in polygon_layers]
if not invert_selection:
polygons_to_keep = [(not p) for p in polygons_to_keep]
polygonset.polygons = [
p for p, keep in zip(polygonset.polygons, polygons_to_keep) if keep
]
polygonset.layers = [
p for p, keep in zip(polygonset.layers, polygons_to_keep) if keep
]
polygonset.datatypes = [
p for p, keep in zip(polygonset.datatypes, polygons_to_keep) if keep
]
paths = []
for path in D.paths:
paths.extend(
path
for layer in zip(path.layers, path.datatypes)
if layer not in layers
)
D.paths = paths
if include_labels:
new_labels = []
for label in D.labels:
original_layer = (label.layer, label.texttype)
original_layer = _parse_layer(original_layer)
if invert_selection:
keep_layer = original_layer in layers
else:
keep_layer = original_layer not in layers
if keep_layer:
new_labels += [label]
D.labels = new_labels
return self
def extract(
self,
layers: Union[List[Tuple[int, int]], Tuple[int, int]] = (),
) -> "Component":
"""Extract polygons from a Component and returns a new Component.
Adapted from phidl.geometry.
"""
from gdsfactory.name import clean_value
component = Component(f"{self.name}_{clean_value(layers)}")
if type(layers) not in (list, tuple):
raise ValueError("layers needs to be a list or tuple")
poly_dict = self.get_polygons(by_spec=True)
parsed_layer_list = [_parse_layer(layer) for layer in layers]
for layer, polys in poly_dict.items():
if _parse_layer(layer) in parsed_layer_list:
component.add_polygon(polys, layer=layer)
return component
def add_polygon(self, points, layer=np.nan):
"""Adds a Polygon to the Component.
Args:
points: Coordinates of the vertices of the Polygon.
layer: layer spec to add polygon on.
"""
from gdsfactory.pdk import get_layer
return super().add_polygon(points=points, layer=get_layer(layer))
def copy(self, prefix: str = "", suffix: str = "_copy") -> "Component":
from gdsfactory.copy import copy
return copy(self, prefix=prefix, suffix=suffix)
def copy_child_info(self, component: "Component") -> None:
"""Copy info from child component into parent.
Parent components can access child cells settings.
"""
if not isinstance(component, Component):
raise ValueError(f"{type(component)} is not a Component")
self.get_child_name = True
self.child = component
polarization = component.info.get("polarization")
wavelength = component.info.get("wavelength")
interconnect = component.info.get("interconnect")
if polarization:
self.info["polarization"] = polarization
if wavelength:
self.info["wavelength"] = wavelength
if interconnect:
self.info["interconnect"] = interconnect
@property
def size_info(self) -> SizeInfo:
"""size info of the component"""
return SizeInfo(self.bbox)
def get_setting(self, setting: str) -> Union[str, int, float]:
return (
self.info.get(setting)
or self.settings.full.get(setting)
or self.metadata_child.get(setting)
)
def is_unlocked(self) -> None:
"""Raises error if Component is locked"""
if self._locked:
raise MutabilityError(
f"Component {self.name!r} cannot be modified as it is already on cache. "
+ mutability_error_message
)
def add(self, element) -> None:
"""Add a new element or list of elements to this Component
Args:
element: `PolygonSet`, `CellReference`, `CellArray` or iterable
The element or iterable of elements to be inserted in this
cell.
Raises:
MutabilityError: if component is locked.
"""
self.is_unlocked()
super().add(element)
def add_array(
self,
component: "Component",
columns: int = 2,
rows: int = 2,
spacing: Tuple[float, float] = (100, 100),
alias: Optional[str] = None,
) -> CellArray:
"""Creates a CellArray reference to a Component.
Args:
component: The referenced component.
columns: Number of columns in the array.
rows: Number of rows in the array.
spacing: array-like[2] of int or float.
Distance between adjacent columns and adjacent rows.
alias: str or None. Alias of the referenced Component.
Returns
a: CellArray containing references to the Component.
"""
if not isinstance(component, Component):
raise TypeError("""add_array() needs a Component object. """)
ref = CellArray(
device=component,
columns=int(round(columns)),
rows=int(round(rows)),
spacing=spacing,
)
ref.owner = self
self.add(ref) # Add ComponentReference Component
if alias is not None:
self.aliases[alias] = ref
return ref
def flatten(self, single_layer: Optional[Tuple[int, int]] = None):
"""Returns a flattened copy of the component.
Flattens the hierarchy of the Component such that there are no longer
any references to other Components. All polygons and labels from
underlying references are copied and placed in the top-level Component.
If single_layer is specified, all polygons are moved to that layer.
Args:
single_layer: move all polygons are moved to the specified (optional).
"""
component_flat = self.copy()
component_flat.polygons = []
component_flat.references = []
poly_dict = self.get_polygons(by_spec=True)
for layer, polys in poly_dict.items():
component_flat.add_polygon(polys, layer=single_layer or layer)
component_flat.name = f"{self.name}_flat"
return component_flat
def add_ref(
self, component: "Component", alias: Optional[str] = None
) -> "ComponentReference":
"""Add ComponentReference to the current Component."""
if not isinstance(component, Device):
raise TypeError(f"type = {type(Component)} needs to be a Component.")
ref = ComponentReference(component)
ref.owner = self
self.add(ref)
if alias is not None:
self.aliases[alias] = ref
return ref
def get_layers(self) -> Union[Set[Tuple[int, int]], Set[Tuple[int64, int64]]]:
"""Return a set of (layer, datatype).
.. code ::
import gdsfactory as gf
gf.components.straight().get_layers() == {(1, 0), (111, 0)}
"""
layers = set()
for element in itertools.chain(self.polygons, self.paths):
for layer, datatype in zip(element.layers, element.datatypes):
layers.add((layer, datatype))
for reference in self.references:
for layer, datatype in reference.ref_cell.get_layers():
layers.add((layer, datatype))
for label in self.labels:
layers.add((label.layer, 0))
return layers
def _repr_html_(self):
"""Show geometry in klayout and in matplotlib
for jupyter notebooks
"""
self.show(show_ports=False) # show in klayout
self.plot(plotter="matplotlib")
return self.__repr__()
def plot(self, plotter: Optional[Plotter] = None, **kwargs) -> None:
"""Returns component plot.
Args:
plotter: backend ('holoviews', 'matplotlib', 'qt').
KeyError Args:
layers_excluded: list of layers to exclude.
layer_colors: layer_colors colors loaded from Klayout.
min_aspect: minimum aspect ratio.
"""
plotter = plotter or CONF.get("plotter", "matplotlib")
if plotter == "matplotlib":
from gdsfactory.quickplotter import quickplot as plot
return plot(self)
elif plotter == "holoviews":
try:
import holoviews as hv
hv.extension("bokeh")
except ImportError as e:
print("you need to `pip install holoviews`")
raise e
return self.ploth(**kwargs)
elif plotter == "qt":
from gdsfactory.quickplotter import quickplot2
return quickplot2(self)
def plotqt(self):
from gdsfactory.quickplotter import quickplot2
return quickplot2(self)
def ploth(
self,
layers_excluded: Optional[Layers] = None,
layer_colors: LayerColors = LAYER_COLORS,
min_aspect: float = 0.25,
padding: float = 0.5,
):
"""Plot component in holoviews.
Args:
layers_excluded: list of layers to exclude.
layer_colors: layer_colors colors loaded from Klayout.
min_aspect: minimum aspect ratio.
padding: around bounding box.
Returns:
Holoviews Overlay to display all polygons.
"""
from gdsfactory.add_pins import get_pin_triangle_polygon_tip
try:
import holoviews as hv
hv.extension("bokeh")
except ImportError as e:
print("you need to `pip install holoviews`")
raise e
self._bb_valid = False # recompute the bounding box
b = self.bbox + ((-padding, -padding), (padding, padding))
b = np.array(b.flat)
center = np.array((np.sum(b[::2]) / 2, np.sum(b[1::2]) / 2))
size = np.array((np.abs(b[2] - b[0]), np.abs(b[3] - b[1])))
dx = np.array(
(
np.maximum(min_aspect * size[1], size[0]) / 2,
np.maximum(size[1], min_aspect * size[0]) / 2,
)
)
b = np.hstack((center - dx, center + dx))
plots_to_overlay = []
layers_excluded = [] if layers_excluded is None else layers_excluded
for layer, polygon in self.get_polygons(by_spec=True).items():
if layer in layers_excluded:
continue
try:
layer = layer_colors.get_from_tuple(layer)
except ValueError:
layers = list(layer_colors._layers.keys())
warnings.warn(f"{layer!r} not defined in {layers}")
layer = LayerColor(gds_layer=layer[0], gds_datatype=layer[1])
plots_to_overlay.append(
hv.Polygons(polygon, label=str(layer.name)).opts(
data_aspect=1,
frame_width=500,
fill_alpha=layer.alpha,
ylim=(b[1], b[3]),
xlim=(b[0], b[2]),
color=layer.color,
line_alpha=layer.alpha,
tools=["hover"],
)
)
for name, port in self.ports.items():
name = str(name)
polygon, ptip = get_pin_triangle_polygon_tip(port=port)
plots_to_overlay.append(
hv.Polygons(polygon, label=name).opts(
data_aspect=1,
frame_width=500,
fill_alpha=0,
ylim=(b[1], b[3]),
xlim=(b[0], b[2]),
color="red",
line_alpha=layer.alpha,
tools=["hover"],
)
* hv.Text(ptip[0], ptip[1], name)
)
return hv.Overlay(plots_to_overlay).opts(
show_legend=True, shared_axes=False, ylim=(b[1], b[3]), xlim=(b[0], b[2])
)
def show(
self,
show_ports: bool = False,
show_subports: bool = False,
port_marker_layer: Layer = "SHOW_PORTS",
**kwargs,
) -> None:
"""Show component in klayout.
returns a copy of the Component, so the original component remains intact.
with pins markers on each port show_ports = True, and optionally also
the ports from the references (show_subports=True)
Args:
show_ports: shows component with port markers and labels.
show_subports: add ports markers and labels to references.
port_marker_layer: for the ports.
Keyword Args:
gdspath: GDS file path to write to.
gdsdir: directory for the GDS file. Defaults to /tmp/.
unit: unit size for objects in library. 1um by default.
precision: for object dimensions in the library (m). 1nm by default.
timestamp: Defaults to 2019-10-25. If None uses current time.
"""
from gdsfactory.add_pins import add_pins_triangle
from gdsfactory.show import show
if show_subports:
component = self.copy(suffix="")
for reference in component.references:
add_pins_triangle(
component=component,
reference=reference,
layer=port_marker_layer,
)
elif show_ports:
component = self.copy(suffix="")
add_pins_triangle(component=component, layer=port_marker_layer)
else:
component = self
show(component, **kwargs)
def to_3d(self, *args, **kwargs):
"""Returns Component 3D trimesh Scene.
Keyword Args:
component: to exture in 3D.
layer_colors: layer colors from Klayout Layer Properties file.
Defaults to active PDK.layer_colors.
layer_stack: contains thickness and zmin for each layer.
Defaults to active PDK.layer_stack.
exclude_layers: layers to exclude.