forked from giaccone/SpicePy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnetlist.py
1665 lines (1413 loc) · 65.5 KB
/
netlist.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
# ===========================================================
# About the code
# ===========================================================
# This code is part of the project 'SpicePy'.
# See README.md for more details
#
# Licensed under the MIT license (see LICENCE)
# Copyright (c) 2017 Luca Giaccone ([email protected])
# ===========================================================
# ==================
# imported modules
# ==================
from scipy.sparse import csr_matrix
import numpy as np
import transient_sources as tsr
# ==================
# constants
# ==================
pi = np.pi
# ==================
# Class
# ==================
class Network:
"""
Class that defines the network.
Basilar attributes (always assigned):
* self.names: component names
* self.values: component values
* self.IC: initial conditions for dynamic components (stored as dict)
* self.source_type: type of transient sources (stored as dict)
* self.nodes: component nodes (only two-port right now)
* self.node_label2num: dictionary to convert node-labels to local node-number
* self.node_num: number of nodes in the network
* self.analysis: type of analysis
* self.plot_cmd: plot directive for transient analysis
* self.tf_cmd: transfer function definition (for .ac multi-freq)
Other attributes (default is None):
* self.A:
* self.G:
* self.C:
* self.rhs:
* self.isort:
* self.t:
* self.f:
* self.x:
* self.vb:
* self.ib:
* self.pb:
Methods:
* read_netlist(self): reads a SPICE netlist (used by '__init__')
* incidence_matrix(self, filename):
* conductance_matrix(self):
* dynamic_matrix(self):
* rhs_matrix(self):
* branch_voltage(self):
* branch_current(self):
* branch_power(self):
* get_voltage(self, arg):
* get_current(self, arg):
* reorder(self):
* print(self, variable='all', polar=False, message=False):
* plot(self, to_file=False, filename=None, dpi_value=150):
"""
def __repr__(self):
return "SpicePy.Network: {} analysis".format(self.analysis[0])
def __str__(self):
# create local dictionary to convert node-numbers to node-labels
num2node_label = {num: name for name, num in self.node_label2num.items()}
# build message to print
msg = '------------------------\n'
msg += ' SpicePy.Network:\n'
msg += '------------------------\n'
for ele, nodes, val in zip(self.names, self.nodes, self.values):
# if val is a list --> ele is a transient source
if isinstance(val, list):
if self.source_type[ele] == 'pwl':
fmt = "{} {} {} {}(" + "{} " * (len(val[0]) - 1) + "{})\n"
msg += fmt.format(ele, num2node_label[nodes[0]], num2node_label[nodes[1]], self.source_type[ele], *val[0])
else:
fmt = "{} {} {} {}(" + "{} " * (len(val) - 1) + "{})\n"
msg += fmt.format(ele, num2node_label[nodes[0]], num2node_label[nodes[1]], self.source_type[ele], *val)
# controlled sources
elif (ele[0].upper() == 'E') | (ele[0].upper() == 'G'):
msg += "{} {} {} {} {} {}\n".format(ele, num2node_label[nodes[0]], num2node_label[nodes[1]],
self.control_source[ele][0],
self.control_source[ele][1],
val)
elif ele[0].upper() == 'F':
msg += "{} {} {} {} {}\n".format(ele, num2node_label[nodes[0]], num2node_label[nodes[1]],
self.control_source[ele],
val)
# if val is complex --> ele is a phasor
elif np.iscomplex(val):
msg += "{} {} {} {} {}\n".format(ele, num2node_label[nodes[0]], num2node_label[nodes[1]], np.abs(val), np.angle(val) * 180/np.pi)
# if ele is C or L
elif ele[0].upper() == 'C' or ele[0].upper() == 'L':
# check if an i.c. is present and print it
if ele in self.IC:
msg += "{} {} {} {} ic={}\n".format(ele, num2node_label[nodes[0]], num2node_label[nodes[1]], val, self.IC[ele])
# otherwise...
else:
msg += "{} {} {} {}\n".format(ele, num2node_label[nodes[0]], num2node_label[nodes[1]], val)
# otherwise...general case --> ele n+ n- val
else:
msg += "{} {} {} {}\n".format(ele, num2node_label[nodes[0]], num2node_label[nodes[1]], val)
# add analysis
msg += " ".join(self.analysis) + '\n'
# if a plot command is present, add it
if self.plot_cmd is not None:
msg += self.plot_cmd + '\n'
# if a transfer function definition is present, add it
if self.tf_cmd is not None:
msg += self.tf_cmd + '\n'
# add number of nodes (reference node is included) and number of branches
msg += '------------------------\n'
msg += '* number of nodes {}\n'.format(self.node_num + 1)
msg += '* number of branches {}\n'.format(len(self.names))
msg += '------------------------\n'
return msg
def __init__(self, filename):
"""
__init__ initializes common attributes using read_netlist method
:param filename:
"""
# initialization of other possible attributes
self.A = None
self.G = None
self.C = None
self.rhs = None
self.isort = None
self.t = None
self.f = None
self.x = None
self.vb = None
self.ib = None
self.pb = None
self.unit_prefix = {'meg': 'e6', 'f': 'e-15', 'p': 'e-12', 'n': 'e-9', 'u': 'e-6', 'm': 'e-3', 'k': 'e3', 'g': 'e9', 't': 'e12'}
# common attributes
(self.names,
self.values,
self.IC,
self.source_type,
self.control_source,
self.nodes,
self.node_label2num,
self.node_num,
self.analysis,
self.plot_cmd,
self.tf_cmd) = self.read_netlist(filename)
def read_netlist(self, filename):
"""
'readNetlist' reads a SPICE netlist
:param filename: file name with the netlist
:return:
* names: element names
* values: element values
* IC: initial conditions
* source_type: type of transient source
* nodes: element nodes
* node_labels2num: dictionary to convert node-labels to local node-number
* Nn: number of nodes in the netlist
* analysis: type of analysis
* plot_cmd: plot command
"""
# initialize counter for number of nodes
Nn = 0
# initialize variable names and values
names = []
values = []
node_labels = []
IC = {}
source_type = {}
control_source = {}
plot_cmd = None
tf_cmd = None
analysis = None
# initial letter of all available components
initials = ['V', 'I', 'R', 'C', 'L', 'E', 'F', 'G']
components = []
# 1) get the analysis type
# 2) catch plot command (if any)
# 3) filter out comments
with open(filename) as f:
# cycle on lines
for b, line in enumerate(f):
# look for inline comments
if ';' in line:
# remove comment
line = line[:line.index(';')]
# if it is not a line-comment
if line[0] != '*':
# check if line describes a component
if line[0].upper() in initials:
# remove carriage return
line = line.replace('\n', '')
# add to component list
components.append(line)
# check if line describes a command
elif line[0] == '.':
# remove carriage return
line = line.replace('\n', '')
if line.lower().find('.end') != -1: # if .end is reached exit
break
elif line.lower().find('.plot') != -1: # if .plot is reached save it
plot_cmd = line
elif line.lower().find('.tf') != -1: # if .tf is reached save it
tf_cmd = line
elif line.lower().find('.backanno') != -1: # skip .backanno if present
pass
else: # save analysis type
# split into a list
analysis = line.split()
else:
pass
# cycle on component list
for line in components:
# look for transient sources (if analysis is .tran)
if analysis[0] == '.tran':
# loop on all possible transient sources
time_sources = ['pwl', 'pulse', 'sin', 'exp']
for source in time_sources:
# when one is found
if source in line.lower():
# get index of the related string
index = line.lower().index(source)
# split string before its name
sline = line[:index].split()
# 1) remove '(' and ')' in the string after its name 2) and split
param = line[index:].replace('(',' ').replace(')',' ').split()
# append transient-source name
sline.append(param[0])
# append parameters
sline.append(param[1:])
break
# if component is not a transient source, catch it normally
else:
# split into a list
sline = line.split()
# if not '.tran', catch them all normally
else:
# split into a list
sline = line.split()
# detect element type
if sline[0][0].upper() == 'R': # resistance
# add name and value
names.append(sline[0])
values.append(float(self.convert_unit(sline[3])))
node_labels.append(sline[1:3])
# inductor
elif sline[0][0].upper() == 'L':
# add name, value and nodes
names.append(sline[0])
values.append(float(self.convert_unit(sline[3])))
node_labels.append(sline[1:3])
# for '.tran'
if analysis[0] == '.tran':
# check presence of i.c.
if len(sline) == 5:
if sline[4].lower().find('ic') != -1:
IC[sline[0]] = float(self.convert_unit(sline[4].split('=')[1]))
else:
#IC[sline[0]] = 'Please check this --> ' + sline[-1]
# print("Warning: wrong definition of IC for {} --> ".format(sline[0]) + IC[sline[0]])
raise ValueError("Warning: wrong definition of IC for {} --> ".format(sline[0]) + IC[sline[0]])
# add ic=0 if i.c. non provided by the user
else:
IC[sline[0]] = 0
# capacitor
elif sline[0][0].upper() == 'C':
# add name and value
names.append(sline[0])
values.append(float(self.convert_unit(sline[3])))
node_labels.append(sline[1:3])
if analysis[0] == '.tran':
if len(sline) == 5:
if sline[4].lower().find('ic') != -1:
IC[sline[0]] = float(self.convert_unit(sline[4].split('=')[1]))
else:
#IC[sline[0]] = 'Please check this --> ' + sline[-1]
#print("Warning: wrong definition of IC for {} --> ".format(sline[0]) + IC[sline[0]])
raise ValueError("Warning: wrong definition of IC for {} --> ".format(sline[0]) + IC[sline[0]])
# add ic=0 if i.c. non provided by the user
else:
IC[sline[0]] = 0
# independent current source
elif sline[0][0].upper() == 'I':
# add name and nodes
names.append(sline[0])
node_labels.append(sline[1:3])
# if '.ac' and phase is present:
if (analysis[0] == '.ac') & (len(sline) == 5):
values.append(float(self.convert_unit(sline[3])) * (
np.cos(float(sline[4]) * pi / 180) + np.sin(float(sline[4]) * pi / 180) * 1j))
# if '.tran' ...
elif analysis[0] == '.tran':
# if is a transient source
if isinstance(sline[-1], list):
source_type[sline[0]] = sline[-2]
if source_type[sline[0]] == 'pwl':
values.append([[float(self.convert_unit(k)) for k in sline[-1]]])
else:
values.append([float(self.convert_unit(k)) for k in sline[-1]])
# otherwise...
else:
values.append(float(self.convert_unit(sline[3])))
# otherwise...
else:
values.append(float(self.convert_unit(sline[3])))
# independent voltage sources
elif sline[0][0].upper() == 'V':
# add name and nodes
names.append(sline[0])
node_labels.append(sline[1:3])
# if '.ac' and phase is present:
if (analysis[0] == '.ac') & (len(sline) == 5):
values.append(float(self.convert_unit(sline[3])) * (
np.cos(float(sline[4]) * pi / 180) + np.sin(float(sline[4]) * pi / 180) * 1j))
# if '.tran'
elif analysis[0] == '.tran':
# if is a transient source
if isinstance(sline[-1], list):
source_type[sline[0]] = sline[-2]
if source_type[sline[0]] == 'pwl':
values.append([[float(self.convert_unit(k)) for k in sline[-1]]])
else:
values.append([float(self.convert_unit(k)) for k in sline[-1]])
# otherwise...
else:
values.append(float(self.convert_unit(sline[3])))
# otherwise...
else:
values.append(float(self.convert_unit(sline[3])))
# VCVS or VCCS
elif (sline[0][0].upper() == 'E') | (sline[0][0].upper() == 'G'):
# add name and nodes
names.append(sline[0])
node_labels.append(sline[1:3])
# get control nodes
control_source[sline[0]] = sline[3:5]
# get gain
values.append(float(self.convert_unit(sline[5])))
# voltage controlled voltage sources
elif sline[0][0].upper() == 'F':
# add name and nodes
names.append(sline[0])
node_labels.append(sline[1:3])
# get control Vsens
control_source[sline[0]] = sline[3]
# get gain
values.append(float(self.convert_unit(sline[4])))
# reordering nodes
unique_names, ii = np.unique(node_labels, return_inverse=True)
if '0' not in unique_names:
raise ValueError("Error: the network does not include node '0'")
nodes = np.reshape(ii, (len(node_labels),2))
# link name-2-number
node_labels2num = {}
for k , label in enumerate(np.unique(node_labels)):
node_labels2num[label] = k
Nn = nodes.max()
# return network structure
return names, values, IC, source_type, control_source, nodes, node_labels2num, Nn, analysis, plot_cmd, tf_cmd
def convert_unit(self, string_value):
"""
'convert_unit' convert a unit-prefix in a string with the releted value
:param string_value: a string with a unit prefic (e.g. '10.5k')
:return: the same sting with the numerical value of the unit-prefix (e.g. '10.5e3')
"""
for prefix, prefix_value in self.unit_prefix.items():
if prefix in string_value.lower():
string_value = string_value.lower().replace(prefix, prefix_value)
break
return string_value
def incidence_matrix(self):
"""
'incidence_matrix' creates the branch-2-node incidence matrix
:return: update self with self.A
"""
# initialize incidence matrix terms
a = []
a_row = []
a_col = []
# cycle on branches (N1 and N2)
for b, nodes in enumerate(self.nodes):
# get nodes
N1, N2 = nodes
# detect connection to ground
if N1 == 0:
a.append(-1)
a_row.append(N2 - 1)
a_col.append(b)
elif N2 == 0:
a.append(1)
a_row.append(N1 - 1)
a_col.append(b)
else:
a.append(1)
a_row.append(N1 - 1)
a_col.append(b)
a.append(-1)
a_row.append(N2 - 1)
a_col.append(b)
# create conductance matrix
self.A = csr_matrix((a, (a_row, a_col)))
def conductance_matrix(self):
"""
'conductance_matrix' creates the conductance matrix
:return: G, conductance matrix (including constant terms related to inductors and independent voltage sources)
"""
# initialize conductance terms
g = []
g_row = []
g_col = []
# reorder if necessary
if self.isort is None:
self.reorder()
# get index
indexR = self.isort[0]
indexL = sorted(self.isort[1])
indexV = sorted(self.isort[3])
indexE = sorted(self.isort[5])
indexF = sorted(self.isort[6])
# cycle on resistances
for ir in indexR:
# get nores
N1, N2 = self.nodes[ir]
# detect connection
if (N1 == 0) or (N2 == 0): # if grounded...
# diagonal term
g.append(1.0 / self.values[ir])
g_row.append(max([N1, N2]) - 1)
g_col.append(max([N1, N2]) - 1)
else: # if not grounded...
# diagonal term
g.append(1.0 / self.values[ir])
g_row.append(N1 - 1)
g_col.append(N1 - 1)
# diagonal term
g.append(1.0 / self.values[ir])
g_row.append(N2 - 1)
g_col.append(N2 - 1)
# N1-N2 term
g.append(-1.0 / self.values[ir])
g_row.append(N1 - 1)
g_col.append(N2 - 1)
# N2-N1 term
g.append(-1.0 / self.values[ir])
g_row.append(N2 - 1)
g_col.append(N1 - 1)
# cycle on inductors
for k, il in enumerate(indexL):
# get nodes
N1, N2 = self.nodes[il]
# detect connection
if N1 == 0: # if grounded to N1 ...
# negative terminal
g.append(-1)
g_row.append(N2 - 1)
g_col.append(self.node_num + k)
# negative terminal
g.append(-1)
g_row.append(self.node_num + k)
g_col.append(N2 - 1)
elif N2 == 0: # if grounded to N2 ...
# positive terminal
g.append(1)
g_row.append(N1 - 1)
g_col.append(self.node_num + k)
# positive terminal
g.append(1)
g_row.append(self.node_num + k)
g_col.append(N1 - 1)
else: # if not grounded ...
# positive terminal
g.append(1)
g_row.append(N1 - 1)
g_col.append(self.node_num + k)
# positive terminal
g.append(1)
g_row.append(self.node_num + k)
g_col.append(N1 - 1)
# negative terminal
g.append(-1)
g_row.append(N2 - 1)
g_col.append(self.node_num + k)
# negative terminal
g.append(-1)
g_row.append(self.node_num + k)
g_col.append(N2 - 1)
# cycle on independent voltage sources
for k, iv in enumerate(indexV):
# get nodes
N1, N2 = self.nodes[iv]
# detect connection
if N1 == 0: # if grounded to N1 ...
# negative terminal
g.append(-1)
g_row.append(N2 - 1)
g_col.append(self.node_num + len(indexL) + k)
# negative terminal
g.append(-1)
g_row.append(self.node_num + len(indexL) + k)
g_col.append(N2 - 1)
elif N2 == 0: # if grounded to N2 ...
# positive terminal
g.append(1)
g_row.append(N1 - 1)
g_col.append(self.node_num + len(indexL) + k)
# positive terminal
g.append(1)
g_row.append(self.node_num + len(indexL) + k)
g_col.append(N1 - 1)
else: # if not grounded ...
# positive terminal
g.append(1)
g_row.append(N1 - 1)
g_col.append(self.node_num + len(indexL) + k)
# positive terminal
g.append(1)
g_row.append(self.node_num + len(indexL) + k)
g_col.append(N1 - 1)
# negative terminal
g.append(-1)
g_row.append(N2 - 1)
g_col.append(self.node_num + len(indexL) + k)
# negative terminal
g.append(-1)
g_row.append(self.node_num + len(indexL) + k)
g_col.append(N2 - 1)
# cycle on VCVS
for k, ie in enumerate(indexE):
# get nodes
N1, N2 = self.nodes[ie]
# detect connection
if N1 == 0: # if grounded to N1 ...
# negative terminal
g.append(-1)
g_row.append(N2 - 1)
g_col.append(self.node_num + len(indexL) + len(indexV) + k)
# negative terminal
g.append(-1)
g_row.append(self.node_num + len(indexL) + len(indexV) + k)
g_col.append(N2 - 1)
elif N2 == 0: # if grounded to N2 ...
# positive terminal
g.append(1)
g_row.append(N1 - 1)
g_col.append(self.node_num + len(indexL) + len(indexV) + k)
# positive terminal
g.append(1)
g_row.append(self.node_num + len(indexL) + len(indexV) + k)
g_col.append(N1 - 1)
else: # if not grounded ...
# positive terminal
g.append(1)
g_row.append(N1 - 1)
g_col.append(self.node_num + len(indexL) + len(indexV) + k)
# positive terminal
g.append(1)
g_row.append(self.node_num + len(indexL) + len(indexV) + k)
g_col.append(N1 - 1)
# negative terminal
g.append(-1)
g_row.append(N2 - 1)
g_col.append(self.node_num + len(indexL) + len(indexV) + k)
# negative terminal
g.append(-1)
g_row.append(self.node_num + len(indexL) + len(indexV) + k)
g_col.append(N2 - 1)
# get control nodes
N1, N2 = [self.node_label2num[k] for k in self.control_source[self.names[ie]]]
# detect connection
if N1 == 0: # if grounded to N1 ...
# negative terminal
g.append(self.values[ie])
g_row.append(self.node_num + len(indexL) + len(indexV) + k)
g_col.append(N2 - 1)
elif N2 == 0: # if grounded to N2 ...
# positive terminal
g.append(-self.values[ie])
g_row.append(self.node_num + len(indexL) + len(indexV) + k)
g_col.append(N1 - 1)
else: # if not grounded ...
# positive terminal
g.append(-self.values[ie])
g_row.append(self.node_num + len(indexL) + len(indexV) + k)
g_col.append(N1 - 1)
# negative terminal
g.append(self.values[ie])
g_row.append(self.node_num + len(indexL) + len(indexV) + k)
g_col.append(N2 - 1)
# cycle on CCCSs
for k, indF in enumerate(indexF):
# get nodes
N1, N2 = self.nodes[indF]
# get Vsens
Vsens = self.control_source[self.names[indF]]
# get index of Vsens
if Vsens[0].upper() == 'V':
h = sorted(self.isort[3]).index(self.names.index(Vsens))
n = self.node_num + len(self.isort[1]) + h
elif Vsens[0].upper() == 'E':
h = sorted(self.isort[5]).index(self.names.index(Vsens))
n = self.node_num + len(self.isort[1]) + len(self.isort[3]) + h
if N1 == 0: # if grounded to N1 ...
g.append(-self.values[indF])
g_row.append(N2 - 1)
g_col.append(n)
elif N2 == 0: # if grounded to N2 ...
g.append(self.values[indF])
g_row.append(N1 - 1)
g_col.append(n)
else: # if not grounded ...
g.append(self.values[indF])
g_row.append(N1 - 1)
g_col.append(n)
#
g.append(-self.values[indF])
g_row.append(N2 - 1)
g_col.append(n)
# create conductance matrix
self.G = csr_matrix((g,(g_row,g_col)))
def dynamic_matrix(self):
"""
'dynamic_matrix' creates the dynamic matrix
:return: C, dynamic matrix (inductors and capacitors)
"""
# initialize conductance terms
c = []
c_row = []
c_col = []
# reorder if necessary
if self.isort is None:
self.reorder()
# get index
indexL = sorted(self.isort[1])
indexC = self.isort[2]
# cycle on inductors
for k, il in enumerate(indexL):
c.append(-self.values[il])
c_row.append(self.node_num + k)
c_col.append(self.node_num + k)
# cycle on capacitors
for ic in indexC:
# get nores
N1, N2 = self.nodes[ic]
# detect connection
if (N1 == 0) or (N2 == 0): # if grounded...
# diagonal term
c.append(self.values[ic])
c_row.append(max([N1, N2]) - 1)
c_col.append(max([N1, N2]) - 1)
else: # if not grounded...
# diagonal term
c.append(self.values[ic])
c_row.append(N1 - 1)
c_col.append(N1 - 1)
# diagonal term
c.append(self.values[ic])
c_row.append(N2 - 1)
c_col.append(N2 - 1)
# N1-N2 term
c.append(-self.values[ic])
c_row.append(N1 - 1)
c_col.append(N2 - 1)
# N2-N1 term
c.append(-self.values[ic])
c_row.append(N2 - 1)
c_col.append(N1 - 1)
# create dynamic matrix
self.C = csr_matrix((c, (c_row, c_col)), shape=self.G.shape)
def rhs_matrix(self):
"""
'rhs_matrix' creates the right hand side matrix
:return: rhs, right hand side
"""
# reorder if necessary
if self.isort is None:
self.reorder()
if self.analysis[0] == '.tran':
def fun(t):
# initialize rhs
rhs = [0] * (self.node_num + len(self.isort[1]) + len(self.isort[3]) + len(self.isort[5]))
# get index
NL = len(self.isort[1])
indexV = sorted(self.isort[3])
indexI = self.isort[4]
# cycle on independent voltage sources
for k, iv in enumerate(indexV):
if isinstance(self.values[iv], list):
tsr_fun = getattr(tsr, self.source_type[self.names[iv]])
rhs[self.node_num + NL + k] += tsr_fun(*self.values[iv], t=t)
else:
# update rhs
rhs[self.node_num + NL + k] += self.values[iv]
# cycle on independent current sources
for ii in indexI:
# get nodes
N1, N2 = self.nodes[ii]
if isinstance(self.values[ii], list):
tsr_fun = getattr(tsr, self.source_type[self.names[ii]])
if N1 == 0:
# update rhs
rhs[N2 - 1] += tsr_fun(*self.values[ii], t=t)
elif N2 == 0:
# update rhs
rhs[N1 - 1] -= tsr_fun(*self.values[ii], t=t)
else:
# update rhs
rhs[N1 - 1] -= tsr_fun(*self.values[ii], t=t)
rhs[N2 - 1] += tsr_fun(*self.values[ii], t=t)
else:
if N1 == 0:
# update rhs
rhs[N2 - 1] += self.values[ii]
elif N2 == 0:
# update rhs
rhs[N1 - 1] -= self.values[ii]
else:
# update rhs
rhs[N1 - 1] -= self.values[ii]
rhs[N2 - 1] += self.values[ii]
return np.array(rhs)
return fun
else:
# initialize rhs
rhs = [0] * (self.node_num + len(self.isort[1]) + len(self.isort[3]) + len(self.isort[5]))
# get index
NL = len(self.isort[1])
indexV = sorted(self.isort[3])
indexI = self.isort[4]
# cycle on independent voltage sources
for k, iv in enumerate(indexV):
# update rhs
rhs[self.node_num + NL + k] += self.values[iv]
# cycle on independent current sources
for ii in indexI:
# get nodes
N1, N2 = self.nodes[ii]
if N1 == 0:
# update rhs
rhs[N2 - 1] += self.values[ii]
elif N2 == 0:
# update rhs
rhs[N1 - 1] -= self.values[ii]
else:
# update rhs
rhs[N1 - 1] -= self.values[ii]
rhs[N2 - 1] += self.values[ii]
self.rhs = np.array(rhs)
def branch_voltage(self):
"""
"branch_voltage" computes the branch voltages
:return:
* self.vb
"""
# check if the incidence matrix is available
if self.A is None:
self.incidence_matrix()
# check if the solution is available
if self.x is None:
print("No solution available")
return None
# branch voltages
self.vb = self.A.transpose() * self.x[:self.node_num, ...]
def branch_current(self):
"""
"branch_current" computes the branch currents
:return:
* self.ib
"""
# check is branch voltages are available
if self.vb is None:
self.branch_voltage()
self.ib = np.zeros_like(self.vb)
for k, name in enumerate(self.names):
self.ib[k, ...] = self.get_current(name)
def branch_power(self):
"""
"branch_power" computes the branch power
(passive sign convention)
:return:
* self.pb: real power for '.op' and complex power for '.ac'
"""
# check is branch voltages are available
if self.vb is None:
self.branch_voltage()
# check is branch current are available
if self.ib is None:
self.branch_current()
if self.analysis[0].lower() == '.ac':
self.pb = self.vb * np.conj(self.ib)
else:
self.pb = self.vb * self.ib
def frequency_span(self):
"""
"frequency_span" generates the frequency span for .ac analysys
:return:
* self.f: frequency array
"""
if self.analysis[0].lower() != '.ac':
raise ValueError("frequency_span works only for .ac analyses")
if self.analysis[1].lower() == 'lin':
npt = float(self.analysis[2])
fs = float(self.convert_unit(self.analysis[3]))
fe = float(self.convert_unit(self.analysis[4]))
self.f = np.linspace(fs, fe, npt)
elif self.analysis[1].lower() == 'dec':
npt_d = float(self.analysis[2])
fs = np.log10(float(self.convert_unit(self.analysis[3])))
fe = np.log10(float(self.convert_unit(self.analysis[4])))
self.f = np.logspace(fs, fe, np.ceil(npt_d * (fe - fs)))
elif self.analysis[1].lower() == 'oct':
npt_d = float(self.analysis[2])
fs = np.log2(float(self.convert_unit(self.analysis[3])))
fe = np.log2(float(self.convert_unit(self.analysis[4])))
self.f = np.logspace(fs, fe, np.ceil(npt_d * (fe - fs)), base=2)
if self.f.size == 1:
self.f = np.asscalar(self.f)
def get_voltage(self, arg):
"""
"get_voltage" computes a voltage across components of between nodes
:param arg:
* can be a string in the form 'R1 C1 (2,3) (3,0) (2)'
* can be a list of node-pair in the form [[2,3],[3,0]]
:return: voltages (numpy.array)
"""
if isinstance(arg, str): # in the input is a string
# make all uppercase and split
arg = arg
voltage_list = arg.split()
# initialize output