-
Notifications
You must be signed in to change notification settings - Fork 95
/
cktsim.js
2130 lines (1862 loc) · 82 KB
/
cktsim.js
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
// Copyright (C) 2011-2015 Massachusetts Institute of Technology
// Chris Terman and Jacob White
/////////////////////////////////////////////////////////////////////////////
//
// Circuit simulator
//
//////////////////////////////////////////////////////////////////////////////
jade_defs.cktsim = function(jade) {
// JSON circuit description: [{type: device_type,
// connections: {port_name: signal, ...},
// properties: {prop_name: value, ...}} ... ]
// device_type is one of
// "resistor" ports: n1, n2; properties: value, name
// "capacitor" ports: n1, n2; properties: value, name
// "inductor" ports: n1, n2; properties: value, name
// "diode" ports: anode, cathode; properties: area, type, name
// "opamp" ports: nplus, nminus, output, gnd; properties: A, name
// "nfet" ports: d, g, s; properties: W, L, name
// "pfet" ports: d, g, s; properties: W, L, name
// "voltage source" ports: nplus, nminus; properties: value=src, name
// "current source" ports: nplus, nminus; properties: value=src, name
// "connect" ports are all aliases for the same electrical node
// "ground" connections is list of aliases for gnd
// "initial voltage" ports: node; properties: IV, name
// signals are just strings
// src == {type: function_name, args: [number, ...]}
// handy for debugging :)
function print_netlist(netlist) {
$.each(netlist,function(index,c) {
var connections = [];
for (var port in c.connections) connections.push(port+"="+c.connections[port]);
var properties = [];
for (var prop in c.properties) properties.push(prop+"="+JSON.stringify(c.properties[prop]));
console.log(c.type + ' ' + connections.join(' ') + '; ' + properties.join(' '));
});
}
// DC Analysis
// netlist: JSON description of the circuit
// returns associative array mapping node names -> DC value
// throws a string to report errors
function dc_analysis(netlist, sweep1, sweep2, options) {
if (netlist.length > 0) {
var ckt = new Circuit(netlist, options || {});
var source1, start1, stop1, step1, source1_saved_src;
var source2, start2, stop2, step2, source2_saved_src;
if (sweep1.source) {
source1 = ckt.device_map[sweep1.source.toLowerCase()];
if (source1 instanceof VSource) sweep1.units= 'V';
else if (source1 instanceof ISource) sweep1.units= 'A';
else throw "Device 1 not independent source in DC sweep: " + sweep1.source;
start1 = sweep1.start;
stop1 = sweep1.stop;
step1 = sweep1.step;
// make sure sign of step is compatible with bounds
if (start1 <= stop1) step1 = Math.abs(step1);
else step1 = -Math.abs(step1);
// save source function user specified
source1_saved_src = source1.src;
}
if (sweep2.source) {
source2 = ckt.device_map[sweep2.source.toLowerCase()];
if (source2 instanceof VSource) sweep2.units= 'V';
else if (source2 instanceof ISource) sweep2.units= 'A';
else throw "Device 2 not independent source in DC sweep: " + sweep2.source;
start2 = sweep2.start;
stop2 = sweep2.stop;
step2 = sweep2.step;
// make sure sign of step is compatible with bounds
if (start2 <= stop2) step2 = Math.abs(step2);
else step2 = -Math.abs(step2);
// save source function user specified
source2_saved_src = source2.src;
}
// do the sweeps
var val1 = start1;
var val2 = start2;
var results = {
_sweep1_: [],
_network_: ckt
}; // remember sweep1 values as one of the"results
var results2 = [];
while (true) {
// start by setting source values
if (source1) source1.src = jade.utils.parse_source({type: 'dc', args: [val1]});
if (source2) source2.src = jade.utils.parse_source({type: 'dc', args: [val2]});
// do DC analysis, add result to accumulated results for each node and branch
var result = ckt.dc(true);
for (var n in result) {
if (n == '_network_') continue;
if (results[n] === undefined) results[n] = [];
results[n].push(result[n]);
}
results._sweep1_.push(val1); // keep track of sweep settings
results._sweep2_ = val2; // remember sweep2 value as one of the results
if (val1 === undefined) break;
else if (Math.abs(val1 - stop1) < Math.abs(0.01*step1)) {
// end of sweep for first source
if (val2 === undefined) break;
results2.push(results); // accumulate results from first sweep
// check to see if we're done
if (Math.abs(val2 - stop2) < Math.abs(0.01*step2)) {
results = results2; // use accumlated results when there are two sweeps
break;
}
// start first source over again
results = {
_sweep1_: [],
_network_: ckt
};
val1 = start1;
// increment second sweep value, make sure we stop at specified end point
val2 += step2;
if ((step2 > 0 && val2 > stop2) || (step2 < 0 && val2 < stop2)) val2 = stop2;
}
else {
// increment first sweep value, make sure we stop at specified end point
val1 += step1;
if ((step1 > 0 && val1 > stop1) || (step1 < 0 && val1 < stop1)) val1 = stop1;
}
}
// all done, restore saved source functions
if (source1_saved_src !== undefined) source1.src = source1_saved_src;
if (source2_saved_src !== undefined) source2.src = source2_saved_src;
// for no sweep or one sweep: results is dictionary of arrays giving DC results
// for two sweeps: results is an array containing the first sweep results for each
// sweep value of the second source
return results;
}
return undefined;
}
// AC analysis
// netlist: JSON description of the circuit
// fstart: starting frequency in Hz
// fstop: ending frequency in Hz
// ac_source_name: string giving name of source element where small
// signal is injected
// returns associative array mapping <node name> -> {magnitude: val, phase: val}
function ac_analysis(netlist, fstart, fstop, ac_source_name, options) {
var npts = 50;
if (netlist.length > 0) {
var ckt = new Circuit(netlist, options || {});
return ckt.ac(npts, fstart, fstop, ac_source_name);
}
return undefined;
}
// Transient analysis
// netlist: JSON description of the circuit
// tstop: stop time of simulation in seconds
// probe_names: optional list of node names to be checked during LTE calculations
// progress_callback(percent_complete,results)
// function called periodically, return true to halt simulation
// until simulation is complete, results are undefined
// results are associative array mapping node name -> object with attributes
// xvalues -> array of simulation times at which yvalues were measured
// yvalues -> array of voltages/currents
function transient_analysis(netlist, tstop, probe_names, progress_callback, options) {
if (netlist.length > 0 && tstop !== undefined) {
try {
var ckt = new Circuit(netlist, options || {});
}
catch (e) {
if (e instanceof Error) e = e.stack.split('\n').join('<br>');
progress_callback(undefined,e.toString());
return undefined;
}
var progress = {};
progress.probe_names = probe_names, // node names for LTE check
progress.update_interval = 250; // in milliseconds
progress.finish = function(results) {
progress_callback(undefined, results);
};
progress.stop_requested = false;
progress.update = function(percent_complete) { // 0 - 100
// invoke the callback which will return true if the
// simulation should halt.
if (progress_callback(percent_complete, undefined)) progress.stop_requested = true;
};
// give system time to show progress bar before we start simulation
setTimeout(function() {
try {
ckt.tran_start(progress, 100, 0, tstop);
}
catch (e) {
if (e instanceof Error) e = e.stack.split('\n').join('<br>');
progress.finish(e);
}
}, 1);
// simulator will handle the rest...
return undefined;
}
return undefined;
}
///////////////////////////////////////////////////////////////////////////////
//
// Circuit analysis
//
//////////////////////////////////////////////////////////////////////////////
// types of "nodes" in the linear system
var T_VOLTAGE = 0;
var T_CURRENT = 1;
var v_newt_lim = 0.3; // Voltage limited Newton great for Mos/diodes
var v_abstol = 1e-6; // Absolute voltage error tolerance
var i_abstol = 1e-12; // Absolute current error tolerance
var eps = 1.0e-12; // A very small number compared to one.
var dc_max_iters = 1000; // max iterations before giving pu
var max_tran_iters = 20; // max iterations before giving up
var time_step_increase_factor = 2.0; // How much can lte let timestep grow.
var lte_step_decrease_factor = 8; // Limit lte one-iter timestep shrink.
var nr_step_decrease_factor = 4; // Newton failure timestep shink.
var reltol = 0.0001; // Relative tol to max observed value
var lterel = 10; // LTE/Newton tolerance ratio (> 10!)
var res_check_abs = Math.sqrt(i_abstol); // Loose Newton residue check
var res_check_rel = Math.sqrt(reltol); // Loose Newton residue check
function Circuit(netlist, options) {
if (options) {
if (options.v_abstol) v_abstol = options.v_abstol;
if (options.i_abstol) { i_abstol = options.ia_abstol; res_check_abs = Math.sqrt(i_abstol); }
if (options.reltol) { reltol = options.reltol; res_check_rel = Math.sqrt(reltol); }
}
this.node_map = {};
this.ntypes = [];
this.devices = []; // list of devices
this.device_map = {}; // map name -> device
this.voltage_sources = []; // list of voltage sources
this.current_sources = []; // list of current sources
this.initial_voltages = [];
this.finalized = false;
this.diddc = false;
this.node_index = -1;
this.periods = 1;
if (netlist !== undefined) this.load_netlist(netlist);
}
Circuit.prototype.history = function(node) {
if (this.result === undefined || this.result[node] === undefined)
return undefined;
var yvalues = this.result[node];
if (typeof yvalues == 'number') {
// change a single numeric value into an array of that value
var y = yvalues;
yvalues = this.result._xvalues_.slice();
for (var i = 0; i < yvalues.length; i += 1) yvalues[i] = y;
this.result[node] = yvalues;
}
return {xvalues: this.result._xvalues_, yvalues: yvalues};
};
Circuit.prototype.result_type = function() { return 'analog'; };
Circuit.prototype.node_list = function() {
var nlist = [];
for (var n in this.results) nlist.push(n);
return nlist;
};
// index of ground node
Circuit.prototype.gnd_node = function() {
return -1;
};
// allocate a new node index
Circuit.prototype.node = function(name, ntype) {
this.node_index += 1;
if (name) this.node_map[name] = this.node_index;
this.ntypes.push(ntype);
return this.node_index;
};
// call to finalize the circuit in preparation for simulation
Circuit.prototype.finalize = function() {
if (!this.finalized) {
this.finalized = true;
this.N = this.node_index + 1; // number of nodes
// give each device a chance to finalize itself
for (var i = this.devices.length - 1; i >= 0; i -= 1) {
this.devices[i].finalize(this);
}
// set up augmented matrix and various temp vectors
this.matrix = mat_make(this.N, this.N + 1);
this.Gl = mat_make(this.N, this.N); // Matrix for linear conductances
this.G = mat_make(this.N, this.N); // Complete conductance matrix
this.C = mat_make(this.N, this.N); // Matrix for linear L's and C's
this.soln_max = new Array(this.N); // max abs value seen for each unknown
this.abstol = new Array(this.N);
this.solution = new Array(this.N);
this.rhs = new Array(this.N);
for (i = this.N - 1; i >= 0; i -= 1) {
this.soln_max[i] = 0.0;
this.abstol[i] = this.ntypes[i] == T_VOLTAGE ? v_abstol : i_abstol;
this.solution[i] = 0.0;
this.rhs[i] = 0.0;
}
// apply any initial voltages
for (i = 0; i < this.initial_voltages.length; i += 1) {
var node = this.initial_voltages[i].node;
var v = this.initial_voltages[i].v;
this.solution[node] = v;
this.soln_max[node] = v;
}
// Load up the linear elements once and for all
for (i = this.devices.length - 1; i >= 0; i -= 1) {
this.devices[i].load_linear(this);
}
// Check for voltage source loops.
var n_vsrc = this.voltage_sources.length;
if (n_vsrc > 0) { // At least one voltage source
var GV = mat_make(n_vsrc, this.N); // Loop check
for (i = n_vsrc - 1; i >= 0; i -= 1) {
var branch = this.voltage_sources[i].branch;
for (var j = this.N - 1; j >= 0; j -= 1) {
GV[i][j] = this.Gl[branch][j];
}
}
var rGV = mat_rank(GV);
if (rGV < n_vsrc) {
throw 'Warning!!! Circuit has a voltage source loop or a source or current probe shorted by a wire, please remove the source or the wire causing the short.';
}
}
}
return true;
};
// load circuit from JSON netlist: [[device,[connections,...],{prop: value,...}]...]
Circuit.prototype.load_netlist = function(netlist) {
var i, j, c, component, connections, node;
// set up mapping for all ground connections
for (i = netlist.length - 1; i >= 0; i -= 1) {
if (netlist[i].type == 'ground') {
connections = netlist[i].connections;
for (j = 0; j < connections.length; j += 1) {
c = connections[j];
this.node_map[c] = this.gnd_node();
}
}
}
// "connect a b ..." makes a, b, ... aliases for the same node
var aliases = {}; // keep track of canonical name for a node
for (i = netlist.length - 1; i >= 0; i -= 1) {
if (netlist[i].type == 'connect') {
connections = netlist[i].connections;
if (connections.length <= 1) continue;
// see if any of the connected nodes is a ground node.
// if so, make it the canonical name. Otherwise just choose
// connections[0] as the canonical name.
var cname = connections[0];
for (j = 1; j < connections.length; j += 1) {
c = connections[j];
if (this.node_map[c] !== undefined) {
cname = c;
break;
}
}
while (aliases[cname] !== undefined) cname = aliases[cname]; // follow alias chain
// so make all the other connected nodes aliases for the canonical name
for (j = 1; j < connections.length; j += 1) {
c = connections[j];
while (aliases[c] !== undefined) c = aliases[c]; // follow alias chain
if (cname != c) aliases[c] = cname;
}
}
}
// process each component in the JSON netlist (see schematic.js for format)
var found_ground = false; // is some component hooked to gnd?
this.counts = {};
for (i = netlist.length - 1; i >= 0; i -= 1) {
component = netlist[i];
var type = component.type;
var properties = component.properties;
this.counts[type] = (this.counts[type] || 0) + 1;
// convert node names to circuit indicies
var connections = {};
for (c in component.connections) {
node = component.connections[c];
while (aliases[node] !== undefined) node = aliases[node]; // follow alias chain
var index = this.node_map[node];
if (index === undefined) index = this.node(node, T_VOLTAGE);
else if (index == this.gnd_node()) found_ground = true;
connections[c] = index;
}
// process the component
var name = properties.name;
switch (type) {
case 'resistor':
this.r(connections.n1, connections.n2, properties.value, name);
break;
case 'diode':
this.d(connections.anode, connections.cathode, properties.area, properties.type, name);
break;
case 'capacitor':
this.c(connections.n1, connections.n2, properties.value, name);
break;
case 'inductor':
break;
case 'voltage source':
this.v(connections.nplus, connections.nminus, properties.value, name);
break;
case 'current source':
this.i(connections.nplus, connections.nminus, properties.value, name);
break;
case 'opamp':
this.opamp(connections.nplus, connections.nminus, connections.output, connections.gnd, properties.A, name);
break;
case 'nfet':
this.n(connections.d, connections.g, connections.s, properties.W, properties.L, name);
break;
case 'pfet':
this.p(connections.d, connections.g, connections.s, properties.W, properties.L, name);
break;
case 'voltage probe':
break;
case 'ground':
break;
case 'connect':
break;
case 'initial voltage':
this.initial_voltages.push({node: connections.node, v:properties.IV});
break;
default:
throw 'Unrecognized device type ' + type;
}
}
if (!found_ground) { // No ground connection from some device
throw 'Please make at least one connection to ground (node gnd)';
}
// finally, update node_map to reflect aliases created by .connect
for (node in aliases) {
c = node;
while (aliases[c] !== undefined) c = aliases[c]; // follow alias chain
// if there's an node index for the canonical node add an entry in node_map for node -> index
i = this.node_map[c];
if (i !== undefined) this.node_map[node] = i;
}
// discover CMOS gates for later analysis
this.find_cmos_gates();
// report circuit stats
var msg = (this.node_index + 1).toString() + ' nodes';
this.size = 0;
for (var d in this.counts) {
msg += ', ' + this.counts[d].toString() + ' ' + d;
this.size += this.counts[d];
}
console.log(msg);
};
Circuit.prototype.find_cmos_gates = function() {
// for each fet, record its source/drain connectivity
var source_drain = {};
$.each(this.devices,function (index,d) {
if (d instanceof Fet) {
if (source_drain[d.d] === undefined) source_drain[d.d] = [];
source_drain[d.d].push(d);
if (source_drain[d.s] === undefined) source_drain[d.s] = [];
source_drain[d.s].push(d);
}
});
//console.log(source_drain);
// find output nodes of CMOS gates by looking for nodes that connect
// to both P and N fets
var cmos_outputs = [];
$.each(source_drain,function (node,fets) {
var found_n = false;
var found_p = false;
$.each(fets,function (index,fet) {
if (fet.type_sign == 1) found_n = true;
else found_p = true;
});
if (found_n && found_p) cmos_outputs.push(node);
});
//console.log(cmos_outputs);
this.counts['cmos_gates'] = cmos_outputs.length;
};
// if converges: updates this.solution, this.soln_max, returns iter count
// otherwise: return undefined and set this.problem_node
// Load should compute -f and df/dx (note the sign pattern!)
Circuit.prototype.find_solution = function(load, maxiters) {
var soln = this.solution;
var rhs = this.rhs;
var d_sol = [];
var abssum_compare;
var converged, abssum_old = 0,
abssum_rhs;
var use_limiting = false;
var down_count = 0;
// iteratively solve until values converge or iteration limit exceeded
for (var iter = 0; iter < maxiters; iter += 1) {
var i;
// set up equations
load.call(this, soln, rhs); // load should be a method of Circuit
// Compute norm of rhs, assume variables of v type go with eqns of i type
abssum_rhs = 0;
for (i = this.N - 1; i >= 0; i -= 1) {
if (this.ntypes[i] == T_VOLTAGE) abssum_rhs += Math.abs(rhs[i]);
}
if ((iter > 0) && (use_limiting === false) && (abssum_old < abssum_rhs)) {
// Old rhsnorm was better, undo last iter and turn on limiting
for (i = this.N - 1; i >= 0; i -= 1) {
soln[i] -= d_sol[i];
}
iter -= 1;
use_limiting = true;
}
else { // Compute the Newton delta
//d_sol = mat_solve(this.matrix,rhs);
d_sol = mat_solve_rq(this.matrix, rhs);
// If norm going down for ten iters, stop limiting
if (abssum_rhs < abssum_old) down_count += 1;
else down_count = 0;
if (down_count > 10) {
use_limiting = false;
down_count = 0;
}
// Update norm of rhs
abssum_old = abssum_rhs;
}
// Update the worst case abssum for comparison.
if ((iter === 0) || (abssum_rhs > abssum_compare)) abssum_compare = abssum_rhs;
// Check residue convergence, but loosely, and give up
// on last iteration
if ((iter < (maxiters - 1)) && (abssum_rhs > (res_check_abs + res_check_rel * abssum_compare))) converged = false;
else converged = true;
// Update solution and check delta convergence
for (i = this.N - 1; i >= 0; i -= 1) {
// Simple voltage step limiting to encourage Newton convergence
if (use_limiting) {
if (this.ntypes[i] == T_VOLTAGE) {
d_sol[i] = (d_sol[i] > v_newt_lim) ? v_newt_lim : d_sol[i];
d_sol[i] = (d_sol[i] < -v_newt_lim) ? -v_newt_lim : d_sol[i];
}
}
soln[i] += d_sol[i];
var thresh = this.abstol[i] + reltol * this.soln_max[i];
if (Math.abs(d_sol[i]) > thresh) {
converged = false;
this.problem_node = i;
}
}
//alert(numeric.prettyPrint(this.solution);)
if (converged === true) {
for (i = this.N - 1; i >= 0; i -= 1) {
if (Math.abs(soln[i]) > this.soln_max[i]) this.soln_max[i] = Math.abs(soln[i]);
}
return iter + 1;
}
}
return undefined;
};
// Define -f and df/dx for Newton solver
Circuit.prototype.load_dc = function(soln, rhs) {
// rhs is initialized to -Gl * soln
mat_v_mult(this.Gl, soln, rhs, - 1.0);
// G matrix is initialized with linear Gl
mat_copy(this.Gl, this.G);
// Now load up the nonlinear parts of rhs and G
for (var i = this.devices.length - 1; i >= 0; i -= 1) {
this.devices[i].load_dc(this, soln, rhs);
}
// G matrix is copied in to the system matrix
mat_copy(this.G, this.matrix);
};
// DC analysis
Circuit.prototype.dc = function(report_results) {
// Allocation matrices for linear part, etc.
if (this.finalize() === false) return undefined;
// find the operating point
var iterations = this.find_solution(Circuit.prototype.load_dc, dc_max_iters);
if (typeof iterations == 'undefined') {
// too many iterations
if (report_results) {
if (this.current_sources.length > 0) {
throw 'Unable to find circuit\'s operating point: do your current sources have a conductive path to ground?';
}
else {
throw 'Unable to find circuit\'s operating point: is there a loop in your circuit that\'s oscillating?';
}
} else return false;
}
else {
// Note that a dc solution was computed
this.diddc = true;
if (report_results) {
// create solution dictionary
this.result = {};
// capture node voltages
for (var name in this.node_map) {
var index = this.node_map[name];
this.result[name] = (index == -1) ? 0 : this.solution[index];
}
// capture branch currents from voltage sources
for (var i = this.voltage_sources.length - 1; i >= 0; i -= 1) {
var v = this.voltage_sources[i];
this.result['I(' + v.name + ')'] = this.solution[v.branch];
}
this.result._network_ = this; // for later reference
return this.result;
} else return true;
}
};
// initialize everything for transient analysis
Circuit.prototype.tran_start = function(progress, ntpts, tstart, tstop) {
var i;
// Standard to do a dc analysis before transient
// Otherwise, do the setup also done in dc.
if (this.diddc === false) {
if (!this.dc(false)) { // DC failed, realloc mats and vects.
//throw 'DC failed, trying transient analysis from zero.';
this.finalized = false; // Reset the finalization.
if (this.finalize() === false) progress.finish(undefined); // nothing more to do
}
}
else if (this.finalize() === false) // Allocate matrices and vectors.
progress.finish(undefined); // nothing more to do
// build array to hold list of results for each variable
// last entry is for timepoints.
this.response = new Array(this.N + 1);
for (i = this.N; i >= 0; i -= 1) {
this.response[i] = [];
}
// Allocate back vectors for up to a second order method
this.old3sol = new Array(this.N);
this.old3q = new Array(this.N);
this.old2sol = new Array(this.N);
this.old2q = new Array(this.N);
this.oldsol = new Array(this.N);
this.oldq = new Array(this.N);
this.q = new Array(this.N);
this.oldc = new Array(this.N);
this.c = new Array(this.N);
this.alpha0 = 1.0;
this.alpha1 = 0.0;
this.alpha2 = 0.0;
this.beta0 = new Array(this.N);
this.beta1 = new Array(this.N);
// Mark a set of algebraic variable (don't miss hidden ones!).
this.ar = this.algebraic(this.C);
// Non-algebraic variables and probe variables get lte
this.ltecheck = new Array(this.N);
for (i = this.N; i >= 0; i -= 1) {
this.ltecheck[i] = (this.ar[i] === 0);
}
for (var name in this.node_map) {
var index = this.node_map[name];
for (i = progress.probe_names.length - 1; i >= 0; i -= 1) {
if (name == progress.probe_names[i]) {
this.ltecheck[index] = true;
break;
}
}
}
// Check for periodic sources
var period = tstop - tstart;
var per;
for (i = this.voltage_sources.length - 1; i >= 0; i -= 1) {
per = this.voltage_sources[i].src.period;
if (per > 0) period = Math.min(period, per);
}
for (i = this.current_sources.length - 1; i >= 0; i -= 1) {
per = this.current_sources[i].src.period;
if (per > 0) period = Math.min(period, per);
}
this.periods = Math.ceil((tstop - tstart) / period);
// maximum 50000 steps/period
this.max_nsteps = this.periods * 50000;
this.time = tstart;
// ntpts adjusted by numbers of periods in input
this.max_step = (tstop - tstart) / (this.periods * ntpts);
this.min_step = this.max_step / 1e8;
this.new_step = this.max_step / 1e6;
this.oldt = this.time - this.new_step;
// Initialize old crnts, charges, and solutions.
this.load_tran(this.solution, this.rhs);
for (i = this.N - 1; i >= 0; i -= 1) {
this.old3sol[i] = this.solution[i];
this.old2sol[i] = this.solution[i];
this.oldsol[i] = this.solution[i];
this.old3q[i] = this.q[i];
this.old2q[i] = this.q[i];
this.oldq[i] = this.q[i];
this.oldc[i] = this.c[i];
}
// now for the real work
this.tstart = tstart;
this.tstop = tstop;
this.progress = progress;
this.step_index = -3; // Start with two pseudo-Euler steps
try {
this.tran_steps(new Date().getTime() + progress.update_interval);
}
catch (e) {
progress.finish(e);
}
};
Circuit.prototype.pick_step = function() {
var min_shrink_factor = 1.0 / lte_step_decrease_factor;
var max_growth_factor = time_step_increase_factor;
// Poly coefficients
var dtt0 = (this.time - this.oldt);
var dtt1 = (this.time - this.old2t);
var dtt2 = (this.time - this.old3t);
var dt0dt1 = (this.oldt - this.old2t);
var dt0dt2 = (this.oldt - this.old3t);
var dt1dt2 = (this.old2t - this.old3t);
var p0 = (dtt1 * dtt2) / (dt0dt1 * dt0dt2);
var p1 = (dtt0 * dtt2) / (-dt0dt1 * dt1dt2);
var p2 = (dtt0 * dtt1) / (dt0dt2 * dt1dt2);
var trapcoeff = 0.5 * (this.time - this.oldt) / (this.time - this.old3t);
var maxlteratio = 0.0;
for (var i = this.N - 1; i >= 0; i -= 1) {
if (this.ltecheck[i]) { // Check lte on variable
var pred = p0 * this.oldsol[i] + p1 * this.old2sol[i] + p2 * this.old3sol[i];
var lte = Math.abs((this.solution[i] - pred)) * trapcoeff;
var lteratio = lte / (lterel * (this.abstol[i] + reltol * this.soln_max[i]));
maxlteratio = Math.max(maxlteratio, lteratio);
}
}
var new_step;
var lte_step_ratio = 1.0 / Math.pow(maxlteratio, 1 / 3); // Cube root because trap
if (lte_step_ratio < 1.0) { // Shrink the timestep to make lte
lte_step_ratio = Math.max(lte_step_ratio, min_shrink_factor);
new_step = (this.time - this.oldt) * 0.75 * lte_step_ratio;
new_step = Math.max(new_step, this.min_step);
}
else {
lte_step_ratio = Math.min(lte_step_ratio, max_growth_factor);
if (lte_step_ratio > 1.2) /* Increase timestep due to lte. */
new_step = (this.time - this.oldt) * lte_step_ratio / 1.2;
else new_step = (this.time - this.oldt);
new_step = Math.min(new_step, this.max_step);
}
return new_step;
};
// Define -f and df/dx for Newton solver
Circuit.prototype.load_tran = function(soln, rhs) {
// Crnt is initialized to -Gl * soln
mat_v_mult(this.Gl, soln, this.c, - 1.0);
// G matrix is initialized with linear Gl
mat_copy(this.Gl, this.G);
// Now load up the nonlinear parts of crnt and G
for (var i = this.devices.length - 1; i >= 0; i -= 1) {
this.devices[i].load_tran(this, soln, this.c, this.time);
}
// Exploit the fact that storage elements are linear
mat_v_mult(this.C, soln, this.q, 1.0);
// -rhs = c - dqdt
for (i = this.N - 1; i >= 0; i -= 1) {
var dqdt = this.alpha0 * this.q[i] + this.alpha1 * this.oldq[i] + this.alpha2 * this.old2q[i];
//alert(numeric.prettyPrint(dqdt));
rhs[i] = this.beta0[i] * this.c[i] + this.beta1[i] * this.oldc[i] - dqdt;
}
// matrix = beta0*G + alpha0*C.
mat_scale_add(this.G, this.C, this.beta0, this.alpha0, this.matrix);
};
// here's where the real work is done
// tupdate is the time we should update progress bar
Circuit.prototype.tran_steps = function(tupdate) {
var i;
if (!this.progress.stop_requested) // halt when user clicks stop
while (this.step_index < this.max_nsteps) {
// Save the just computed solution, and move back q and c.
for (i = this.N - 1; i >= 0; i -= 1) {
if (this.step_index >= 0) this.response[i].push(this.solution[i]);
this.oldc[i] = this.c[i];
this.old3sol[i] = this.old2sol[i];
this.old2sol[i] = this.oldsol[i];
this.oldsol[i] = this.solution[i];
this.old3q[i] = this.oldq[i];
this.old2q[i] = this.oldq[i];
this.oldq[i] = this.q[i];
}
if (this.step_index < 0) { // Take a prestep using BE
this.old3t = this.old2t - (this.oldt - this.old2t);
this.old2t = this.oldt - (this.tstart - this.oldt);
this.oldt = this.tstart - (this.time - this.oldt);
this.time = this.tstart;
this._beta0 = 1.0;
this._beta1 = 0.0;
}
else { // Take a regular step
// Save the time, and rotate time wheel
this.response[this.N].push(this.time);
this.old3t = this.old2t;
this.old2t = this.oldt;
this.oldt = this.time;
// Make sure we come smoothly in to the interval end.
if (this.time >= this.tstop) break; // We're done!
else if (this.time + this.new_step > this.tstop) this.time = this.tstop;
else if (this.time + 1.5 * this.new_step > this.tstop) this.time += (2 / 3) * (this.tstop - this.time);
else this.time += this.new_step;
// Use trap (average old and new crnts.
this._beta0 = 0.5;
this._beta1 = 0.5;
}
// For trap rule, turn off current avging for algebraic eqns
for (i = this.N - 1; i >= 0; i -= 1) {
this.beta0[i] = this._beta0 + this.ar[i] * this._beta1;
this.beta1[i] = (1.0 - this.ar[i]) * this._beta1;
}
// Loop to find NR converging timestep with okay LTE
while (true) {
// Set the timestep coefficients (alpha2 is for bdf2).
this.alpha0 = 1.0 / (this.time - this.oldt);
this.alpha1 = -this.alpha0;
this.alpha2 = 0;
// If timestep is 1/10,000th of tstop, just use BE.
if ((this.time - this.oldt) < 1.0e-4 * this.tstop) {
for (i = this.N - 1; i >= 0; i -= 1) {
this.beta0[i] = 1.0;
this.beta1[i] = 0.0;
}
}
// Use Newton to compute the solution.
var iterations = this.find_solution(Circuit.prototype.load_tran, max_tran_iters);
// If NR succeeds and stepsize is at min, accept and newstep=maxgrowth*minstep.
// Else if Newton Fails, shrink step by a factor and try again
// Else LTE picks new step, if bigger accept current step and go on.
if ((iterations !== undefined) && (this.step_index <= 0 || (this.time - this.oldt) < (1 + reltol) * this.min_step)) {
if (this.step_index > 0) this.new_step = time_step_increase_factor * this.min_step;
break;
}
else if (iterations === undefined) { // NR nonconvergence, shrink by factor
//alert('timestep nonconvergence ' + this.time + ' ' + this.step_index);
this.time = this.oldt + (this.time - this.oldt) / nr_step_decrease_factor;
}
else { // Check the LTE and shrink step if needed.
this.new_step = this.pick_step();
if (this.new_step < (1.0 - reltol) * (this.time - this.oldt)) {
this.time = this.oldt + this.new_step; // Try again
}
else break; // LTE okay, new_step for next step
}
}
this.step_index += 1;
var t = new Date().getTime();
if (t >= tupdate) {
// update progress bar
var completed = Math.round(100 * (this.time - this.tstart) / (this.tstop - this.tstart));
this.progress.update(completed);
// a brief break in the action to allow progress bar to update
// then pick up where we left off
var ckt = this;
setTimeout(function() {
try {
ckt.tran_steps(t + ckt.progress.update_interval);
}
catch (e) {
ckt.progress.finish(e);
}
}, 1);
// our portion of the work is done
return;
}
}
// analysis complete -- create solution dictionary
this.result = {};
for (var name in this.node_map) {
var index = this.node_map[name];
this.result[name] = (index == -1) ? 0 : this.response[index];
}
// capture branch currents from voltage sources
for (i = this.voltage_sources.length - 1; i >= 0; i -= 1) {
var v = this.voltage_sources[i];
this.result['I(' + v.name + ')'] = this.response[v.branch];
}
this.result._xvalues_ = this.response[this.N];
this.result._network_ = this; // for later reference
//this.progress.finish(result);
throw this.result;
};
// AC analysis: npts/decade for freqs in range [fstart,fstop]
// result._frequencies_ = vector of log10(sample freqs)
// result['xxx'] = vector of dB(response for node xxx)
Circuit.prototype.ac = function(npts, fstart, fstop, source_name) {
var i;
this.dc(true); // make sure we can find operating point
var N = this.N;
var G = this.G;
var C = this.C;
// Complex numbers, we're going to need a bigger boat
var matrixac = mat_make(2 * N, (2 * N) + 1);
// Get the source used for ac
source_name = source_name.toLowerCase();
if (this.device_map[source_name] === undefined) {
throw 'AC analysis refers to unknown source ' + source_name;
}
this.device_map[source_name].load_ac(this, this.rhs);
// build array to hold list of magnitude and phases for each node
// last entry is for frequency values
var response = new Array(2 * N + 1);
for (i = 2 * N; i >= 0; i -= 1) {
response[i] = [];
}
// multiplicative frequency increase between freq points
var delta_f = Math.exp(Math.LN10 / npts);
var phase_offset = new Array(N);
for (i = N - 1; i >= 0; i -= 1) {
phase_offset[i] = 0;
}
var f = fstart;
fstop *= 1.0001; // capture that last freq point!