summaryrefslogtreecommitdiffstatshomepage
path: root/src/emu/netlist/analog/nld_solver.c
blob: 7ede33a26644400dbe43f2244fc0c12b37762912 (plain) (blame)
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
/*
 * nld_solver.c
 *
 */

#include "nld_solver.h"
#include "nld_twoterm.h"
#include "../nl_lists.h"

#if HAS_OPENMP
#include "omp.h"
#endif

// ----------------------------------------------------------------------------------------
// netlist_matrix_solver
// ----------------------------------------------------------------------------------------

#define SOLVER_VERBOSE_OUT(x) do {} while (0)
//#define SOLVER_VERBOSE_OUT(x) printf x

ATTR_COLD netlist_matrix_solver_t::netlist_matrix_solver_t()
: m_owner(NULL)
{
}

ATTR_COLD netlist_matrix_solver_t::~netlist_matrix_solver_t()
{
#if NEW_INPUT
    for (int i = 0; i < m_inps.count(); i++)
        delete m_inps[i];
#endif
}

ATTR_COLD void netlist_matrix_solver_t::setup(netlist_net_t::list_t &nets, NETLIB_NAME(solver) &aowner)
{
	m_owner = &aowner;

	NL_VERBOSE_OUT(("New solver setup\n"));

	for (netlist_net_t * const * pn = nets.first(); pn != NULL; pn = nets.next(pn))
	{
		NL_VERBOSE_OUT(("setting up net\n"));

		m_nets.add(*pn);

		(*pn)->m_solver = this;

        for (int i = 0; i < (*pn)->m_core_terms.count(); i++)
		{
		    netlist_core_terminal_t *p = (*pn)->m_core_terms[i];
			NL_VERBOSE_OUT(("%s %s %d\n", p->name().cstr(), (*pn)->name().cstr(), (int) (*pn)->isRailNet()));
			switch (p->type())
			{
				case netlist_terminal_t::TERMINAL:
					switch (p->netdev().family())
					{
						case netlist_device_t::CAPACITOR:
							if (!m_steps.contains(&p->netdev()))
								m_steps.add(&p->netdev());
							break;
						case netlist_device_t::BJT_EB:
						case netlist_device_t::DIODE:
						//case netlist_device_t::VCVS:
						case netlist_device_t::BJT_SWITCH:
							NL_VERBOSE_OUT(("found BJT/Diode\n"));
							if (!m_dynamic.contains(&p->netdev()))
								m_dynamic.add(&p->netdev());
							break;
						default:
							break;
					}
					{
						netlist_terminal_t *pterm = static_cast<netlist_terminal_t *>(p);
						if (pterm->m_otherterm->net().isRailNet())
							(*pn)->m_rails.add(pterm);
						else
							(*pn)->m_terms.add(pterm);
					}
					NL_VERBOSE_OUT(("Added terminal\n"));
					break;
				case netlist_terminal_t::INPUT:
				    {
#if NEW_INPUT
				        // FIXME: multiple outputs per net ...
                        netlist_analog_output_t *m = new netlist_analog_output_t();
                        m->init_object(*this, this->name() + "." + pstring::sprintf("m%d", m_inps.count()));
                        //register_output("m", *m);
                        m_inps.add(m);
                        m->m_proxied_net = &p->net();
                        m->net().register_con(*p);
                        // FIXME: repeated
                        m->net().rebuild_list();
#else
                        if (!m_inps.contains(p))
                            m_inps.add(p)
#endif
                        NL_VERBOSE_OUT(("Added input\n"));
				    }
                    break;
				default:
					owner().netlist().error("unhandled element found\n");
					break;
			}
		}
		NL_VERBOSE_OUT(("added net with %d populated connections (%d railnets)\n", (*pn)->m_terms.count(), (*pn)->m_rails.count()));
	}
}

ATTR_HOT void netlist_matrix_solver_t::update_inputs()
{

#if NEW_INPUT
    // avoid recursive calls. Inputs are updated outside this call
    for (netlist_analog_output_t * const *p = m_inps.first(); p != NULL; p = m_inps.next(p))
        if ((*p)->m_proxied_net->m_last_Analog != (*p)->m_proxied_net->m_cur_Analog)
            (*p)->set_Q((*p)->m_proxied_net->m_cur_Analog);
    for (netlist_analog_output_t * const *p = m_inps.first(); p != NULL; p = m_inps.next(p))
    {
        if ((*p)->m_proxied_net->m_last_Analog != (*p)->m_proxied_net->m_cur_Analog)
            (*p)->m_proxied_net->m_last_Analog = (*p)->m_proxied_net->m_cur_Analog;
    }
#else
	for (netlist_core_terminal_t * const *p = m_inps.first(); p != NULL; p = m_inps.next(p))
	{
		if ((*p)->net().m_last_Analog != (*p)->net().m_cur_Analog)
		{
			(*p)->netdev().update_dev();
		}
	}
	for (netlist_core_terminal_t * const *p = m_inps.first(); p != NULL; p = m_inps.next(p))
	{
        if ((*p)->net().m_last_Analog != (*p)->net().m_cur_Analog)
            (*p)->net().m_last_Analog = (*p)->net().m_cur_Analog;
	}
#endif

}


ATTR_HOT void netlist_matrix_solver_t::update_dynamic()
{
	/* update all non-linear devices  */
	for (netlist_core_device_t * const *p = m_dynamic.first(); p != NULL; p = m_dynamic.next(p))
		switch ((*p)->family())
		{
			case netlist_device_t::DIODE:
				static_cast<NETLIB_NAME(D) *>((*p))->update_terminals();
				break;
			default:
				(*p)->update_terminals();
				break;
		}
}

ATTR_HOT void netlist_matrix_solver_t::schedule()
{
    // FIXME: Make this a parameter
#if 0
    if (!m_Q_sync.net().is_queued())
        m_Q_sync.net().push_to_queue(m_params.m_nt_sync_delay);
#else
    if (solve())
        update_inputs();
#endif
}

ATTR_COLD void netlist_matrix_solver_t::start()
{
    register_output("Q_sync", m_Q_sync);
    register_input("FB_sync", m_fb_sync);
    connect(m_fb_sync, m_Q_sync);
}

ATTR_COLD void netlist_matrix_solver_t::reset()
{
	m_last_step = netlist_time::zero;
}

ATTR_COLD void netlist_matrix_solver_t::update()
{
    if (solve())
        update_inputs();
}


ATTR_HOT void netlist_matrix_solver_t::step(const netlist_time delta)
{
	const double dd = delta.as_double();
	for (int k=0; k < m_steps.count(); k++)
		m_steps[k]->step_time(dd);
}

ATTR_HOT bool netlist_matrix_solver_t::solve()
{

	netlist_time now = owner().netlist().time();
	netlist_time delta = now - m_last_step;

	// We are already up to date. Avoid oscillations.
	if (delta < netlist_time::from_nsec(1))
	    return true;

	NL_VERBOSE_OUT(("Step!\n"));
	/* update all terminals for new time step */
	m_last_step = now;
	//printf("usecs: %f\n", delta.as_double()*1000000.0);
	step(delta);

	if (is_dynamic())
	{
		int this_resched;
		int newton_loops = 0;
		do
		{
            update_dynamic();
            while ((this_resched = solve_non_dynamic()) > m_params.m_gs_loops)
                owner().netlist().warning("Dynamic Solve iterations exceeded .. Consider increasing RESCHED_LOOPS");
            newton_loops++;
		} while (this_resched > 1 && newton_loops < m_params.m_nr_loops);

		// reschedule ....
		if (this_resched > 1 && !m_Q_sync.net().is_queued())
		{
            owner().netlist().warning("NEWTON_LOOPS exceeded ... reschedule");
	        m_Q_sync.net().push_to_queue(m_params.m_nt_sync_delay);
	        return false;
		}
	}
	else
	{
		while (solve_non_dynamic() > m_params.m_gs_loops)
            owner().netlist().warning("Non-Dynamic Solve iterations exceeded .. Consider increasing RESCHED_LOOPS");
	}
	return true;
}

// ----------------------------------------------------------------------------------------
// netlist_matrix_solver - Direct base
// ----------------------------------------------------------------------------------------


template <int m_N, int _storage_N>
ATTR_COLD int netlist_matrix_solver_direct_t<m_N, _storage_N>::get_net_idx(netlist_net_t *net)
{
	for (int k = 0; k < N(); k++)
		if (m_nets[k] == net)
			return k;
	return -1;
}

template <int m_N, int _storage_N>
ATTR_COLD void netlist_matrix_solver_direct_t<m_N, _storage_N>::setup(netlist_net_t::list_t &nets, NETLIB_NAME(solver) &owner)
{
	netlist_matrix_solver_t::setup(nets, owner);

	m_term_num = 0;
	m_rail_start = 0;
	for (int k = 0; k < N(); k++)
	{
		netlist_net_t *net = m_nets[k];
		const netlist_net_t::terminal_list_t &terms = net->m_terms;
		for (int i = 0; i < terms.count(); i++)
		{
			m_terms[m_term_num].net_this = k;
			int ot = get_net_idx(&terms[i]->m_otherterm->net());
			m_terms[m_term_num].net_other = ot;
			m_terms[m_term_num].term = terms[i];
			if (ot>=0)
			{
				m_term_num++;
				SOLVER_VERBOSE_OUT(("Net %d Term %s %f %f\n", k, terms[i]->name().cstr(), terms[i]->m_gt, terms[i]->m_go));
			}
		}
	}
	m_rail_start = m_term_num;
	for (int k = 0; k < N(); k++)
	{
		netlist_net_t *net = m_nets[k];
		const netlist_net_t::terminal_list_t &terms = net->m_terms;
		const netlist_net_t::terminal_list_t &rails = net->m_rails;
		for (int i = 0; i < terms.count(); i++)
		{
			m_terms[m_term_num].net_this = k;
			int ot = get_net_idx(&terms[i]->m_otherterm->net());
			m_terms[m_term_num].net_other = ot;
			m_terms[m_term_num].term = terms[i];
			if (ot<0)
			{
				m_term_num++;
				SOLVER_VERBOSE_OUT(("found term with missing othernet %s\n", terms[i]->name().cstr()));
			}
		}
		for (int i = 0; i < rails.count(); i++)
		{
			m_terms[m_term_num].net_this = k;
			m_terms[m_term_num].net_other = -1; //get_net_idx(&rails[i]->m_otherterm->net());
			m_terms[m_term_num].term = rails[i];
			m_term_num++;
			SOLVER_VERBOSE_OUT(("Net %d Rail %s %f %f\n", k, rails[i]->name().cstr(), rails[i]->m_gt, rails[i]->m_go));
		}
	}
}

template <int m_N, int _storage_N>
ATTR_HOT void netlist_matrix_solver_direct_t<m_N, _storage_N>::build_LE(
		double (* RESTRICT A)[_storage_N],
		double (* RESTRICT RHS))
{
#if 0
	for (int i = 0; i < m_term_num; i++)
	{
		terms_t &t = m_terms[i];
		RHS[t.net_this] += t.term->m_Idr;
		A[t.net_this][t.net_this] += t.term->m_gt;
		if (t.net_other >= 0)
		{
			//m_A[t.net_other][t.net_other] += t.term->m_otherterm->m_gt;
			A[t.net_this][t.net_other] += -t.term->m_go;
			//m_A[t.net_other][t.net_this] += -t.term->m_otherterm->m_go;
		}
		else
			RHS[t.net_this] += t.term->m_go * t.term->m_otherterm->net().Q_Analog();
	}
#else
	for (int i = 0; i < m_rail_start; i++)
	{
		terms_t &t = m_terms[i];
		//printf("A %d %d %s %f %f\n",t.net_this, t.net_other, t.term->name().cstr(), t.term->m_gt, t.term->m_go);

		RHS[t.net_this] += t.term->m_Idr;
		A[t.net_this][t.net_this] += t.term->m_gt;
		A[t.net_this][t.net_other] += -t.term->m_go;
	}
	for (int i = m_rail_start; i < m_term_num; i++)
	{
		terms_t &t = m_terms[i];

		RHS[t.net_this] += t.term->m_Idr;
		A[t.net_this][t.net_this] += t.term->m_gt;
		RHS[t.net_this] += t.term->m_go * t.term->m_otherterm->net().Q_Analog();
	}
#endif
}

template <int m_N, int _storage_N>
ATTR_HOT void netlist_matrix_solver_direct_t<m_N, _storage_N>::gauss_LE(
		double (* RESTRICT A)[_storage_N],
		double (* RESTRICT RHS),
		double (* RESTRICT x))
{
#if 0
	for (int i = 0; i < N(); i++)
	{
		for (int k = 0; k < N(); k++)
			printf("%f ", A[i][k]);
		printf("| %f = %f \n", x[i], RHS[i]);
	}
	printf("\n");
#endif

	for (int i = 0; i < N(); i++) {
#if 0
		/* Find the row with the largest first value */
		int maxrow = i;
		for (int j = i + 1; j < N(); j++)
		{
			if (fabs(A[j][i]) > fabs(A[maxrow][i]))
				maxrow = j;
		}

		if (maxrow != i)
		{
            /* Swap the maxrow and ith row */
            for (int k = i; k < N(); k++) {
                const double tmp = A[i][k];
                A[i][k] = A[maxrow][k];
                A[maxrow][k] = tmp;
            }
            const double tmpR = RHS[i];
            RHS[i] = RHS[maxrow];
            RHS[maxrow] = tmpR;
		}
#endif
		/* Singular matrix? */
		double f = A[i][i];
		//if (fabs(f) < 1e-20) printf("Singular!");
		f = 1.0 / f;

		/* Eliminate column i from row j */
		for (int j = i + 1; j < N(); j++)
		{
			if (A[j][i] != 0.0)
			{
	            const double f1 = A[j][i] * f;

	            for (int k = i; k < N(); k++)
					A[j][k] -= A[i][k] * f1;

	            RHS[j] -= RHS[i] * f1;
			}
		}
	}
	/* back substitution */
	for (int j = N() - 1; j >= 0; j--)
	{
		double tmp = 0;
		for (int k = j + 1; k < N(); k++)
			tmp += A[j][k] * x[k];
		x[j] = (RHS[j] - tmp) / A[j][j];
	}
#if 0
	printf("Solution:\n");
	for (int i = 0; i < N(); i++)
	{
		for (int k = 0; k < N(); k++)
			printf("%f ", A[i][k]);
		printf("| %f = %f \n", x[i], RHS[i]);
	}
	printf("\n");
#endif

}

template <int m_N, int _storage_N>
ATTR_HOT double netlist_matrix_solver_direct_t<m_N, _storage_N>::delta(
		const double (* RESTRICT RHS),
		const double (* RESTRICT V))
{
	double cerr = 0;
	double cerr2 = 0;
	for (int i = 0; i < this->N(); i++)
	{
		double e = (V[i] - this->m_nets[i]->m_cur_Analog);
		double e2 = (RHS[i] - this->m_RHS[i]);
		cerr += e * e;
		cerr2 += e2 * e2;
	}
	return (cerr + cerr2*(100000.0 * 100000.0)) / this->N();
}

template <int m_N, int _storage_N>
ATTR_HOT void netlist_matrix_solver_direct_t<m_N, _storage_N>::store(
		const double (* RESTRICT RHS),
		const double (* RESTRICT V))
{
	for (int i = 0; i < this->N(); i++)
	{
		this->m_nets[i]->m_cur_Analog = this->m_nets[i]->m_new_Analog = V[i];
	}
	if (RHS != NULL)
	{
		for (int i = 0; i < this->N(); i++)
		{
			this->m_RHS[i] = RHS[i];
		}
	}
}

template <int m_N, int _storage_N>
ATTR_HOT int netlist_matrix_solver_direct_t<m_N, _storage_N>::solve_non_dynamic()
{
	double A[_storage_N][_storage_N] = { { 0.0 } };
	double RHS[_storage_N] = { 0.0 };
	double new_v[_storage_N] = { 0.0 };

	this->build_LE(A, RHS);

	this->gauss_LE(A, RHS, new_v);

	if (this->is_dynamic())
	{
		double err = delta(RHS, new_v);

		store(RHS, new_v);

		if (err > this->m_params.m_accuracy * this->m_params.m_accuracy)
		{
			return 2;
		}
		return 1;
	}
	store(NULL, new_v);  // ==> No need to store RHS
	return 1;
}


// ----------------------------------------------------------------------------------------
// netlist_matrix_solver - Direct1
// ----------------------------------------------------------------------------------------

ATTR_HOT int netlist_matrix_solver_direct1_t::solve_non_dynamic()
{

    netlist_net_t *net = m_nets[0];
	double m_A[1][1] = { {0.0} };
	double m_RHS[1] = { 0.0 };
	build_LE(m_A, m_RHS);
	//NL_VERBOSE_OUT(("%f %f\n", new_val, m_RHS[0] / m_A[0][0]);

	double new_val =  m_RHS[0] / m_A[0][0];

	double e = (new_val - net->m_cur_Analog);
	double cerr = e * e;

	net->m_cur_Analog = net->m_new_Analog = new_val;

	if (is_dynamic() && (cerr  > m_params.m_accuracy * m_params.m_accuracy))
	{
		return 2;
	}
	else
		return 1;

}



// ----------------------------------------------------------------------------------------
// netlist_matrix_solver - Direct2
// ----------------------------------------------------------------------------------------

ATTR_HOT int netlist_matrix_solver_direct2_t::solve_non_dynamic()
{
	double A[2][2] = { { 0.0 } };
	double RHS[2] = { 0.0 };

	build_LE(A, RHS);

	const double a = A[0][0];
	const double b = A[0][1];
	const double c = A[1][0];
	const double d = A[1][1];

	double new_val[2];
	new_val[1] = a / (a*d - b*c) * (RHS[1] - c / a * RHS[0]);
	new_val[0] = (RHS[0] - b * new_val[1]) / a;

	if (is_dynamic())
	{
		double err = delta(RHS, new_val);
		store(RHS, new_val);
		if (err > m_params.m_accuracy * m_params.m_accuracy)
			return 2;
		else
			return 1;
	}
	store(NULL, new_val);
	return 1;
}

// ----------------------------------------------------------------------------------------
// netlist_matrix_solver - Gauss - Seidel
// ----------------------------------------------------------------------------------------

template <int m_N, int _storage_N>
ATTR_HOT int netlist_matrix_solver_gauss_seidel_t<m_N, _storage_N>::solve_non_dynamic()
{
	bool resched = false;

	int  resched_cnt = 0;
	ATTR_UNUSED netlist_net_t *last_resched_net = NULL;

	/* over-relaxation not really works on these matrices */
	//const double w = 1.0; //2.0 / (1.0 + sin(3.14159 / (m_nets.count()+1)));
	//const double w1 = 1.0 - w;

	double w[_storage_N];
	double one_m_w[_storage_N];
	double RHS[_storage_N];

	for (int k = 0; k < this->N(); k++)
	{
		double gtot_t = 0.0;
		double gabs_t = 0.0;
		double RHS_t = 0.0;

		netlist_net_t *net = this->m_nets[k];
		const netlist_net_t::terminal_list_t &terms = net->m_terms;
		const netlist_net_t::terminal_list_t &rails = net->m_rails;
		const int term_count = terms.count();
		const int rail_count = rails.count();

		for (int i = 0; i < rail_count; i++)
		{
			gtot_t += rails[i]->m_gt;
			gabs_t += fabs(rails[i]->m_go);
			RHS_t += rails[i]->m_Idr;
			RHS_t += rails[i]->m_go * rails[i]->m_otherterm->net().Q_Analog();
		}

		for (int i = 0; i < term_count; i++)
		{
			gtot_t += terms[i]->m_gt;
			gabs_t += fabs(terms[i]->m_go);
			RHS_t += terms[i]->m_Idr;
		}

		gabs_t *= this->m_params.m_convergence_factor;
		if (gabs_t > gtot_t)
		{
			// Actually 1.0 / g_tot  * g_tot / (gtot_t + gabs_t)
			w[k] = 1.0 / (gtot_t + gabs_t);
			one_m_w[k] = gabs_t / (gtot_t + gabs_t);
		}
		else
		{
			w[k] = 1.0 / gtot_t;
			one_m_w[k] = 1.0 - 1.0;
		}

		RHS[k] = RHS_t;
	}
    for (int k = 0; k < this->N(); k++)
        this->m_nets[k]->m_new_Analog = this->m_nets[k]->m_cur_Analog;

	do {
		resched = false;
		double cerr = 0.0;

		for (int k = 0; k < this->N(); k++)
		{
			netlist_net_t *net = this->m_nets[k];
			const netlist_net_t::terminal_list_t &terms = net->m_terms;
			const int term_count = terms.count();

			double iIdr = RHS[k];

			for (int i = 0; i < term_count; i++)
			{
                iIdr += terms[i]->m_go * terms[i]->m_otherterm->net().m_new_Analog;
			}

			//double new_val = (net->m_cur_Analog * gabs[k] + iIdr) / (gtot[k]);
			double new_val = net->m_new_Analog * one_m_w[k] + iIdr * w[k];

			double e = (new_val - net->m_new_Analog);
			cerr += e * e;

			net->m_new_Analog = new_val;
		}
		if (cerr > this->m_params.m_accuracy * this->m_params.m_accuracy)
		{
			resched = true;
		}
		resched_cnt++;
	} while (resched && (resched_cnt < this->m_params.m_gs_loops));

	if (resched)
	{
	    //this->netlist().warning("Falling back to direct solver .. Consider increasing RESCHED_LOOPS");
	    return netlist_matrix_solver_direct_t<m_N, _storage_N>::solve_non_dynamic();
	}

    for (int k = 0; k < this->N(); k++)
        this->m_nets[k]->m_cur_Analog = this->m_nets[k]->m_new_Analog;

	return resched_cnt;
}

// ----------------------------------------------------------------------------------------
// solver
// ----------------------------------------------------------------------------------------

typedef netlist_net_t::list_t  *net_groups_t;

ATTR_COLD static bool already_processed(net_groups_t groups, int &cur_group, netlist_net_t *net)
{
	if (net->isRailNet())
		return true;
	for (int i = 0; i <= cur_group; i++)
	{
		if (groups[i].contains(net))
			return true;
	}
	return false;
}

ATTR_COLD static void process_net(net_groups_t groups, int &cur_group, netlist_net_t *net)
{
	if (net->m_core_terms.is_empty())
		return;
	/* add the net */
	SOLVER_VERBOSE_OUT(("add %d - %s\n", cur_group, net->name().cstr()));
	groups[cur_group].add(net);
	for (int i = 0; i < net->m_core_terms.count(); i++)
	{
	    netlist_core_terminal_t *p = net->m_core_terms[i];
	    SOLVER_VERBOSE_OUT(("terminal %s\n", p->name().cstr()));
		if (p->isType(netlist_terminal_t::TERMINAL))
		{
			SOLVER_VERBOSE_OUT(("isterminal\n"));
			netlist_terminal_t *pt = static_cast<netlist_terminal_t *>(p);
			netlist_net_t *other_net = &pt->m_otherterm->net();
			if (!already_processed(groups, cur_group, other_net))
				process_net(groups, cur_group, other_net);
		}
	}
}


NETLIB_START(solver)
{
	register_output("Q_step", m_Q_step);

    register_param("SYNC_DELAY", m_sync_delay, NLTIME_FROM_NS(10).as_double());

	register_param("FREQ", m_freq, 48000.0);
	m_inc = netlist_time::from_hz(m_freq.Value());

	register_param("ACCURACY", m_accuracy, 1e-7);
	register_param("CONVERG", m_convergence, 0.3);
	register_param("GS_LOOPS", m_gs_loops, 7);      // Gauss-Seidel loops
    register_param("NR_LOOPS", m_nr_loops, 25);      // Newton-Raphson loops
	register_param("PARALLEL", m_parallel, 0);
	register_param("GMIN", m_gmin, NETLIST_GMIN_DEFAULT);

	// internal staff

	register_input("FB_step", m_fb_step);
	connect(m_fb_step, m_Q_step);

}

NETLIB_RESET(solver)
{
	for (int i = 0; i < m_mat_solvers.count(); i++)
		m_mat_solvers[i]->reset();
}


NETLIB_UPDATE_PARAM(solver)
{
	m_inc = netlist_time::from_hz(m_freq.Value());
}

NETLIB_NAME(solver)::~NETLIB_NAME(solver)()
{
	netlist_matrix_solver_t * const *e = m_mat_solvers.first();
	while (e != NULL)
	{
		netlist_matrix_solver_t * const *en = m_mat_solvers.next(e);
		delete *e;
		e = en;
	}

}

NETLIB_UPDATE(solver)
{
	int t_cnt = m_mat_solvers.count();

#if HAS_OPENMP && USE_OPENMP
	if (m_parallel.Value())
	{
		omp_set_num_threads(4);
		omp_set_dynamic(0);
		#pragma omp parallel
		{
			#pragma omp for nowait
			for (int i = 0; i <  t_cnt; i++)
			{
				this_resched[i] = m_mat_solvers[i]->solve();
			}
		}
	}
	else
		for (int i = 0; i < t_cnt; i++)
		{
			if (do_full || (m_mat_solvers[i]->is_timestep()))
				this_resched[i] = m_mat_solvers[i]->solve();
		}
#else
    for (int i = 0; i < t_cnt; i++)
    {
        if (m_mat_solvers[i]->is_timestep())
            if (m_mat_solvers[i]->solve())
                m_mat_solvers[i]->update_inputs();
    }
#endif

    /* step circuit */
    if (!m_Q_step.net().is_queued())
        m_Q_step.net().push_to_queue(m_inc);
}

ATTR_COLD void NETLIB_NAME(solver)::solve_all()
{
    for (int i = 0; i < m_mat_solvers.count(); i++)
        //m_mat_solvers[i]->m_Q_sync.net().push_to_queue(m_mat_solvers[i]->m_params.m_nt_sync_delay);
        if (m_mat_solvers[i]->solve())
            m_mat_solvers[i]->update_inputs();
}


ATTR_COLD void NETLIB_NAME(solver)::post_start()
{
	netlist_net_t::list_t groups[100];
	int cur_group = -1;

	SOLVER_VERBOSE_OUT(("Scanning net groups ...\n"));
	// determine net groups
	for (netlist_net_t * const *pn = netlist().m_nets.first(); pn != NULL; pn = netlist().m_nets.next(pn))
	{
		NL_VERBOSE_OUT(("proc %s\n", (*pn)->name().cstr()));
		if (!already_processed(groups, cur_group, *pn))
		{
			cur_group++;
			process_net(groups, cur_group, *pn);
		}
	}

	// setup the solvers
	SOLVER_VERBOSE_OUT(("Found %d net groups in %d nets\n", cur_group + 1, netlist().m_nets.count()));
	for (int i = 0; i <= cur_group; i++)
	{
		netlist_matrix_solver_t *ms;
		int net_count = groups[i].count();

		switch (net_count)
		{
			case 1:
				ms = new netlist_matrix_solver_direct1_t();
				break;
			case 2:
				ms = new netlist_matrix_solver_direct2_t();
				break;
			case 3:
				ms = new netlist_matrix_solver_direct_t<3,3>();
				//ms = new netlist_matrix_solver_gauss_seidel_t<3,3>();
				break;
			case 4:
				ms = new netlist_matrix_solver_direct_t<4,4>();
				//ms = new netlist_matrix_solver_gauss_seidel_t<4,4>();
				break;
#if 0
			case 5:
				//ms = new netlist_matrix_solver_direct_t<5,5>();
				ms = new netlist_matrix_solver_gauss_seidel_t<5,5>();
				break;
			case 6:
				//ms = new netlist_matrix_solver_direct_t<6,6>();
				ms = new netlist_matrix_solver_gauss_seidel_t<6,6>();
				break;
#endif
			default:
				if (net_count <= 16)
				{
					//ms = new netlist_matrix_solver_direct_t<0,16>();
					ms = new netlist_matrix_solver_gauss_seidel_t<0,16>();
				}
				else if (net_count <= 32)
				{
					//ms = new netlist_matrix_solver_direct_t<0,16>();
					ms = new netlist_matrix_solver_gauss_seidel_t<0,32>();
				}
				else if (net_count <= 64)
				{
					//ms = new netlist_matrix_solver_direct_t<0,16>();
					ms = new netlist_matrix_solver_gauss_seidel_t<0,64>();
				}
				else
				{
					netlist().error("Encountered netgroup with > 64 nets");
					ms = NULL; /* tease compilers */
				}

				break;
		}

		ms->m_params.m_accuracy = m_accuracy.Value();
		ms->m_params.m_convergence_factor = m_convergence.Value();
		ms->m_params.m_gs_loops = m_gs_loops.Value();
        ms->m_params.m_nr_loops = m_nr_loops.Value();
		ms->m_params.m_nt_sync_delay = m_sync_delay.Value();


        register_sub(*ms, pstring::sprintf("Solver %d",m_mat_solvers.count()));

        ms->setup(groups[i], *this);

        m_mat_solvers.add(ms);

        netlist().log("Solver %s", ms->name().cstr());
        netlist().log("       # %d ==> %d nets %s", i, groups[i].count(), (*(*groups[i].first())->m_core_terms.first())->name().cstr());
		netlist().log("       has %s elements", ms->is_dynamic() ? "dynamic" : "no dynamic");
		netlist().log("       has %s elements", ms->is_timestep() ? "timestep" : "no timestep");
		for (int j=0; j<groups[i].count(); j++)
		{
		    netlist().log("Net %d: %s", j, groups[i][j]->name().cstr());
			netlist_net_t *n = groups[i][j];
			for (int k = 0; k < n->m_core_terms.count(); k++)
			{
			    const netlist_core_terminal_t *p = n->m_core_terms[k];
			    netlist().log("   %s", p->name().cstr());
			}
		}
	}

}