-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnetlist_parser.py
1610 lines (1346 loc) · 47.3 KB
/
netlist_parser.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
# -*- coding: iso-8859-1 -*-
# netlist_parser.py
# Netlist parser module
# Copyright 2006 Giuseppe Venturini
# This file is part of the ahkab simulator.
#
# Ahkab is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# Ahkab 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License v2
# along with ahkab. If not, see <http://www.gnu.org/licenses/>.
"""Parse spice-like files, generate circuits instances and print them.
The syntax is explained in the docs and it's based on [1] whenever possible.
Ref. [1] http://newton.ex.ac.uk/teaching/CDHW/Electronics2/userguide/
"""
import sys, imp, math
import circuit, devices, printing, utilities, diode, mosq, ekv, plotting, options
def parse_circuit(filename, read_netlist_from_stdin=False):
"""Parse a SPICE-like netlist and return a circuit instance
that includes all components, all nodes known
with that you can recreate mna and N at any time.
Note that solving the circuit requires accessing to the elements in
the circuit instance to evaluate non linear elements' currents.
Directives are collected in a list and returned too, except for
subcircuits, those are added to circuit.subckts_dict.
Returns:
(circuit_instance, directives)
"""
# Lots of differences with spice's syntax:
# Support for alphanumeric node names, but the ref has to be 0. always
# Do not break lines with +
# .end is not required, but if is used anything following it is ignored
# many others, see doc.
circ = circuit.circuit(title="", filename=filename)
if not read_netlist_from_stdin:
ffile = open(filename, "r")
else:
ffile = sys.stdin
file_list = [(ffile, "unknown", not read_netlist_from_stdin)]
file_index = 0
directives = []
model_directives = []
postproc = []
subckts_list_temp = []
netlist_lines = []
current_subckt_temp = []
within_subckt = False
line_n = 0
try:
while ffile is not None:
for line in ffile:
line_n = line_n + 1
line = line.strip().lower()
if line_n == 1:
# the first line is always the title
circ.title = line
continue
elif len(line) == 0:
continue #empty line
elif line[0] == "*": # comments start with *
continue
# directives are grouped together and evaluated after
# we have the whole circuit.
# subcircuits are grouped too, but processed first
if line[0] == ".":
line_elements = line.split()
if line_elements[0] == '.subckt':
if within_subckt:
raise NetlistParseError, "nested subcircuit declaration detected"
current_subckt_temp = current_subckt_temp + [(line, line_n)]
within_subckt = True
elif line_elements[0] == '.ends':
if not within_subckt:
raise NetlistParseError, "corresponding .subckt not found"
within_subckt = False
subckts_list_temp.append(current_subckt_temp)
current_subckt_temp = []
elif line_elements[0] == '.include':
file_list.append(parse_include_directive(line, line_elements=None))
elif line_elements[0] == ".end":
break
elif line_elements[0] == ".plot":
postproc.append((line, line_n))
elif line_elements[0] == ".model":
model_directives.append((line, line_n))
else:
directives.append((line, line_n))
continue
if within_subckt:
current_subckt_temp = current_subckt_temp + [(line, line_n)]
else:
netlist_lines = netlist_lines + [(line, line_n)]
if within_subckt:
raise NetlistParseError, ".ends not found"
file_index = file_index + 1
ffile = get_next_file_and_close_current(file_list, file_index)
#print file_list
except NetlistParseError, (msg,):
if len(msg):
printing.print_general_error(msg)
printing.print_parse_error(line_n, line)
#if not read_netlist_from_stdin:
#ffile.close()
sys.exit(45)
#if not read_netlist_from_stdin:
#ffile.close()
models = parse_models(model_directives)
# now we parse the subcircuits, we want a circuit.subckt object that holds the netlist code,
# the nodes and the subckt name in a handy way.
# We will create all the elements in the subckt every time it is instantiated in the netlist file.
subckts_dict = {}
for subckt_temp in subckts_list_temp:
subckt_obj = parse_sub_declaration(subckt_temp)
if not subckts_dict.has_key(subckt_obj.name):
subckts_dict.update({subckt_obj.name:subckt_obj})
else:
raise NetlistParseError, "subckt " + subckt_obj.name + " has been redefined"
elements = main_netlist_parser(circ, netlist_lines, subckts_dict, models)
circ.elements = circ.elements + elements
return (circ, directives, postproc)
def main_netlist_parser(circ, netlist_lines, subckts_dict, models):
elements = []
try:
for (line, line_n) in netlist_lines:
# elements: detect the element type and call the
# appropriate parsing function
# we always use normal convention V opposite to I
# n1 is +, n2 is -, current flows from + to -
line_elements = line.split()
if line[0] == "r":
elements = elements + \
parse_elem_resistor(line, circ, line_elements)
elif line[0] == "c":
elements = elements + \
parse_elem_capacitor(line, circ, line_elements)
elif line[0] == "l":
elements = elements + \
parse_elem_inductor(line, circ, line_elements)
elif line[0] == "k":
elements = elements + \
parse_elem_inductor_coupling(line, circ, \
line_elements, elements)
elif line[0] == "v":
elements = elements + \
parse_elem_vsource(line, circ, line_elements)
elif line[0] == "i":
elements = elements + \
parse_elem_isource(line, circ, line_elements)
elif line[0] == "d":
elements = elements + \
parse_elem_diode(line, circ, line_elements, models)
elif line[0] == 'm': #mosfet
elements = elements + \
parse_elem_mos(line, circ, line_elements, models)
elif line[0] == "e": #vcvs
elements = elements + \
parse_elem_vcvs(line, circ, line_elements)
elif line[0] == "g": #vccs
elements = elements + \
parse_elem_vccs(line, circ, line_elements)
elif line[0] == "y": #User defined module -> MODIFY
elements = elements + \
parse_elem_user_defined(line, circ, line_elements)
elif line[0] == "x": #User defined module -> MODIFY
elements = elements + \
parse_sub_instance(line, circ, subckts_dict, line_elements, models)
else:
raise NetlistParseError, "unknown element."
except NetlistParseError, (msg,):
if len(msg):
printing.print_general_error(msg)
printing.print_parse_error(line_n, line)
sys.exit(45)
return elements
def get_next_file_and_close_current(file_list, file_index):
if file_list[file_index - 1][2]:
file_list[file_index - 1][0].close()
if file_index == len(file_list):
ffile = None
else:
ffile = open(file_list[file_index][1], "r")
file_list[file_index][0] = ffile
return ffile
def parse_models(models_lines):
models = {}
for line, line_n in models_lines:
tokens = line.split()
if len(tokens) < 3:
raise NetlistParseError, ("Syntax error in model declaration on line " + str(line_n) + ".\n\t"+line,)
model_label = tokens[2]
model_type = tokens[1]
model_parameters = {}
for index in range(3, len(tokens)):
if tokens[index][0] == "*":
break
(label, value) = parse_param_value_from_string(tokens[index])
model_parameters.update({label.upper():value})
if model_type == "ekv":
model_iter = ekv.ekv_mos_model(**model_parameters)
model_iter.name = model_label
elif model_type == "mosq":
model_iter = mosq.mosq_mos_model(**model_parameters)
model_iter.name = model_label
elif model_type == "diode":
model_parameters.update({'name':model_label})
model_iter = diode.diode_model(**model_parameters)
else:
raise NetlistParseError, ("Unknown model ("+model_type+") on line " + str(line_n) + ".\n\t"+line,)
models.update({model_label:model_iter})
return models
def parse_elem_resistor(line, circ, line_elements=None):
"""Parses a resistor from the line supplied, adds its nodes to the circuit
instance circ and returns a list holding the resistor element.
Parameters:
line: the line, if you have already .split()-ed it, set this to None
and supply the elements through line_elements.
circ: the circuit instance.
line_elements: will be generated by the function from line.split()
if set to None.
Returns: [resistor_elem]
"""
if line_elements is None:
line_elements = line.split()
if (len(line_elements) < 4) or (len(line_elements) > 4 and not line_elements[4][0] == "*"):
raise NetlistParseError, ""
ext_n1 = line_elements[1]
ext_n2 = line_elements[2]
n1 = circ.add_node(ext_n1)
n2 = circ.add_node(ext_n2)
R = convert_units(line_elements[3])
if R == 0:
raise NetlistParseError, "ZERO-valued resistors are not allowed."
elem = devices.resistor(n1=n1, n2=n2, R=R)
elem.descr = line_elements[0][1:]
return [elem]
def parse_elem_capacitor(line, circ, line_elements=None):
"""Parses a capacitor from the line supplied, adds its nodes to the circuit
instance circ and returns a list holding the capacitor element.
Parameters:
line: the line, if you have already .split()-ed it, set this to None
and supply the elements through line_elements.
circ: the circuit instance.
line_elements: will be generated by the function from line.split()
if set to None.
Returns: [capacitor_elem]
"""
if line_elements is None:
line_elements = line.split()
if (len(line_elements) < 4) or (len(line_elements) > 5 and not line_elements[6][0]=="*"):
raise NetlistParseError, ""
ic = None
if len(line_elements) == 5 and not line_elements[4][0] == '*':
(label, value) = parse_param_value_from_string(line_elements[4])
if label == "ic":
ic = convert_units(value)
else:
raise NetlistParseError, "unknown parameter " + label
ext_n1 = line_elements[1]
ext_n2 = line_elements[2]
n1 = circ.add_node(ext_n1)
n2 = circ.add_node(ext_n2)
elem = devices.capacitor(n1=n1, n2=n2, C=convert_units(line_elements[3]), ic=ic)
elem.descr = line_elements[0][1:]
return [elem]
def parse_elem_inductor(line, circ, line_elements=None):
"""Parses a inductor from the line supplied, adds its nodes to the circuit
instance circ and returns a list holding the inductor element.
Parameters:
line: the line, if you have already .split()-ed it, set this to None
and supply the elements through line_elements.
circ: the circuit instance.
line_elements: will be generated by the function from line.split()
if set to None.
Returns: [inductor_elem]
"""
if line_elements is None:
line_elements = line.split()
if (len(line_elements) < 4) or (len(line_elements) > 5 and not line_elements[6][0]=="*"):
raise NetlistParseError, ""
ic = None
if len(line_elements) == 5 and not line_elements[4][0] == '*':
(label, value) = parse_param_value_from_string(line_elements[4])
if label == "ic":
ic = convert_units(value)
else:
raise NetlistParseError, "unknown parameter " + label
ext_n1 = line_elements[1]
ext_n2 = line_elements[2]
n1 = circ.add_node(ext_n1)
n2 = circ.add_node(ext_n2)
elem = devices.inductor(n1=n1, n2=n2, L=convert_units(line_elements[3]), ic=ic)
elem.descr = line_elements[0][1:]
return [elem]
def parse_elem_inductor_coupling(line, circ, line_elements=None, elements=[]):
"""Parses a inductor coupling from the line supplied,
returns a list holding the element.
Parameters:
line: the line, if you have already .split()-ed it, set this to None
and supply the elements through line_elements.
circ: the circuit instance.
line_elements: will be generated by the function from line.split()
if set to None.
Returns: [inductor_coupling_elem]
"""
if line_elements is None:
line_elements = line.split()
if (len(line_elements) < 4) or (len(line_elements) > 4 and not line_elements[5][0]=="*"):
raise NetlistParseError, ""
name = line_elements[0]
L1 = line_elements[1]
L2 = line_elements[2]
try:
Kvalue = convert_units(line_elements[3])
except ValueError:
(label, value) = parse_param_value_from_string(line_elements[3])
if not label == "k":
raise NetlistParseError, "unknown parameter " + label
Kvalue = convert_units(value)
L1descr = L1[1:]
L2descr = L2[1:]
L1elem, L2elem = None, None
for e in elements:
if isinstance(e, devices.inductor) and L1descr == e.descr:
L1elem = e
elif isinstance(e, devices.inductor) and L2descr == e.descr:
L2elem = e
if L1elem is None or L2elem is None:
error_msg = "One or more coupled inductors for %s were not found: %s (found: %s), %s (found: %s)." % \
(name, L1, L1elem is not None, L2, L2elem is not None)
printing.print_general_error(error_msg)
raise NetlistParseError, ""
M = math.sqrt(L1elem.L * L2elem.L) * Kvalue
elem = devices.inductor_coupling(L1=L1, L2=L2, K=Kvalue, M=M)
elem.descr = name[1:]
L1elem.coupling_devices.append(elem)
L2elem.coupling_devices.append(elem)
return [elem]
def parse_elem_vsource(line, circ, line_elements=None):
"""Parses a vsource from the line supplied, adds its nodes to the circuit
instance circ and returns a list holding the vsource element.
Parameters:
line: the line, if you have already .split()-ed it, set this to None
and supply the elements through line_elements.
circ: the circuit instance.
line_elements: will be generated by the function from line.split()
if set to None.
Returns: [vsource_elem]
"""
if line_elements is None:
line_elements = line.split()
if len(line_elements) < 3:
raise NetlistParseError, ""
vdc = None
vac = None
function = None
index = 3
while True: #for index in range(3, len(line_elements)):
if index == len(line_elements):
break
if line_elements[index][0] == '*':
break
(label, value) = parse_param_value_from_string(line_elements[index])
if label == 'type':
if value == 'vdc':
param_number = 0
elif value == 'vac':
param_number = 0
elif value == 'pulse':
param_number = 7
elif value == 'exp':
param_number = 6
elif value == 'sin':
param_number = 5
else:
raise NetlistParseError, "unknown signal type."
if param_number and function is None:
function = parse_time_function(value, line_elements[index+1:index+param_number+1], "voltage")
index = index + param_number
#continue
elif function is not None:
raise NetlistParseError, "only a time function can be defined."
elif label == 'vdc':
vdc = convert_units(value)
elif label == 'vac':
vac = convert_units(value)
else:
raise NetlistParseError, ""
index = index + 1
if vdc == None and function == None:
raise NetlistParseError, "neither vdc nor a time function are defined."
#usual
ext_n1 = line_elements[1]
ext_n2 = line_elements[2]
n1 = circ.add_node(ext_n1)
n2 = circ.add_node(ext_n2)
elem = devices.vsource(n1=n1, n2=n2, vdc=vdc, abs_ac=vac)
elem.descr = line_elements[0][1:]
if function is not None:
elem.is_timedependent = True
elem._time_function = function
return [elem]
def parse_elem_isource(line, circ, line_elements=None):
"""Parses a isource from the line supplied, adds its nodes to the circuit
instance circ and returns a list holding the isource element.
Parameters:
line: the line, if you have already .split()-ed it, set this to None
and supply the elements through line_elements.
circ: the circuit instance.
line_elements: will be generated by the function from line.split()
if set to None.
Returns: [isource_elem]
"""
if line_elements is None:
line_elements = line.split()
if len(line_elements) < 3:
raise NetlistParseError, ""
idc = None
iac = None
function = None
index = 3
while True: #for index in range(3, len(line_elements)):
if index == len(line_elements):
break
if line_elements[index][0] == '*':
break
(label, value) = parse_param_value_from_string(line_elements[index])
if label == 'type':
if value == 'idc':
param_number = 0
elif value == 'iac':
param_number = 0
elif value == 'pulse':
param_number = 7
elif value == 'exp':
param_number = 6
elif value == 'sin':
param_number = 5
else:
raise NetlistParseError, "unknown signal type."
if param_number and function is None:
function = parse_time_function(value, line_elements[index+1:index+param_number+1], "current")
index = index + param_number
elif function is not None:
raise NetlistParseError, "only a time function can be defined."
elif label == 'idc':
idc = convert_units(value)
elif label == 'iac':
iac = convert_units(value)
else:
raise NetlistParseError, ""
index = index + 1
if idc == None and function == None:
raise NetlistParseError, "neither idc nor a time function are defined."
ext_n1 = line_elements[1]
ext_n2 = line_elements[2]
n1 = circ.add_node(ext_n1)
n2 = circ.add_node(ext_n2)
elem = devices.isource(n1=n1, n2=n2, idc=idc, abs_ac=iac)
elem.descr = line_elements[0][1:]
if function is not None:
elem.is_timedependent = True
elem._time_function = function
return [elem]
def parse_elem_diode(line, circ, line_elements=None, models=None):
"""Parses a diode from the line supplied, adds its nodes to the circuit
instance circ and returns a list holding the diode element and a resistor,
if the diode has Rs != 0.
Diode syntax:
#DX N+ N- <MODEL_LABEL> <AREA=xxx>
Parameters:
line: the line, if you have already .split()-ed it, set this to None
and supply the elements through line_elements.
circ: the circuit instance.
line_elements: will be generated by the function from line.split()
if set to None.
Returns: a list with the diode element and a optional resistor Rs
"""
#sarebbe bello implementare anche: <IC=VD> <TEMP=T>
if line_elements is None:
line_elements = line.split()
Area = None
T = None
ic = None
off = False
if (len(line_elements) < 4):
raise NetlistParseError, ""
model_label = line_elements[3]
for index in range(4, len(line_elements)):
if line_elements[index][0] == '*':
break
(param, value) = parse_param_value_from_string(line_elements[index])
value = convert_units(value)
if param == "area":
Area = value
elif param == "t":
T = value
elif param == "ic":
ic = value
elif param == "off":
if not len(value):
off = True
else:
off = convert_boolean(value)
else:
raise NetlistParseError, "unknown parameter " + param
ext_n1 = line_elements[1]
ext_n2 = line_elements[2]
n1 = circ.add_node(ext_n1)
n2 = circ.add_node(ext_n2)
#if Rs: #we need to add a Rs on the anode
# new_node = n1
# n1 = circ.generate_internal_only_node_label()
# #print "-<<<<<<<<"+str(n1)+" "+str(n2) +" "+str(new_node)
# rs_elem = devices.resistor(n1=new_node, n2=n1, R=Rs)
# rs_elem.descr = "INT"
# return_list = return_list + [rs_elem]
if not models.has_key(model_label):
raise NetlistParseError, "Unknown model id: "+model_label
elem = diode.diode(n1=n1, n2=n2, model=models[model_label], AREA=Area, T=T, ic=ic, off=off)
elem.descr = line_elements[0][1:]
return [elem]
def parse_elem_mos(line, circ, line_elements, models):
"""Parses a mos from the line supplied, adds its nodes to the circuit
instance circ and returns a list holding the mos element.
MOS syntax:
MX ND NG NS KP=xxx Vt=xxx W=xxx L=xxx type=n/p <LAMBDA=xxx>
Parameters:
line: the line, if you have already .split()-ed it, set this to None
and supply the elements through line_elements.
circ: the circuit instance.
line_elements: will be generated by the function from line.split()
if set to None.
Returns: [mos_elem]
"""
#sarebbe bello implementare anche: <IC=VD> <TEMP=T>
#(self, nd, ng, ns, kp=1.0e-14, w, l, mos_type='n', lambd=0, type_of_elem="mosq")
if line_elements is None:
line_elements = line.split()
if (len(line_elements) < 6):
raise NetlistParseError, "required parameters are missing."
#print "MX ND NG NS model_id W=xxx L=xxx"
model_label = line_elements[5]
#kp = None
w = None
l = None
#mos_type = None
#vt = None
m = 1
n = 1
#lambd = 0 # va is supposed infinite if not specified
for index in range(6, len(line_elements)):
if line_elements[index][0] == '*':
break
(param, value) = parse_param_value_from_string(line_elements[index])
#if param == 'kp':
# kp = convert_units(value)
if param == "w":
w = convert_units(value)
elif param == "l":
l = convert_units(value)
#elif param == "vt":
# vt = convert_units(value)
elif param == "m":
m = convert_units(value)
#elif param == "vt":
# n = convert_units(value)
#elif param == "type":
# if value != 'n' and value != 'p':
# raise NetlistParseError, "unknown mos type "+value
# mos_type = value
else:
raise NetlistParseError, "unknown parameter " + param
if (w is None) or (l is None):
raise NetlistParseError, "required parameter is missing."
#print "MX ND NG NS W=xxx L=xxx <LAMBDA=xxx>"
ext_nd = line_elements[1]
ext_ng = line_elements[2]
ext_ns = line_elements[3]
ext_nb = line_elements[4]
nd = circ.add_node(ext_nd)
ng = circ.add_node(ext_ng)
ns = circ.add_node(ext_ns)
nb = circ.add_node(ext_nb)
if not models.has_key(model_label):
raise NetlistParseError, "Unknown model id: "+model_label
if isinstance(models[model_label], ekv.ekv_mos_model):
elem = ekv.ekv_device(nd, ng, ns, nb, w, l, models[model_label], m, n)
elif isinstance(models[model_label], mosq.mosq_mos_model):
elem = mosq.mosq_device(nd, ng, ns, nb, w, l, models[model_label], m, n)
else:
raise NetlistParseError, "Unknown MOS model type: "+model_label
elem.descr = line_elements[0][1:]
return [elem]
def parse_elem_vcvs(line, circ, line_elements=None):
"""Parses a voltage controlled voltage source (vcvs) from the line
supplied, adds its nodes to the circuit instance circ and returns a
list holding the vcvs element.
Parameters:
line: the line, if you have already .split()-ed it, set this to None
and supply the elements through line_elements.
circ: the circuit instance.
line_elements: will be generated by the function from line.split()
if set to None.
Returns: [vcvs_elem]
"""
if line_elements is None:
line_elements = line.split()
if (len(line_elements) < 6) or (len(line_elements) > 6 and not line_elements[6][0] == "*"):
raise NetlistParseError, ""
ext_n1 = line_elements[1]
ext_n2 = line_elements[2]
ext_sn1 = line_elements[3]
ext_sn2 = line_elements[4]
n1 = circ.add_node(ext_n1)
n2 = circ.add_node(ext_n2)
sn1 = circ.add_node(ext_sn1)
sn2 = circ.add_node(ext_sn2)
elem = devices.evsource(n1=n1, n2=n2, sn1=sn1, sn2=sn2, alpha=convert_units(line_elements[5]))
elem.descr = line_elements[0][1:]
return [elem]
def parse_elem_vccs(line, circ, line_elements=None):
"""Parses a voltage controlled current source (vccs) from the line
supplied, adds its nodes to the circuit instance circ and returns a
list holding the vccs element.
Syntax:
GX N+ N- NC+ NC- VALUE
Parameters:
line: the line, if you have already .split()-ed it, set this to None
and supply the elements through line_elements.
circ: the circuit instance.
line_elements: will be generated by the function from line.split()
if set to None.
Returns: [vccs_elem]
"""
if line_elements is None:
line_elements = line.split()
if (len(line_elements) < 6) or (len(line_elements) > 6 \
and not line_elements[6][0]=="*"):
raise NetlistParseError, ""
ext_n1 = line_elements[1]
ext_n2 = line_elements[2]
ext_sn1 = line_elements[3]
ext_sn2 = line_elements[4]
n1 = circ.add_node(ext_n1)
n2 = circ.add_node(ext_n2)
sn1 = circ.add_node(ext_sn1)
sn2 = circ.add_node(ext_sn2)
elem = devices.gisource(n1=n1, n2=n2, sn1=sn1, sn2=sn2, alpha=convert_units(line_elements[5]))
elem.descr = line_elements[0][1:]
return [elem]
def parse_elem_user_defined(line, circ, line_elements=None):
"""Parses a user defined element.
In order for this to work, you should write a module that supplies the
elem class.
Syntax:
Y<X> <n1> <n2> module=<module_name> type=<type> [<param1>=<value1> ...]
This method will attempt to load the module <module_name> and it will
then look for a class named <type>.
An object will be instatiated with the following arguments:
n1, n2, param_dict, get_int_id_func, convert_units_func
Where:
n1: is the anode of the element
n2: is the cathode
param_dict: is a dictionary, its elements are {param1:value1, ...}
get_int_id_func, convert_units_func are two function that may be used
in the __init__ method, if needed.
get_int_id_func: a function that gives back the internal name of a node
convert_units_func: utility function to convert eg 1p -> 1e-12
See ideal_oscillators.py for a reference implementation.
Parameters:
line: the line, if you have already .split()-ed it, set this to None
and supply the elements through line_elements.
circ: the circuit instance.
line_elements: will be generated by the function from line.split()
if set to None.
Returns: [userdef_elem]
"""
if line_elements is None:
line_elements = line.split()
if len(line_elements) < 4:
raise NetlistParseError, ""
param_dict = {}
for index in range(3, len(line_elements)):
if line_elements[index][0] == '*':
break
(param, value) = parse_param_value_from_string(line_elements[index])
if not param_dict.has_key(param):
param_dict.update({param:value})
else:
raise NetlistParseError, param+" already defined."
if param_dict.has_key("module"):
module_name = param_dict.pop("module", None)
else:
raise NetlistParseError, "module name is missing."
if circuit.user_defined_modules_dict.has_key(module_name):
module = circuit.user_defined_modules_dict[module_name]
else:
try:
fp, pathname, description = imp.find_module(module_name)
module = imp.load_module(module_name, fp, pathname, description)
except ImportError:
raise NetlistParseError, "module " + module_name + " not found."
circuit.user_defined_modules_dict.update({module_name:module})
if param_dict.has_key("type"):
elem_type_name = param_dict.pop("type", None)
else:
raise NetlistParseError, "type of element is missing."
try:
elem_class = getattr(module, elem_type_name)
except AttributeError:
raise NetlistParseError, "module doesn't have elem type: "+ elem_type_name
ext_n1 = line_elements[1]
ext_n2 = line_elements[2]
n1 = circ.add_node(ext_n1)
n2 = circ.add_node(ext_n2)
elem = elem_class(n1, n2, param_dict, circ.add_node, convert_units)
elem.descr = line_elements[0][1:]
elem.letter_id = "y"
selfcheck_result, error_msg = elem.check()
if not selfcheck_result:
raise NetlistParseError, "module: " + module_name + " elem type: "+ elem_type_name+" error: "+\
error_msg
#fixme non so sicuro che sia una buona idea
return [elem]
def parse_time_function(ftype, line_elements, stype):
"""Parses a time function of type ftype from the line_elements supplied.
ftype: a string, one among "pulse", "exp", "sin"
line_elements: mustn't hold the "type=<ftype>" element
stype: set this to "current" for current sources, "voltage" for voltage sources
See devices.pulse, devices.sin, devices.exp for more.
Returns: a time-<function instance
"""
if ftype == 'pulse':
function = parse_pulse_time_function(line_elements, stype)
elif ftype == 'exp':
function = parse_exp_time_function(line_elements, stype)
elif ftype == 'sin':
function = parse_sin_time_function(line_elements, stype)
else:
raise NetlistParseError, "unknown signal type."
# This way it knows if it is a v/i source in __str__
function._type = "V"*(stype.lower()=="voltage") + "I"*(stype.lower()=="current")
return function
def parse_pulse_time_function(line_elements, stype):
"""This is called by parse_time_function() to actually parse this
type of functions.
"""
function = devices.pulse()
for token in line_elements:
(param, value) = parse_param_value_from_string(token)
if stype == "voltage" and param == 'v1' or stype == "current" \
and param == 'i1':
function.v1 = convert_units(value)
elif stype == "voltage" and param == 'v2' or stype == "current" \
and param == 'i2':
function.v2 = convert_units(value)
elif param == 'td':
function.td = convert_units(value)
elif param == 'per':
function.per = convert_units(value)
elif param == 'tr':
function.tr = convert_units(value)
elif param == 'tf':
function.tf = convert_units(value)
elif param == 'pw':
function.pw = convert_units(value)
else:
raise NetlistParseError, "unknown param for time function pulse: "+param
if not function.ready():
raise NetlistParseError, \
"required parameters are missing for time function pulse."
return function
def parse_exp_time_function(line_elements, stype):
"""This is called by parse_time_function() to actually parse this
type of functions.
"""
function = devices.exp()
for token in line_elements:
(param, value) = parse_param_value_from_string(token)
if stype == "voltage" and param == 'v1' or \
stype == "current" and param == 'i1':
function.v1 = convert_units(value)
elif stype == "voltage" and param == 'v2' or \
stype == "current" and param == 'i2':
function.v2 = convert_units(value)
elif param == 'td1':
function.td1 = convert_units(value)
elif param == 'tau1':
function.tau1 = convert_units(value)
elif param == 'td2':
function.td2 = convert_units(value)
elif param == 'tau2':
function.tau2 = convert_units(value)
else:
raise NetlistParseError, "unknown param for time function exp: "+param
if not function.ready():
raise NetlistParseError, "required params are missing for time function exp."
return function
def parse_sin_time_function(line_elements, stype):
"""This is called by parse_time_function() to actually parse this
type of functions.
"""
function = devices.sin()
for token in line_elements:
(param, value) = parse_param_value_from_string(token)
if stype == "voltage" and param == 'vo' \
or stype == "current" and param == 'io':
function.vo = convert_units(value)
elif stype == "voltage" and param == 'va' or \
stype == "current" and param == 'ia':
function.va = convert_units(value)
elif param == 'freq':
function.freq = convert_units(value)
elif param == 'theta':
function.theta = convert_units(value)
elif param == 'td':
function.td = convert_units(value)
else:
raise NetlistParseError, "unknown param for time function sin: "+param
if not function.ready():
raise NetlistParseError, "required params are missing for time function sin."
return function
def convert_units(string_value):
"""Converts a value conforming to spice's syntax to float.
Quote from spice3's manual:
A number field may be an integer field (eg 12, -44), a floating point
field (3.14159), either an integer or floating point number followed by
an integer exponent (1e-14, 2.65e3), or either an integer or a floating
point number followed by one of the following scale factors:
T = 1e12, G = 1e9, Meg = 1e6, K = 1e3, mil = 25.4x1e-6, m = 1e-3,
u = 1e-6, n = 1e-9, p = 1e-12, f = 1e-15