-
Notifications
You must be signed in to change notification settings - Fork 1
/
Pyspice.leo
executable file
·1575 lines (1422 loc) · 49.1 KB
/
Pyspice.leo
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
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet ekr_test?>
<leo_file>
<leo_header file_format="2" tnodes="0" max_tnode_index="0" clone_windows="0"/>
<globals body_outline_ratio="0.5">
<global_window_position top="23" left="4" height="695" width="1016"/>
<global_log_window_position top="0" left="0" height="0" width="0"/>
</globals>
<preferences/>
<find_panel_settings/>
<vnodes>
<v t="dan.20080319143651" str_leo_pos="4,0"><vh>@chapters</vh></v>
<v t="dan.20070210134628" tnodeList="dan.20070210134628,etihwnad.20060605202632.1"><vh>@file Roadmap</vh>
<v t="etihwnad.20060605202632.1"><vh>todo</vh></v>
</v>
<v t="dan.20070210134929" tnodeList="dan.20070210134929"><vh>@file HISTORY</vh></v>
<v t="dan.20070210134747" tnodeList="dan.20070210134747"><vh>@file README</vh></v>
<v t="dan.20100228190229.2782" a="E"><vh>TODO</vh>
<v t="dan.20100228190229.2783"><vh>parse param expressions</vh></v>
</v>
<v t="etihwnad.20060606092308.1" a="E"><vh>@nosent pyspice.py</vh>
<v t="etihwnad.20060605200356.2"><vh><< head docstring>></vh>
<v t="etihwnad.20060605202504"><vh><< head >></vh></v>
<v t="etihwnad.20060605201903"><vh><< copyright >></vh></v>
<v t="dan.20061011115934"><vh><< release notes >></vh>
<v t="dan.20061111103052"><vh>v0.3</vh></v>
<v t="dan.20080325141426"><vh>v0.2a</vh></v>
<v t="dan.20061011120652"><vh>v0.2</vh></v>
<v t="dan.20061011120117"><vh>v0.1</vh></v>
</v>
</v>
<v t="etihwnad.20060605210612"><vh><< global imports >></vh></v>
<v t="etihwnad.20060605205852"><vh><< global vars >></vh></v>
<v t="etihwnad.20060609195838"><vh>Option processing</vh>
<v t="etihwnad.20060605200356.36"><vh>options</vh></v>
</v>
<v t="etihwnad.20060605211347" a="E"><vh>classes</vh>
<v t="dan.20070113152139"><vh>exceptions</vh>
<v t="dan.20070113152139.1"><vh>class UnitError</vh></v>
<v t="etihwnad.20060605200356.32"><vh>class ElementError</vh>
<v t="etihwnad.20060605200356.33"><vh>__init__</vh></v>
<v t="etihwnad.20060605200356.34"><vh>__str__</vh></v>
</v>
</v>
<v t="dan.20061229140222"><vh>class Netlist</vh>
<v t="dan.20061229141817"><vh>__init__</vh></v>
<v t="dan.20080323201044"><vh>_addMassagedLine</vh></v>
<v t="dan.20061229215859"><vh>addElement</vh></v>
<v t="dan.20061229142604"><vh>addLine</vh></v>
<v t="dan.20061229142423"><vh>classify</vh></v>
<v t="dan.20080323183246"><vh>massageLine</vh></v>
<v t="dan.20061229141501"><vh>readfile</vh></v>
<v t="dan.20080325131728"><vh>removeElement</vh></v>
</v>
<v t="dan.20061229231842"><vh>class ElementHandler</vh>
<v t="dan.20061229231842.1"><vh>__init__</vh></v>
<v t="dan.20061229231842.2"><vh>add_handler</vh></v>
</v>
<v t="dan.20061008213431"><vh>base classes</vh>
<v t="etihwnad.20060605200356.3"><vh>class SpiceElement</vh>
<v t="etihwnad.20060605200356.4"><vh>__init__</vh></v>
<v t="etihwnad.20060605200356.5"><vh>__str__</vh></v>
<v t="etihwnad.20060605200356.6"><vh>drop</vh></v>
</v>
<v t="etihwnad.20060605200356.11"><vh>class Passive2NodeElement</vh>
<v t="etihwnad.20060605200356.12"><vh>__init__</vh></v>
<v t="etihwnad.20060605200356.13"><vh>__str__</vh></v>
<v t="etihwnad.20060605200356.14"><vh>drop</vh></v>
</v>
<v t="dan.20061008213532"><vh>class Active2NodeElement</vh>
<v t="dan.20061008213532.1"><vh>__init__</vh></v>
<v t="dan.20061008213532.2"><vh>__str__</vh></v>
</v>
<v t="dan.20061008214054"><vh>class Active4NodeElement</vh>
<v t="dan.20061008214054.1"><vh>__init__</vh></v>
<v t="dan.20061008214054.2"><vh>__str__</vh></v>
</v>
</v>
<v t="dan.20061008213431.1" a="E"><vh>element classes</vh>
<v t="etihwnad.20060605200356.7"><vh>class CommentLine</vh>
<v t="etihwnad.20060605200356.8"><vh>__init__</vh></v>
</v>
<v t="etihwnad.20060605200356.9"><vh>class ControlElement</vh>
<v t="etihwnad.20060605200356.10"><vh>__init__</vh></v>
</v>
<v t="etihwnad.20060605200356.15"><vh>class Capacitor</vh>
<v t="etihwnad.20060605200356.16"><vh>__init__</vh></v>
<v t="etihwnad.20060605200356.17"><vh>isparallel</vh></v>
<v t="etihwnad.20060605200356.18"><vh>combine</vh></v>
</v>
<v t="etihwnad.20060612195947"><vh>class Inductor</vh>
<v t="etihwnad.20060612195947.1"><vh>__init__</vh></v>
<v t="etihwnad.20060612195947.2"><vh>isparallel</vh></v>
<v t="etihwnad.20060612195947.3"><vh>combine</vh></v>
</v>
<v t="etihwnad.20060605200356.19" a="E"><vh>class Mosfet</vh>
<v t="etihwnad.20060605200356.20"><vh>__init__</vh></v>
<v t="etihwnad.20060605200356.21"><vh>__str__</vh></v>
<v t="etihwnad.20060605200356.22"><vh>isparallel</vh></v>
<v t="etihwnad.20060605200356.23"><vh>combine</vh></v>
</v>
<v t="etihwnad.20060605200356.24"><vh>class Resistor</vh>
<v t="etihwnad.20060605200356.25"><vh>__init__</vh></v>
</v>
<v t="dan.20061008213903"><vh>class Vsource</vh>
<v t="dan.20061008213903.1"><vh>__init__</vh></v>
</v>
<v t="dan.20061008213936"><vh>class Isource</vh>
<v t="dan.20061008213936.1"><vh>__init__</vh></v>
</v>
</v>
</v>
<v t="dan.20080323214255"><vh>functions</vh>
<v t="dan.20080323214255.1"><vh>combineCapacitorsInplace</vh></v>
<v t="dan.20080323223326"><vh>combineMosfetsInplace</vh></v>
</v>
<v t="etihwnad.20060609195838.1"><vh>helpers</vh>
<v t="etihwnad.20060612075426"><vh>unit</vh></v>
<v t="etihwnad.20060605200356.27"><vh>debug</vh></v>
<v t="etihwnad.20060605200356.26"><vh>info</vh></v>
<v t="etihwnad.20060605200356.28"><vh>warning</vh></v>
</v>
<v t="dan.20080323201405"><vh>main</vh></v>
</v>
<v t="dan.20070113143715" tnodeList="dan.20070113143715,dan.20070113145158,dan.20070113154450"><vh>@file test_pyspice.py</vh>
<v t="dan.20070113145158"><vh>unit conversions</vh></v>
<v t="dan.20070113154450"><vh>netlist parsing</vh></v>
</v>
<v t="dan.20080324085048"><vh>old</vh>
<v t="etihwnad.20060605200356.35"><vh>classify</vh></v>
<v t="etihwnad.20060605200356.29"><vh>drop_2node</vh></v>
<v t="etihwnad.20060605200356.37"><vh>old_main</vh></v>
<v t="etihwnad.20060605200356.31"><vh>read_netlist</vh>
<v t="etihwnad.20060609200142"><vh><< docstring >></vh></v>
<v t="etihwnad.20060609200142.1"><vh><< imports >></vh></v>
</v>
<v t="etihwnad.20060605200356.30"><vh>write_2node</vh></v>
</v>
</vnodes>
<tnodes>
<t tx="dan.20061008213431">@
These classes are used to break down the spectrum of SPICE elements
into 'classes' of elements. I.e. 2 node passives, 2-node sources, 4-node sources,
and so on. The elements found in a real netlist are based on these types.
@c
</t>
<t tx="dan.20061008213431.1">@
This is a(n incomplete) definition of the various SPICE elements.
NOTE: When adding a new element type definition, be sure to add a handler
for the new class after defining the class using:
elements.add_handler('x', Xdevice)
@c
#make a repository for element handlers
_elementHandler = ElementHandler()
</t>
<t tx="dan.20061008213532">
class Active2NodeElement(SpiceElement):
"""Base class for active 2-node elements.
Assumes SPICE element line:
xXXX n1 n2 value p1=val p2=val ...
Inherits:
None
Redefines:
None
"""
@others
</t>
<t tx="dan.20061008213532.1">def __init__(self, line, num):
SpiceElement.__init__(self, line, num)
self.type = 'active2'
self.typeName = 'Active2NodeElement'
arr = line.split()
self.name = arr[0]
self.n1 = _current_scope + arr[1]
self.n2 = _current_scope + arr[2]
self.value = unit(arr[3])
self.param = dict() #store x = y as dictionary
for p in arr[4:]:
k, v = p.split('=')
self.param[k] = unit(v)
</t>
<t tx="dan.20061008213532.2">def __str__(self):
"""Returns the netlist-file representation of this element"""
s = StringIO()
print>>s, self.name, self.n1, self.n2, self.value,
for k, v in self.param.iteritems():
print>>s, k + '=' + str(v),
return _wrapper.fill(s.getvalue())
</t>
<t tx="dan.20061008213903">
class Vsource(Active2NodeElement):
"""Assumes SPICE element line:
vXXX n1 n2 value p1=val p2=val ...
"""
@others
_elementHandler.add_handler('v', Vsource)
</t>
<t tx="dan.20061008213903.1">def __init__(self, line, num):
Active2NodeElement.__init__(self, line, num)
self.type = 'v'
self.typeName = 'Vsource'
</t>
<t tx="dan.20061008213936">
class Isource(Active2NodeElement):
"""Assumes SPICE element line:
iXXX n1 n2 value p1=val p2=val ...
"""
@others
_elementHandler.add_handler('i', Isource)
</t>
<t tx="dan.20061008213936.1">def __init__(self, line, num):
Active2NodeElement.__init__(self, line, num)
self.type = 'i'
self.typeName = 'Isource'
</t>
<t tx="dan.20061008214054">
class Active4NodeElement(SpiceElement):
"""Base class for active 4-node elements (xCyS).
Assumes SPICE element line:
xXXX n1 n2 value p1=val p2=val ...
Inherits:
None
Redefines:
None
"""
@others
</t>
<t tx="dan.20061008214054.1">def __init__(self, line, num):
SpiceElement.__init__(self, line, num)
self.type = 'active4'
self.typeName = 'Active4NodeElement'
arr = line.split()
self.name = arr[0]
self.n1 = _current_scope + arr[1]
self.n2 = _current_scope + arr[2]
self.n3 = _current_scope + arr[3]
self.n4 = _current_scope + arr[4]
self.value = unit(arr[5])
self.param = dict() #store x = y as dictionary
for p in arr[6:]:
k, v = p.split('=')
self.param[k] = unit(v)
</t>
<t tx="dan.20061008214054.2">def __str__(self):
s = StringIO()
print>>s, self.name, self.n1, self.n2, self.n3, self.n4, self.value,
for k, v in self.param.iteritems():
#are there instances when 0 is (in)significant?
#if v == 0: continue
print>>s, k + '=' + str(v),
return _wrapper.fill(s.getvalue())
</t>
<t tx="dan.20061011115934">Release Notes, changelog
-----------------------------------------------------
@others
</t>
<t tx="dan.20061011120117">pyspice v0.1:
-------------
Initial release.
Only worked for netlist containing MOSFETs and Capacitors.
</t>
<t tx="dan.20061011120652">pyspice.py v0.2:
----------------
-At least default (pass through) handling of all element types.
NOTE: For combining, this uses a global node name scheme. In other
words: subcircuits, libraries, etc. are not in a separate node
namespace as they should be, beware.
-Changed structure of classes (in LEO), there are base classes that contain
common attributes and element classes that define the specific behavior.
-This version _should_ work with any netlist and only touch M's and C's, YMMV.
-Work is ongoing on the class structure and most important IMO is getting netlist
hierarchy implemented.
</t>
<t tx="dan.20061111103052">pyspice.py v0.3:
----------------
-entire netlist is held in the top level Netlist object
-temporarily does not drop small capacitors
-code cleanup
</t>
<t tx="dan.20061229140222">
class Netlist:
"""Base class that holds an entire netlist.
Notes:
-this will eventually hold the entire shebang
-providing __init__ with a file name will:
-read in netlist
-classify the lines
-take care of hierarchy
-source other files
"""
@others
</t>
<t tx="dan.20061229141501">def readfile(self, fname):
"""Read a SPICE netlist from the open file pointer into the netlist.
Reads the file as a netlist into the deck. Appends the line's text
and adds a classified SpiceElement to the deck.
return:
None
Note:
-we need to read at least a full line with continuations before we can
add the line to the netlist
"""
if isinstance(fname, file):
ifp = fname
else:
ifp = open(fname, 'rU')
#first line of any file is ignored
# typically a title line
# set title iff title is not set
line = ifp.readline()
if not self.title:
self.title = line
currentCard = ifp.readline()
n = 2 #1-indexed line numbers
for line in ifp:
n += 1
#handle line continuations here
if line[0] == '+':
currentCard += line[1:]
continue
#a new card is started, the previous card is
#unambiguously finished
mLine = self.massageLine(currentCard)
self._addMassagedLine(mLine)
self.addElement(self.classify(mLine, num=n))
currentCard = line
</t>
<t tx="dan.20061229141817">def __init__(self, fname=None, title=None):
"""Optionally reads a netlist from a file"""
self.deck = []
self.lines = []
self.title = title
self.elements = dict()
for e in _elementHandler.validTypes:
self.elements[e] = []
if fname:
self.readfile(fname)
</t>
<t tx="dan.20061229142423">def classify(self, line, num=None):
"""Takes a line and creates an appropriate SpiceElement"""
return _elementHandler.handler[line[0][0].lower()](line, num=num)
</t>
<t tx="dan.20061229142604">def addLine(self, line):
"""Add the given non-empty line to netlist after massaging"""
if line:
#fail on line continuations
if line[0] == '+':
raise PyspiceError('addLine does not handle line continuations')
else:
line = self.massageLine(line)
self._addMassagedLine(line)
</t>
<t tx="dan.20061229215859">def addElement(self, element):
self.deck.append(element)
self.elements[element.type].append(element)
</t>
<t tx="dan.20061229231842">class ElementHandler:
@others
</t>
<t tx="dan.20061229231842.1">def __init__(self):
self.validTypes = '*.abcdefghijklmnopqrstuvwxyz'
self.handler = dict()
for t in self.validTypes:
self.handler[t] = SpiceElement
</t>
<t tx="dan.20061229231842.2">def add_handler(self, type, handler):
"""Replaces the existing element object definition with the
given one"""
self.handler[type] = handler
</t>
<t tx="dan.20070113143715">@first #!/usr/bin/python
@language python
@tabwidth -4
"""Unit test stuff for pyspice.py"""
__author__ = "Dan White ([email protected])"
__version__ = "$Revision: 1.3 $"
__date__ = "$Date: 2004/05/05 21:57:20 $"
__copyright__ = "Copyright (c) 2007 Dan White"
__license__ = "GPL"
import pyspice
import unittest
from decimal import Decimal as D
@others
if __name__ == "__main__":
unittest.main()</t>
<t tx="dan.20070113145158">
class unitConversion(unittest.TestCase):
"""Tests conversion between SPICE string and Decimal number."""
knownValues = ( ('5T', D('5.0e12')),
('5G', D('5.0e9')),
('10MEG', D('10.0e6')),
('342x', D('342.0e6')),
('15k', D('15.0e3')),
('1MIL', D('25.4e-6')),
('435M', D('435e-3')),
('1U', D('1.0e-6')),
('67N', D('67.0e-9')),
('4P', D('4.0e-12')),
('3F', D('3.0e-15')) )
badValues = ( 'like' )
def test_unit_knownValues(self):
"""unit() should give known result with known input"""
for s, num in self.knownValues:
result = pyspice.unit(s)
self.assertEqual(num,result)
def test_unit_badValues(self):
"""unit() should fail with bad input"""
for s in self.badValues:
self.assertRaises(pyspice.BadUnitError, pyspice.unit, s)
</t>
<t tx="dan.20070113152139">
class PyspiceError(Exception):
'''Base exception for pyspice'''
pass
</t>
<t tx="dan.20070113152139.1">
class BadUnitError(PyspiceError):
pass
</t>
<t tx="dan.20070113154450">
class netlistParsing(unittest.TestCase):
"""Tests the netlist parser"""
pass</t>
<t tx="dan.20070210134628">@nocolor
Contained here is the descriptive blueprint of how this package is supposed to work
@others</t>
<t tx="dan.20070210134747">@nocolor
Please see Roadmap for more information on what's currently going on here.
</t>
<t tx="dan.20070210134929">@pagewidth 80
@nocolor
The poorly-documented chronology of this package's development progress. The intention is to keep me focused on the big picture and just fill in the missing parts.
</t>
<t tx="dan.20080319143651"></t>
<t tx="dan.20080323183246">#finds a "name = value" pair for shrinking
RE_PARAM = re.compile(r"(\S*)\s*=\s*(\S*)")
#finds only whitespace
RE_WHITESPACE_EMPTY = re.compile(r'^\s*$')
def massageLine(self, line):
#remove trailing newline
line = line.strip('\r\n')
#pass through empty lines and convert to comments
if self.RE_WHITESPACE_EMPTY.search(line):
return '*'
# and pass through comments, they stay as-is
elif line[0] == '*':
return line
if _opt == 'keep':
pass
elif _opt == 'lower':
#case is unimportant in SPICE
#lowercase all non-comment lines
line = line.lower()
elif _opt == 'upper':
line = line.upper()
#remove whitespace in parameter assignments
# to prepare for x.split(' ') that happens next:
# 'as = 3e-12' => 'as=3e-12'
line = self.RE_PARAM.sub(r'\1=\2', line)
return line
</t>
<t tx="dan.20080323201044">def _addMassagedLine(self, line):
"""Add the given non-empty line to netlist. Assumes the line has already
been massaged."""
self.lines.append(line)
</t>
<t tx="dan.20080323201405">def main():
global _opt
opt = options()
_opt = opt
# output file header
print>>ofp, "* pyspice.py %s: by Dan White <[email protected]>" % __version__
print>>ofp, "* mail me bug reports, fixes, and comments if you find this useful"
print>>ofp, "* ----------------------------------------------------------------"
# Read and parse given input file (as top-level)
netlist = Netlist(ifp)
# Show input statistics
if opt.v:
info('Read in %i elements' % len(netlist.deck))
s = StringIO()
print>>s, 'Input Element counts:'
for t, v in netlist.elements.iteritems():
if len(v):
print>>s, '%s: %i' % (t, len(v))
info(s.getvalue())
# Combine elements if requested
nCombined = dict()
if opt.combine_c:
nCombined['c'] = combineCapacitorsInplace(netlist)
if opt.v:
info('Combined %i capacitors' % nCombined['c'])
if opt.combine_m:
nCombined['m'] = combineMosfetsInplace(netlist)
if opt.v:
info('Combined %i mosfets' % nCombined['m'])
# Show output statistics
if opt.v:
s = StringIO()
print>>s, 'Output Element counts:'
for t, v in netlist.elements.iteritems():
if len(v):
print>>s, '%s: %i' % (t, len(v))
info(s.getvalue())
for card in netlist.deck:
print>>ofp, card
</t>
<t tx="dan.20080323214255"></t>
<t tx="dan.20080323214255.1">def combineCapacitorsInplace(nlist):
'''Finds all parallel capacitors and replaces each with a single element
of equivalent value. The capacitor is named by the first-occuring name.
Returns the number of combined capacitors.'''
caps = [c for c in nlist.deck if c.type == 'c']
#this modifies the list being iterated over in place
#usually this is BAD, here it is our way of only checking capacitor
#combinations for parallel-isity once, the netlist is modified in parallel.
#
#This works because different instances of the same class never compare
#equal
n = 0
for c in caps:
for x in caps[caps.index(c)+1:]:
if c.combine(x):
n += 1
caps.remove(x)
nlist.removeElement(x)
return n
</t>
<t tx="dan.20080323223326">def combineMosfetsInplace(nlist):
'''TODO'''
fets = [m for m in nlist.deck if m.type == 'm']
n = 0
for m in fets:
for x in fets[fets.index(m)+1:]:
if m.combine(x):
n += 1
fets.remove(x)
nlist.removeElement(x)
return n
</t>
<t tx="dan.20080324085048"></t>
<t tx="dan.20080325131728">def removeElement(self, element):
self.deck.remove(element)
self.elements[element.type].remove(element)
</t>
<t tx="dan.20080325141426">pyspice.py v0.2a:
----------------
-added a missing newline before an import statement
</t>
<t tx="dan.20100228190229.2782">@nocolor</t>
<t tx="dan.20100228190229.2783">hspice-style .param foo = 'x*a*sqrt(bar)'
evaluation and substitution
hspice also supports user functions
.param func(x,y) = 'x+y'
</t>
<t tx="etihwnad.20060605200356.2">"""
<< head >>
<< copyright >>
<< release notes >>
@others
"""
@nocolor
</t>
<t tx="etihwnad.20060605200356.3">
class SpiceElement:
"""Base class for SPICE elements.
Methods:
__init__(self, line, num) -> SpiceElement
__str__(self) -> string spice line
drop() -> False
"""
@others
</t>
<t tx="etihwnad.20060605200356.4">def __init__(self, line, num=None):
"""SpiceElement constructor
line - netlist expanded line
type - first character
num - input netlist line number (for keeping roughly the same
order when printing modified netlist)
"""
#accept lists of 'words' also; BE CAREFUL with this, though
self.line = line
self.type = 'spice'
self.typeName = 'SpiceElement'
self.num = num
</t>
<t tx="etihwnad.20060605200356.5">def __str__(self):
return _wrapper.fill(self.line)
</t>
<t tx="etihwnad.20060605200356.6">def drop(self, val=0, mode='<'):
"""Template for dropping elements that defaults to NO if
not overidden in the element class"""
return False
</t>
<t tx="etihwnad.20060605200356.7">
class CommentLine(SpiceElement):
"""SPICE Comment line (/^\*.*/)
"""
@others
_elementHandler.add_handler('*', CommentLine)
</t>
<t tx="etihwnad.20060605200356.8">def __init__(self, line, num):
SpiceElement.__init__(self, line, num)
self.type = '*'
self.typeName = ''
</t>
<t tx="etihwnad.20060605200356.9">
class ControlElement(SpiceElement):
"""Control statement object, no processing for now.
Note: this will eventially be a base class for the real control elements
Note: currently has no knowledge of blocks (.lib/.endl, .subckt/.ends)
has only ONE node namespace, make sure subckt's have unique node names!
"""
@others
_elementHandler.add_handler('.', ControlElement)
</t>
<t tx="etihwnad.20060605200356.10">def __init__(self, line, num):
SpiceElement.__init__(self, line, num)
self.type = '.'
self.typeName = 'ControlElement'
</t>
<t tx="etihwnad.20060605200356.11">
class Passive2NodeElement(SpiceElement):
"""Base class for 2-node elements.
Assumes SPICE element line:
xXXX n1 n2 value p1=val p2=val ...
Inherits:
None
Redefines:
drop(self, val, mode) -> bool
"""
@others
</t>
<t tx="etihwnad.20060605200356.12">def __init__(self, line, num):
SpiceElement.__init__(self, line, num)
self.type = 'passive2'
self.typeName = 'Passive2NodeElement'
arr = line.split()
self.name = arr[0]
self.n1 = _current_scope + arr[1]
self.n2 = _current_scope + arr[2]
self.value = unit(arr[3])
self.param = dict() #store x = y as dictionary
for p in arr[4:]:
k, v = p.split('=')
self.param[k] = unit(v)
</t>
<t tx="etihwnad.20060605200356.13">def __str__(self):
"""Returns the netlist-file representation of this element"""
s = StringIO()
print>>s, self.name, self.n1, self.n2, self.value,
for k, v in self.param.iteritems():
print>>s, k+'='+str(v),
return _wrapper.fill(s.getvalue())
</t>
<t tx="etihwnad.20060605200356.14">def drop(self, val=0.0, mode='<'):
"""Indicate whether to drop the element from the list.
Occurs iff (val 'mode' self.value)
Can this be converted to specifying an arbitrary binary function?
This may allow a more elegant comparison.
e.g. mode = < instead of mode = '<' or mode = cap_smaller(x, y)
"""
if mode == '<':
if self.value < val: return True
elif mode == '<=':
if self.value <= val: return True
elif mode == '>':
if self.value > val: return True
elif mode == '>=':
if self.value >= val: return True
else:
return False
return False #shouldn't get here, but...
</t>
<t tx="etihwnad.20060605200356.15">
class Capacitor(Passive2NodeElement):
"""Assumes SPICE element line:
cXXX n1 n2 value p1=val p2=val ...
Provides:
isparallel(other)
combine(other)
"""
@others
_elementHandler.add_handler('c', Capacitor)
</t>
<t tx="etihwnad.20060605200356.16">def __init__(self, line, num):
Passive2NodeElement.__init__(self, line, num)
self.type = 'c'
self.typeName = 'Capacitor'
</t>
<t tx="etihwnad.20060605200356.17">def isparallel(self, other):
"""Returns True if instance is parallel with other instance
"""
if self.n1 == other.n1 and self.n2 == other.n2:
return True
elif self.n1 == other.n2 and self.n2 == other.n1:
return True
else:
return False
</t>
<t tx="etihwnad.20060605200356.18">def combine(self, other):
"""Adds values if capacitors are in parallel, returns True if
it combined them.
NOTE: Does not currently touch param dictionary when combining,
just the values. How should this be done? Maybe combine iff
params are identical to avoid problems?
"""
global _ncombine_capacitors
if self.isparallel(other):
self.value += other.value
_ncombine_capacitors += 1
return True
else:
return False
</t>
<t tx="etihwnad.20060605200356.19">
class Mosfet(SpiceElement):
"""Mosfet constructor takes an array derived from the
netlist line
"""
@others
_elementHandler.add_handler('m', Mosfet)
</t>
<t tx="etihwnad.20060605200356.20">def __init__(self, line, num):
if isinstance(line, str):
line = line.split()
self.line = line
self.type = 'm'
self.typeName = 'Mosfet'
self.num = num
self.name = line[0]
self.d = line[1]
self.g = line[2]
self.s = line[3]
self.b = line[4]
self.model = line[5]
self.param = dict()
for p in line[6:]:
k, v = p.split('=')
self.param[k.lower()] = unit(v)
self.w = self.param['w']
self.l = self.param['l']
</t>
<t tx="etihwnad.20060605200356.21">def __str__(self):
s = StringIO()
print>>s, self.name, self.d, self.g, self.s, self.b, self.model,
for k, v in self.param.iteritems():
#TODO really kosher to ignore 0-values, careful of non-zero defaults
if v == 0: continue
print>>s, k + '=' + str(v),
return _wrapper.fill(s.getvalue())
</t>
<t tx="etihwnad.20060605200356.22">def isparallel(self, other):
"""Returns True if transistors are parallel
"""
# check gate, substrate, and model first
if self.g == other.g and self.b == other.b and self.model == other.model:
#source and drain can be reversed
if self.d == other.d and self.s == other.s:
return True
elif self.d == other.s and self.s == other.d:
return True
else:
return False
else:
return False
</t>
<t tx="etihwnad.20060605200356.23">def combine(self, other):
"""Combines adds other to self iff the transistors are identical,
will NOT combine if W/L is different. Parameter 'M' is incremented on
self, other is left alone.
Returns True if it combined the transistors.
Increments global _ncombine_mosfets for information.
NOTE: This currently merely adds the parameters (except w, l, and m)
without regard to their meaning. Here is the place to specially handle
certain FET parameters. Average certain parameters?
"""
global _ncombine_mosfets
if self.isparallel(other):
#combine iff W/L (for original FET) is same also
if self.w == other.w and self.l == other.l:
for k, v in other.param.iteritems():
if k == 'w' or k == 'l' or k == 'm': continue
self.param[k] += v
if ('m' in self.param.keys()) or ('m' in other.param.keys()):
#add other's M parameter or increment
self.param['m'] += other.param.get('m', 1)
else:
self.param['m'] = 2
_ncombine_mosfets += 1
return True
else:
return False
</t>
<t tx="etihwnad.20060605200356.24">
class Resistor(Passive2NodeElement):
"""Assumes SPICE element line:
rXXX n1 n2 value p1=val p2=val ...
"""
@others
_elementHandler.add_handler('r', Resistor)
</t>
<t tx="etihwnad.20060605200356.25">def __init__(self, line, num):
Passive2NodeElement.__init__(self, line, num)
self.type = 'r'
self.typeName = 'Resistor'
</t>
<t tx="etihwnad.20060605200356.26">def info(message):
"""Print information to stderr."""
for m in message.split('\n'):
if m:
print>>stderr, 'Info:', m
</t>
<t tx="etihwnad.20060605200356.27">def debug(message):
"""Print debugging info to stderr."""
for m in message.split('\n'):
if m:
print>>stderr, 'Debug:', m
</t>
<t tx="etihwnad.20060605200356.28">def warning(message, elm=None, num=None):
"""Print warning to stderr. If elm and num defined,
print different message"""
if elm and num:
message = _opt.infile+":"+str(num)+" '"+elm+\
"' type not defined yet, passing through..."
print>>stderr, 'Warning:', message
</t>
<t tx="etihwnad.20060605200356.29">def drop_2node(elm,val,mode='<',type=None, verbose=True):
"""Drop 2-node elements in elm list according to val.
mode = '<' | '>'
type - print info on what and how many it dropped
Note: only works correctly for capacitors for now
"""
new_elm=[]
val=float(val)
for i in elm:
if mode=='<' and i.value>=val:
new_elm.append(i)
elif mode=='>' and i.value<=val:
new_elm.append(i)
else:
continue
#Print info about how many it dropped
if verbose:
infostr='Dropped '+str((len(elm)-len(new_elm)))+' '
if type and type[-1]=='s':
info(infostr+type)
elif type:
info(infostr+type+'s')
else:
info(infostr+'elements')
return new_elm
</t>
<t tx="etihwnad.20060605200356.30">##
# write 2-node SPICE elements to file
# node pair is specified by key in dict:
# "node0,node1"
##
#NOTE:
# this function is dying a slow, painful death. Each element is
# getting its own custom __str__() method for writing to netlists.
#
def write_2node(elm, type=None, ofp=sys.stdout, comment=None):
"""Write 2-node SPICE elements to file
elm - dictionary of elements
type - SPICE element name
ofp - output file pointer
comment - comment string at head of elm list
Note: "type" must begin with a SPICE element letter, the rest is printed
as identifying information, e.g. linductor, capacitor, mosfet.
"""
if not type:
raise SyntaxError('Must define a SPICE element name')
i=1
if comment:
print>>ofp,'\n**\n* '+comment+'\n**'
for k,v in elm.iteritems():
node=k.split(',')
print>>ofp, type[0]+str(i).rjust(3,'0'),node[0],node[1],v
i+=1
infostr='Wrote '+str(i)+' '+type
if type[-1]=='s':
info(infostr)
else:
info(infostr+'s')
</t>
<t tx="etihwnad.20060605200356.31">##
# Read netlist from open file object
# -make sure if reading from stdin to read only once and
# use this function to make sure you read the entire netlist
##
def read_netlist(fname):
<< docstring >>
<< imports >>
if isinstance(fname,file):
ifp=fname
else:
ifp=open(fname,'rU')
# netlist=ifp.readlines()
nline=0
lines=[] #raw expanded netlist
#
re_param=re.compile(r"(\S*)\s*=\s*(\S*)")
for line in ifp:
line=line.strip('\r\n')
#pass through empty lines
if not len(line.split()):
#convert empty line to comment as a placeholder
lines.append('*')
nline+=1
continue #next please...
#pass through comments, they stay asis
elif line[0]=='*':
lines.append(line)
nline+=1
continue #next please...
#case is unimportant in SPICE
line=line.lower()
#remove whitespace in parameter assignments
# to prepare for x.split(' ') that happens later:
# 'as = 3e-12' => 'as=3e-12'
line=re.sub(re_param,r'\1=\2',line)
if line[0]!='+': #beginning of SPICE line
lines.append(line)
nline+=1
else: #line continuation
line=line[1:]
lines[-1]=lines[-1]+line
return lines
</t>
<t tx="etihwnad.20060605200356.32">