-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbb_util.py
1673 lines (1407 loc) · 58.1 KB
/
bb_util.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
#-----------------------------------------------------------------------
# This file is part of Nazca.
#
# Nazca is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# Nazca is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with Nazca. If not, see <http://www.gnu.org/licenses/>.
#-----------------------------------------------------------------------
#==============================================================================
# (c) 2016-2019 Ronald Broeke, Katarzyna Lawniczuk
#==============================================================================
"""Module with a set of Buiding Block templates for faciliating PDK creation."""
import os
from collections import OrderedDict
import inspect
from functools import wraps
from ast import literal_eval
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import json
import yaml
from pprint import pprint
from PIL import Image
import hashlib
import nazca as nd
from nazca import cfg
from nazca.logging import logger
from nazca.clipper import merge_polygons
#from nazca.util import parameters_to_string
import nazca.geometries as geom
#==============================================================================
# hash
#==============================================================================
_hash_id = None
_hash_params = {}
_hash_name = 'NONAME'
cfg._hashme = []
def hashme(*params):
"""Decorator to not regenerate a building block (cell) based on the same parameters.
The @hashme decorator can be used in cases of parametrized cells.
It checks if a function call (that returns a CEll) occured before
with the same parameters.
If that is the case @hashme will return a
reference to the previously created cell with these parameters,
rather than creating a full copy with a new cell name.
Example:
Usage of the hashme decorator::
@hashme('mycellname')
def parametrized_cell(W, L):
with nd.Cell(hashme=True) as C:
# cell stuff
nd.strt(length=L, width=W).put()
return C
parametrized_cell(W=3.0, L=10.0)
# cell_name ='mycellname'
Usage of hashme with adding keyword values to the cellname::
@hashme('mycellname', 'L', 'W')
def parametrized_cell(W, L):
with nd.Cell(hashme=True) as C:
# cell stuff
nd.strt(length=L, width=W).put()
return C
parametrized_cell(W=3.0, L=10.0)
# cell_name ='mycellname_10.0_3.0'
Parameters in the @hashme are str types.
The first parameter in @hashme is the cellname. The 2nd and more
parameters are optional names of the function call keywords.
If keyword names are added, the cellname will include them.
This is useful to add key metrics to the cell name.
In the decorated function the Cell creation can automatically access the
info created by @hashme, such as the cell name via nd.Cell(hashme=True).
Note: do *not* use any global parameters in a paramtrized function that is
decorated with hashme. I.e. put all parameters that may change the cell
in the function call. The reason is that a change of a global parameter
could possibly cause a different result of the generated cell without
being noticed.
Returns:
decorator
"""
hash_class_warning =\
"""Warning: @hashme decorator on Class method:
By default Nazca will guarantee a unique cell name each time a cell is created.
It does so by suffixing cell names with an ordinal counter.
This may result in multiple copies of the same cell, though,
where only one would do.
Decorating the cell generating function with @hashme avoids cell copies of
identical cells by returning an existing cell if the function has been
called with the same parameters earlier.
The @hashme 'state checker' can only be used safely if the state of the
function it decorates is *not* dependent on a state *external* to that
function, i.e. if the variations of the cell it generates *only* depend
on the function parameters. In contrast, Class methods typically depend
on attributes stored at class level, hence, by their very nature Class methods
do not fit well with the @hashme concept to guarantee unique cells for
unique names.
Example of a cell function where @hashme should NOT be used, i.e. in a class method:
class myElement():
# stuff
def make_cell(a, b, c):
# stuff
return cell_object
elm = myElement()
Now compare two ways place a cell multiple times.
* method 1:
elm.make_cell(a, b, c).put()
elm.make_cell(a, b, c).put()
a) creates two copies of the cell and suffixes the name with an ordinal counter.
b) if @hashme is used it returns an existing cell if the call profile
of make_cell has been used earlier.
* method 2:
A secure way in all cases to reuse cells is to call a cell generation function
only once and assign its returns value -the Cell object- to a variable.
Use this variable to put instances of the cells:
E = elm.cell(a, b, c)
E.put()
E.put()
"""
#print('params:' , params)
Npar = len(params)
if Npar == 0:
print('warning: no name given to @hashme')
name = 'NONAME'
else:
name = params[0]
params = params[1:]
def decorator(cellfunc):
"""Decorator for grabbing and hashing a function's full parameter list.
While executing the wrapper a global hashid and parameter list are set.
Before leaving the wrapper the hashid is reset to None.
Returns:
function: wrapper function
"""
@wraps(cellfunc)
def wrapper(*args, **kwargs):
global _hash_id
global _hash_params
global _hash_name
nonlocal name
if cfg.hashme:
raise Exception("Can not call an @hashme-decorated function before the Cell() call "\
"inside another @hashme decorated function. Move the function call(s) after the 'with Cell()' context.")
hash_length = 4
name_long = name
getargs = inspect.getfullargspec(cellfunc)
funcargs = getargs.args
funcdefaults = getargs.defaults
if funcdefaults is not None:
delta = len(funcargs) - len(funcdefaults)
else:
delta = len(funcargs)
hashstr = ''
_hash_params = OrderedDict()
if funcargs:
if funcargs[0] == 'self':
funcargs = funcargs[1:]
print(hash_class_warning)
for i, a in enumerate(funcargs):
if i < len(args):
default = args[i]
elif i-delta >= 0:
default = funcdefaults[i-delta]
else:
default = None
_hash_params[a] = kwargs.get(a, default)
for p in params:
if p in _hash_params.keys():
if isinstance(_hash_params[p], float):
#avoid formats like 0.0000000001 in names.
name_long += "_{:.5f}".format(_hash_params[p]).rstrip('0').rstrip('.')
else:
name_long += "_{}".format(_hash_params[p])
for p in sorted(_hash_params.keys()):
hashstr += '{}_{}'.format(p, _hash_params[p])
_hash_id = hashlib.md5(hashstr.encode()).hexdigest()[:hash_length]
else:
_hash_id = ''
if _hash_id != '':
_hash_name = "{}_${}".format(name_long, _hash_id)
else:
_hash_name = name_long
# add cfg to avoid explicit import of this module for hashme attributes
cfg.hashme = True
cfg.hash_id = _hash_id
cfg.hash_cellnameparams = params
cfg.hash_params = _hash_params
basename = cfg.gds_cellname_cleanup(name)
cfg.hash_basename = basename # base
cfg.hash_paramsname = cfg.gds_cellname_cleanup(name_long) # base + params
cfg.hash_name = cfg.gds_cellname_cleanup(_hash_name) # base + params + hash
cfg.hash_func_id = id(cellfunc)
# check if basename comes from a unique function:
try:
funcid = cfg.basenames[basename]
if funcid != cfg.hash_func_id:
logger.warning("Reusing a basename across function IDs: '{}'".
format(basename))
#raise
except KeyError:
logger.debug(f"Adding basename '{basename}' to cfg.basenames")
if cfg.validate_basename:
nd.validate_basename(basename)
# add basename:
cfg.basenames[basename] = cfg.hash_func_id
cell_exists = _hash_name in cfg.cellnames.keys()
if cell_exists:
cfg.hashme = False
return cfg.cellnames[_hash_name]
else:
cell_new = cellfunc(*args, **kwargs)
#reset:
_hash_id = None
_hash_params = {}
_hash_name = ''
cfg.hashme = False
cfg.hash_id = ''
cfg.hash_params = ''
cfg.hash_cellnameparams = {}
cfg.hash_basename = ''
cfg.hash_paramsname = ''
cfg.hash_name = ''
cfg.hash_func_id = None
return cell_new
return wrapper
return decorator
# create layers_ignore list to exclude layer from being part of bbox calculations:
cfg.bbox_layers_ignore = []
def bbox_layers_ignore(layers=None, reset=False):
"""Set the layers that should be ignore in bbox calculations."""
if layers is None:
layers = []
layerIDs = [nd.get_layer(ml) for ml in layers]
if reset:
cfg.bbox_layers_ignore = layerIDs
else:
cfg.bbox_layers_ignore.extend(layerIDs)
def get_Cell(name):
"""Get Cell object by providing cell name.
Args:
name (str): cell name
Returns:
Cell: cell having cellname <name>
"""
if name in cfg.cellnames.keys():
return cfg.cellnames[name]
else:
mes = f"Error: Requested cell with name '{name}' not existing. "\
f"Availabe are the following {len(cfg.cellnames)} cells: {sorted(cfg.cellnames.keys())}."
logger.exception(mes)
raise Exception(mes)
def rangecheck(allowed_values):
"""Check if parameter values are in range.
A dictionary with the allowed values for parameters is sent to rangecheck.
If any parameter is out of range, a ValueError will be raised and relevant
error info is provided to solve the issue.
Args:
allowed_values (dict): {'<var_name>': (low, <var_name>, high)},
where the key is the <varname> in a str type,
and low and high are the min and max values
Raises:
ValueError if out of range.
Returns:
None
Example:
Add a check in a function on 0 <= a <= 10 and -5 <= b <= 5.
The call will raise a ValueError::
def func(a, b):
nd.rangecheck({'a': (0, a, 10), 'b': (-5, b, 5)})
func(a=100, b=100)
# output:
# ValueError: a=100 too large. Allowed values: 0<=a<=10
# b=100 too large. Allowed values: -5<=b<=5
"""
err = ''
for varname, values in allowed_values.items():
if isinstance(values, tuple): # for backward compatibility
#logger.warning("obsolete, use ...")
if len(values) != 3:
raise ValueError(f"Need to provide 3 values, got {len(values)}")
else:
values= {
'min': values[0],
'default': values[1],
'max': values[2],
'type': None,
'doc': '',
'unit': '',
}
if values['default'] is None:
raise Exception(f"Value None is not allowed in rangecheck() in cell '{nd.cfg.cells[-1].cell_name}'.")
elif not isinstance(values, dict):
raise Exception (f"Expected type dict, not type '{type(values)}'.")
if values['type'] not in cfg.allowed_vartypes:
err += f"vartype '{values['type']}' unknown. Allowed vartypes: '{cfg.allowed_vartypes}'\n"
if values['min'] is None:
values['min'] = float('-inf')
if values['max'] is None:
values['max'] = float('inf')
#if low <= value <= high:
# continue
if values['default'] < values['min']:
err += f"{varname}={values['default']} too small. Allowed values: {values['min']}<={varname}<={values['max']}\n"
elif values['default'] > values['max']:
err += f"{varname}={values['default']} too large. Allowed values: {values['min']}<={varname}<={values['max']}\n"
# store variable info in cell for later use:
cell = nd.cfg.cells[-1]
cell.ranges[varname] = values
if err != '':
if cfg.rangecheck:
raise ValueError(err)
else:
logger.error(err, "continuing anyway (rangecheck is set to False).\n")
return None
#==============================================================================
#
#==============================================================================
stubs = dict() # dict of all stubs. {stub_name: stub_cell_obj}
stubmap = dict() # dict of xsection_name to its stub's xsection_name. {xs_name: stub_xs_name}
class Functional_group():
"""Class to group building blocks syntactically together.
Example:
Create bb_splitters group with various splitter components
such that the mmi can be found under bb_splitters.<tab>::
bb_splitters = Functional_group()
bb_splitters.mmi1x2 = mmi1x2
bb_splitters.mmi2x2 = mmi2x2
bb_splitters.mmi3x3 = mmi3x3
"""
def __init__(self, name=''):
"""Create a Functional group object."""
self.name = name
BB_Group = Functional_group
# Put in this module to avoid loading utils.py:
def parameters_to_string(param):
"""Create a string from a parameter dictionary.
Args:
param (dict): (parameter_name, value)
Note that the output format, i.e. inside the annotation object)
may be foundry specific depending on the setting of
cfg.parameter_style
'default' output format:
Parameters:
<parameter> = <value>
<parameter> = <value>
...
'yaml' output format:
<parameter>: <value>
<parameter>: <value>
...
Returns:
str: parameters as a string
"""
if cfg.parameter_style == 'yaml':
return yaml.dump(dict(param)) # change from ordered dict
elif cfg.parameter_style == 'hhi':
plist = []
for key, value in param.items():
plist.append("{}:{}".format(key, value))
return '\n'.join(plist)
elif cfg.parameter_style == 'default':
plist = ['Parameters:']
for key, value in param.items():
plist.append("{} = {}".format(key, value))
return '\n'.join(plist)
else:
nd.logger.error(f"cfg.parameter_style = '{cfg.parameter_style}' not recognized.")
def string_to_parameters(string):
"""Convert a string to a parameter dictionary.
The returned parameter values are represented as type str.
Expected format of <string>:
"parameters:
<parameter> = <value>
<parameter> = <value>
..."
Header 'parameters:' is case incensitive and spaces will be stripped.
Args:
string (str): parameters
Returns:
OrderedDict: {<parameter_name>: <parameter_value>}
"""
if cfg.parameter_style == 'default':
lines = string.split('\n')
p = OrderedDict()
if (lines[0].lower() == 'parameters:'):
for line in lines[1:]:
param = line.split('=', 1)
if len(param) == 2:
p[param[0].strip()] = param[1].strip()
else:
logger.error(
f"string_to_parameter: Expected one keyword "
f"and one value,\nbut found instead: {param}. "
f"Provided string instead: '{string}'"
)
else:
logger.exception(
f"string_to_parameter: "
f"Expected header 'parameters:', because cfg.parameter_style = '{cfg.parameter_style }'. "
f"Provided string instead: '{string}'"
)
return p
elif cfg.parameter_style == 'yaml':
p = yaml.load(string, Loader=yaml.Loader)
return p
else:
logger.error("string_to_parameter: "
"Expected header 'parameters:'\n"
)
return {}
def put_parameters(parameters=None, pin=None):
"""Put a parameter list as annotation in a building block.
Args:
parameters (dict): {parameter_name: value}
Returns:
Annotation: Annotation object with the parameterlist
"""
cell = cfg.cells[-1]
if isinstance(parameters, dict):
cell.parameters = parameters
text = parameters_to_string(cell.parameters)
elif cell.hashme:
text = parameters_to_string(cell.parameters)
else:
text = ''
if cfg.parameter_style == 'hhi' :
for i, plist in enumerate(text.split('\n')):
anno = nd.Annotation(text=plist, layer='bb_parameter_text')
if pin is None:
anno.put(0, 10*i)
else:
anno.put(pin.move(0, 5*i))
else: # standard
anno = nd.Annotation(text=text, layer='bb_parameter_text')
if pin is None:
anno.put(0)
else:
anno.put(pin)
return text
def cellname(cellname=None, length=0, width=None, align='lc', name_layer=None):
"""Create the cellname as a text cell.
Args:
cellname (str): name of the cell
length (float): length available for the BB name in um
width (float):
align (str): text alignment (see nazca.text, default = 'lc')
name_layer (str): name of the layer to be used for bbox name
Returns:
Cell: text with cellname
"""
cell = cfg.cells[-1]
if cellname is None:
cellname = cell.cell_paramsname
if width is not None:
maxheight = min(width*0.8, cfg.cellname_max_height)
else:
maxheight = cfg.cellname_max_height
if name_layer is None:
name_layer = 'bbox_name'
length = length * cfg.cellname_scaling
texth = min(maxheight, abs(length) / nd.linelength(cellname, 1))
txt = nd.text(cellname, texth, layer=name_layer, align=align)
return txt
#==============================================================================
# stubs and pins
#==============================================================================
def add_pinstyle(name, styledict):
"""Set a custom pin style for a technology.
Start with the style in <name> if existing, otherwise with the
default cfg.pinstyle settings and overrule these
for the keywords provided in the <styledict>.
Each pinstyle name will point to a unique dictionary internally.
Args:
name (str): pinstyle name
styledict (dict): pinstyle
Returns:
None
"""
present = nd.cfg.pinstyles.get(name, None)
if present is None:
present = nd.cfg.pinstyle
newstyle = present.copy()
keys = nd.cfg.pinstyle.keys()
if styledict is not None:
for item, setting in styledict.items():
if item in cfg.pinstylelabels:
newstyle[item] = setting
else:
logger.warning("No valid pinstyle key '{}' for pinstyle. Available keys: {}".\
format(item, cfg.pinstylelabels))
nd.cfg.pinstyles[name] = newstyle
# for backward compatibility:
raise_set_pinstyle = False
set_pinstyle_flag = False
def set_pinstyle(name, styledict):
global set_pinstyle_flag
if not set_pinstyle_flag:
print("Method set_pinstyle() is obsolete. Use add_pinstyle() instead."\
" Find the source of this issue by adding nd.raise_set_pinstyle=True after import nazca." )
if nd.raise_set_pinstyle:
raise Exception("set_pinstyle() is obsolete.")
add_pinstyle(name, styledict)
set_pinstyle_flag = True
add_pinstyle(name, styledict)
def add_pinshape(name, shape, overwrite=True):
"""Add a pin shape to the pinshapes dict.
Args:
name (str): reference name of the shape
shape (list of (float, float)): pin shape [(x1, y1), ...]
Returns:
None
"""
if name in cfg.pinshapes.keys() and not overwrite:
print(f"pinshape name '{name}' already exists. Use an other name of set overwrite=True.")
else:
cfg.pinshapes[name] = shape
def set_default_pinstyle(stylename):
"""Provide the name to use for the standard pinstyle.
The default standard style utilized in 'default'.
Returns:
None
"""
cfg.default_pinstyle = stylename
#@hashme('arrow', 'layer', 'pinshape', 'pinshape')
# Do NOT @hashme this function,
# because parameter values are finalized inside the function.
def make_pincell(layer=None, shape=None, size=None, style=None):
"""Create a cell to indicate a pin position.
The cell contains a shape, e.g. an arrow, to point out a location in the layout.
Available pin shapes are in a dictionary in cfg.pinshapes: {name: polygon}.
The predefined shapes have been normalized to unit size.
Args:
layer (float): layer number to place the pin symbol/shape
shape (str): name (dict key) of the pin symbol/shape
size (float): scaling factor of the pin symbol/shape
style (str):
Returns:
Cell: cell with pin symbol
"""
if style is not None:
pinstyle = cfg.pinstyles.get(style, None)
if pinstyle is None:
print("Error: pinstyle '{}' unknown. Known styles: {}".\
format(style, list(cfg.pinstyles.keys())))
pinstyle = cfg.pinstyles['default']
else:
pinstyle = cfg.pinstyles[cfg.default_pinstyle]
if shape is None:
shape_use= pinstyle['shape']
else:
shape_use = shape
if layer is None:
layer = pinstyle['layer']
layer = nd.get_layer(layer)
if size is None:
size = pinstyle['size']
#if cfg.black_pinstyle is not None:
# pinstyle = cfg.pinstyles[cfg.black_pinstyle]
# shape_use = cfg.pinstyles[cfg.black_pinstyle]['shape']
if shape_use not in cfg.pinshapes.keys():
mes = "arrowtype '{}' not recognized.".format(shape)
mes += "Available options are: {}.".format(cfg.pinshapes.keys())
mes += "Fall back type '{}' will be used.".format(shape_use)
logger.warning(mes)
shape = shape_use
name = "{}_{}_{}_{}".format('arrow', layer, shape, size)
name = cfg.gds_cellname_cleanup(name)
if name in cfg.cellnames.keys():
return cfg.cellnames[name]
with nd.Cell(name, instantiate=cfg.instantiate_pin, store_pins=False) as arrow:
arrow.auxiliary = True
outline = [(x*size, y*size) for x, y in cfg.pinshapes[shape]]
nd.Polygon(layer=layer, points=outline).put(0)
return arrow
def stubname(xs, width, thick, stubshape=None, pinshape=None, pinsize=None, pinlayer=None):
"""Construct a stub name.
Args:
xs (str); xsection name
width (float): stub width
thick (float): thickness of stub into cell (length)
Returns:
str: stub name
"""
if width is None:
return 'stub_{}'.format(xs)
else:
name = 'stub_{}_w{}_t{}_{}_{}_s{}_l{}'.\
format(xs, width, thick, stubshape, pinshape, pinsize, pinlayer)
return cfg.gds_cellname_cleanup(name)
missing_xs = []
def _makestub(xs_guide=None, width=0, length=2.0, shape=None, pinshape=None,
pinsize=None, pinlayer=None, cell=None, pinstyle=None):
"""Create a stub in the logical layers.
A stub is the stub of a xsection shape around a pin to visualize a connection.
A pincell is added to the stub to indicate the pin position inside the stub.
The new stub is added to the stubs dictionary: {name: stubcell}
Args:
xs_guide (str): name of xsection
width (float): stub width
thick (float): thickness of stub into cell (length)
shape (str): shape of the stub: 'box' | 'circ' (default = 'box')
pinshape (string): pinshape used in the stub
pinsize (float): scaling factor of the pinshape (default = 1)
cell (Cell): use the provided cell as stub instead of creating a new stub cell
Returns:
str: name of the stub
"""
if cfg.validation_stub_xs is not None:
xs_logic = cfg.validation_stub_xs
else:
xs_logic = cfg.stubmap.get(xs_guide, None)
if xs_logic is None: # if no stub defined, use the xs as its own stub.
if xs_guide is None: # no stub defined
arrow = make_pincell(
layer=pinlayer,
shape=pinshape,
size=pinsize,
style=pinstyle,
)
return arrow
xs_logic = xs_guide
if xs_guide not in cfg.XSdict.keys():
if xs_guide not in missing_xs:
missing_xs.append(xs_guide)
if xs_guide != cfg.default_xs_name:
logger.error("Can not make a stub in cell '{3}' in undefined xsection '{0}'.\n"\
" Possible causes: '{0}' is misspelled or not yet defined.\n"\
" Will use xsection '{2}' instead and continue.\n"
" To define a new xsection:\n"\
" add_xsection(name='{0}')\n"\
" or with layers info and adding a custom stub:\n"\
" add_xsection(name='{0}', layer=1)\n"\
" add_xsection(name='{1}', layer=2)\n"\
" add_stub(xsection='{0}', stub='{1}')".\
format(xs_guide, 'stubname', cfg.default_xs_name, cfg.cells[-1].cell_name))
xs_guide = cfg.default_xs_name
cfg.stubmap[xs_guide] = xs_guide
xs_logic = xs_guide
name = stubname(xs_guide, width, length, shape, pinshape, pinsize, pinlayer)
if name in stubs.keys():
return name
# make a new stub:
stubshapes = ['box', 'circle']
arrow = make_pincell(
layer=pinlayer,
shape=pinshape,
size=pinsize,
style=pinstyle,
)
if width is None:
width = 0
with nd.Cell(name, instantiate=cfg.instantiate_stub, store_pins=False) as C:
C.auxilliary = True
C.default_pins('a0', 'a0')
nd.Pin('a0', chain=0).put(0)
arrow.put(0)
if cell is not None:
cell.put()
else:
if length > 0:
for lay, grow, acc, polyline in nd.layeriter(xs_logic):
(a1, b1), (a2, b2), c1, c2 = grow
if shape == 'circle':
outline = geom.circle(radius=0.5*length, N=32)
else:
#outline = geom.box(width=width+(b1-b2), length=length)
outline = [(0, a2*width+b2), (0, a1*width+b1), (length, a1*width+b1), (length, a2*width+b2)]
if abs((a2*width+b2) - (a1*width+b1)) > 0.0001:
nd.Polygon(layer=lay, points=outline).put(0, 0, 180)
if shape not in stubshapes:
logger.warning("stub shape '{}' not recognized, possible options are {}.".
format(shape, stubshapes))
stubs[name] = C
return name # name can have change to default_xs
def put_stub(pinname=None, length=None, shape='box', pinshape=None, pinsize=None,
pinlayer=None, pinshow=True, annotation_layer=None, pinstyle=None):
"""Add a xsection stub to one or more pins.
The xsection and width of the stub is obtained from its pin attributes.
If no attributes are set, the stub layers are empty and the stubcell
only contains the pincell. It is possible to supply a list of pins.
The pinstyle is determined by the following sequence:
1. use the pinstyle of the xsection, if set
2. use the pinstyle 'default'
3. update the pinstyle with explicit settings via the keyword parameters
The pinshape is one of the following:
1. A reference to a key in the cfg.pinshapes dictionary which contains
the raisepin polygon description of which a pin cell is created.
2. A cell.
For a pin having attribute xs=None only the pin is drawn.
Args:
pinname (str | list of str | None): name(s) of the pin(s) (default = None)
For pinname=None (default) all chain-pins will obtain a stub.
length (float): length of the stub (thickness into cell)
shape (string | cell): shape of the stub 'box' | 'cirlce' (default = 'box')
pinshape (string): pinshape used in the stub
pinsize (float): scaling factor of the pinshape (default = 1)
layer (str | int | (int, int)): pin layer
annotation_layer (str | int | (int, int)): annotation layer
pinstyle (str): pin style used. Default it will look in the xsection
pinstyle setting. f that is None the pinstyle 'default' is used
pinshow (bool): set the pin show attribute (default=True)
Returns:
None
"""
cell = cfg.cells[-1] # active cell
# prepare pin:
if pinname is None or pinname == []:
pinname = [name for name, pin in cell.pin.items() if pin.chain == 1]
elif isinstance(pinname, str):
pinname = [pinname]
elif isinstance(pinname, nd.Node):
pinname = [pinname.name]
# prepare stub
if isinstance(shape, nd.Cell):
stubcell = shape
shape = shape.cell_name
else:
stubcell = None
# prepare pinstyles
stylestr = 'default'
if cfg.validation_pinstyle is not None:
pinstyle = cfg.validation_pinstyle
pinstylenames = cfg.pinstyles.keys()
if pinstyle in pinstylenames:
stylestr = pinstyle
elif pinstyle is not None:
logger.warning("pinstyle '{}' unknown. Using default instead. " \
"Known pinstyles: {}".format(pinstyle, pinstylenames))
for p in pinname:
try:
node = cell.pin[p]
node.show = pinshow # display pin name in layout and fingerprint
if stubcell is not None: # use existing Nazca cell for stub+pin
name = "stub_{}".format(shape)
if name not in stubs.keys():
stubs[name] = stubcell
stubs[name].put(node)
else:
if node.xs is None: # pin cell only, no stub
xs = None
width = 0
else: # define stub + pin from style
xs = node.xs
if cfg.validation_pinstyle is None:
xs_pinstyle = nd.get_xsection(xs).pinstyle
if xs_pinstyle in pinstylenames and pinstyle is None:
stylestr = xs_pinstyle
else:
stylestr = 'default'
if node.width is None:
width = 0
#TODO: why allow str widths here?
elif isinstance(node.width, str):
width = literal_eval(node.width)
else:
width = node.width
# make and place cell
if xs is None: # pin only
arrow = make_pincell(
layer=pinlayer,
shape=pinshape,
size=pinsize,
style=stylestr,
)
arrow.put(node)
else: # stub
if length is not None:
if isinstance(length, (float, int)):
stub_length = float(length)
else:
stubstyle = stylestr
if stubstyle is None:
stubstyle = 'default'
stub_length = nd.cfg.pinstyles[stubstyle].get('stub_length', 0)
if stub_length is None:
stub_length = 0.0
name = _makestub(
xs_guide=xs,
width=width,
length=stub_length,
shape=shape,
pinshape=pinshape,
pinsize=pinsize,
pinlayer=pinlayer,
pinstyle=stylestr,
)
# place stubs without drc check
drc = cfg.drc
cfg.drc = False
if node.io & 1:
stubs[name].put(node.rot(180), flip=True)
else:
stubs[name].put(node.rot(180))
cfg.drc = drc
# add annotation (keep outside of stub and pin cell):
if stylestr is None:
stylestr = 'default'
if annotation_layer is None:
annotation_layer = nd.cfg.pinstyles[stylestr]['annotation_layer']
# Move the annotation location for readability
drc = cfg.drc # switch off drc check for annotations
cfg.drc = False
nd.Annotation(layer=annotation_layer, text=p).\
put(node.move(*nd.cfg.pinstyles[stylestr]['annotation_move']))
if cfg.store_pin_attr:
if node.type != 'bbox':
text = f"name: {node.name}\nwidth: {node.width}\nxs: {node.xs}\nxya: {node.fxya(digits=6)}\nflip: {node.io}\nremark: {node.remark}"
nd.Annotation(layer='bb_pin_attr', text=text).put(node)
cfg.drc = drc
except Exception as E:
mes = "Can't add stub in cell '{}' on pin '{}'.".\
format(cell.cell_name, p)
logger.exception(mes)
raise Exception(E)
def validation_style(
on=True,
stub_layer=None,
pin_style=None,
validation_layermapmode="none",