-
Notifications
You must be signed in to change notification settings - Fork 1
/
tubefit.c
2058 lines (1564 loc) · 57.1 KB
/
tubefit.c
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
/* $Id: tubefit.c,v 1.25 2005/05/31 07:16:57 afrolov Exp $ */
/*
* Curve Captor - vacuum tube curve capture and model builder tool
* Numerical backend - data fitting and approximation routines.
*
* Copyright (C) 2001-2005 Andrei Frolov <[email protected]>
* Distributed under the terms of GNU Public License.
*
*/
#define SELF "tubefit"
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdarg.h>
#include <math.h>
#define WAVE_PTS 64
/******************* Options and defaults *****************************/
/* Usage */
char *usage_msg[] = {
"Vacuum tube model builder, Version " VERSION,
"Author: Andrei Frolov <[email protected]>",
"",
"Usage: " SELF " -[2|3|4|5] [...] < curve.dat",
"",
" General options:",
" -h print this message",
" -v verbosity (cumulative)",
"",
" Operation parameters:",
" -[2|3|4|5] valve type (2=diode, 3=triode, etc)",
" -P Pa rated anode dissipation power",
" -L Vp,Ip[,R] loadline: working point and load resistance",
" -[I|O|W] V specify input/output AC signal amplitude or power",
"",
" Model fit options:",
" -C flags apply cuts to tube data to fit specific requirements",
" (g = negative grid; p = rated power; l = loadline)",
" -M model use user-supplied model instead of finding best fitting one",
"",
" I/O functions:",
" -f format specify format for tagged input data",
" -d dump data in plain format for later use",
" -m [GUI] list available models and their fits",
" -p circuit [GUI] produce plate curves plot (SE or composite)",
" (SE = single ended; CF = cathode follower; PP = push-pull)",
" -w [GUI] do waveform analysis",
NULL
};
/* Options */
static int verbose = 0;
static int vtype = 3;
static double Pa = 0.0;
static double V0 = 0.0;
static double I0 = 0.0;
static double RL = 0.0;
static double Vin = 0.0;
static double Vout = 0.0;
static double Wout = 0.0;
static char *format = NULL;
static int output_only = 0;
static int list_models = 0;
static int plot_curves = 0;
static int waveform = 0;
static int grid_cut = 0;
static int power_cut = 0;
static int loadline_cut = 0;
static char *user_model = NULL;
/**********************************************************************/
/*
* Numerical and utility functions:
* error handlers, vectors and matrices, other misc stuff.
*
*/
#ifndef TINY /* machine precision */
#define TINY 2.2204460492503131e-16
#endif /* TINY */
#ifndef HUGE /* largest number */
#define HUGE 1.7976931348623158e308
#endif /* HUGE */
/******************* Basic error handlers *****************************/
void usage()
{
int i = 0; char *s;
while ((s = usage_msg[i++]))
fprintf(stderr, "%s\n", s);
exit(1);
}
void warning(char *fmt, ...)
{
va_list args;
fprintf(stderr,"%s: ", SELF);
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
fprintf(stderr, "\n");
}
void error(char *fmt, ...)
{
va_list args;
fprintf(stderr, "%s: ", SELF);
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
fprintf(stderr, "\n");
exit(-1);
}
void fatal(char *msg)
{
error("Fatal error: %s\nTerminating process...", msg);
}
/******************* Foo or die routines ******************************/
/* allocate memory or die */
void *xmalloc(size_t size)
{
register void *p = malloc(size);
if (!p) fatal("virtual memory exhausted in malloc()");
return p;
}
/* reallocate memory or die */
void *xrealloc(void *addr, size_t size)
{
register void *p = realloc(addr, size);
if (!p) fatal("virtual memory exhausted in realloc()");
return p;
}
/* duplicate string or die */
char *xstrdup(const char *s)
{
register char *p = strdup(s);
if (!p) fatal("virtual memory exhausted in strdup()");
return p;
}
/******************* Vectors and matrices *****************************/
/* allocate a vector with subscript range v[0..n] */
double *vector(unsigned long n)
{
register double *v = (double *)xmalloc((size_t)(n*sizeof(double)));
return v;
}
/* grow a vector to subscript range v[0..n] */
double *grow_vector(double *v, unsigned long n)
{
v = (double *)xrealloc(v, (size_t)(n*sizeof(double)));
return v;
}
/* allocate an int vector with subscript range v[0..n] */
int *ivector(unsigned long n)
{
register int *v = (int *)xmalloc((size_t)(n*sizeof(int)));
return v;
}
/* grow an int vector to subscript range v[0..n] */
int *grow_ivector(int *v, unsigned long n)
{
v = (int *)xrealloc(v, (size_t)(n*sizeof(int)));
return v;
}
/* allocate an unsigned long vector with subscript range v[0..n] */
unsigned long *uvector(unsigned long n)
{
register unsigned long *v = (unsigned long *)xmalloc((size_t)(n*sizeof(unsigned long)));
return v;
}
/* grow an unsigned long vector to subscript range v[0..n] */
unsigned long *grow_uvector(unsigned long *v, unsigned long n)
{
v = (unsigned long *)xrealloc(v, (size_t)(n*sizeof(unsigned long)));
return v;
}
/* free a vector allocated with vector() */
void free_vector(void *v)
{
free((void *)(v));
}
/* allocate a matrix with subscript range m[0..nr][0..nc] */
double **matrix(unsigned long nr, unsigned long nc)
{
register unsigned long i;
register double **m = (double **)xmalloc((size_t)(nr*sizeof(double *)+sizeof(unsigned long)));
*(((unsigned long *)(m))++) = nr;
for (i = 0; i < nr; i++) m[i] = vector(nc);
return m;
}
/* grow a matrix to subscript range m[0..nr][0..nc] */
double **grow_matrix(double **m, unsigned long nr, unsigned long nc)
{
register unsigned long i;
unsigned long old_nr = *(--((unsigned long *)(m)));
/* Reallocate row index if necessary */
if (nr != old_nr)
m = (double **)xrealloc(m, (size_t)(nr*sizeof(double *)+sizeof(unsigned long)));
*(((unsigned long *)(m))++) = nr;
/* Reallocate rows */
for (i = 0; i < old_nr; i++) m[i] = grow_vector(m[i], nc);
for (i = old_nr; i < nr; i++) m[i] = vector(nc);
return m;
}
/* free a matrix allocated by matrix() */
void free_matrix(double **m)
{
register unsigned long i;
unsigned long nr = *((unsigned long *)(m)-1);
for (i = 0; i < nr; i++) free_vector(m[i]);
free((void *)((unsigned long *)(m)-1));
}
/******************* getline() replacement ****************************/
/*
* getline.c -- Replacement for GNU C library function getline
*
* Copyright (C) 1993 Free Software Foundation, Inc.
* Distributed under the terms of GNU Public License.
*
* Written by Jan Brittenson <[email protected]>
* Modified by Andrei Frolov <[email protected]>
*
*/
#if !defined(HAVE_GETLINE)
#include <sys/types.h>
#include <assert.h>
#include <errno.h>
/* Always add at least this many bytes when extending the buffer. */
#define MIN_CHUNK 64
/* Read up to (and including) a TERMINATOR from STREAM into *LINEPTR
(and null-terminate it). *LINEPTR is a pointer returned from malloc
(or NULL), pointing to *N characters of space. It is realloc'd as
necessary. Return the number of characters read (not including the
null terminator), or -1 on error or EOF. On a -1 return, the caller
should check feof(), if not then errno has been set to indicate the
error. */
ssize_t getdelim(char **lineptr, size_t *n, int delimiter, FILE *stream)
{
int nchars_avail; /* Allocated but unused chars in *LINEPTR. */
char *read_pos; /* Where we're reading into *LINEPTR. */
if (!lineptr || !n || !stream) { errno = EINVAL; return -1; }
if (!*lineptr) {
*n = MIN_CHUNK; *lineptr = (char *)malloc(*n);
if (!*lineptr) { errno = ENOMEM; return -1; }
}
nchars_avail = *n; read_pos = *lineptr;
for (;;) {
register int c = getc(stream); int save_errno = errno;
/* We always want at least one char left in the buffer,
since we always (unless we get an error while reading
the first char) NULL-terminate the line buffer. */
assert((*lineptr + *n) == (read_pos + nchars_avail));
if (nchars_avail < 2) {
if (*n > MIN_CHUNK) *n <<= 1; else *n += MIN_CHUNK;
nchars_avail = *n + *lineptr - read_pos;
*lineptr = (char *)realloc(*lineptr, *n);
if (!*lineptr) { errno = ENOMEM; return -1; }
read_pos = *n - nchars_avail + *lineptr;
assert((*lineptr + *n) == (read_pos + nchars_avail));
}
/* Might like to return partial line, but there is no place for
us to store errno. And we don't want to just lose errno. */
if (ferror(stream)) { errno = save_errno; return -1; }
/* Return partial line, if any. */
if (c == EOF) { if (read_pos == *lineptr) return -1; else break; }
*read_pos++ = c;
nchars_avail--;
/* Return the line. */
if (c == delimiter) break;
}
/* Done - NULL terminate and return the number of chars read. */
*read_pos = '\0';
return read_pos - *lineptr;
}
ssize_t getline (char **lineptr, size_t *n, FILE *stream)
{
return getdelim(lineptr, n, '\n', stream);
}
#endif /* !HAVE_GETLINE */ /* end of getline() replacement */
/**********************************************************************/
/*
* Non-linear model fitting:
* chi^2 optimization via simulated annealing
*
* Tube models:
* - Diode: Child-Langmuir, Perugini
* - Triode: Child-Langmuir, Rydel, Koren
*
*/
/******************* Multidimensional minimization ********************/
/* directional minimization along a vector xi in n dimensions */
double vmin(double p[], double xi[], int n, double (*f)(double []), double eps)
{
double a, b, c, u, v, w, x, fa, fb, fc, fu, fv, fw, fx;
double q, r, s, t, tol, e = 0.0, d = 0.0;
int i, maxiter = 84; // maximal number of iterations
#define GOLD 1.61803398874989484820458683436563811772030918
#define CGOLD 0.38196601125010515179541316563436188227969082
#define EVAL(X,F) { double t[n]; for (i = 0; i < n; i++) t[i] = p[i] + (X)*xi[i]; (F) = (*f)(t); }
#define SWAP(A,B) { double T = (A); (A) = (B); (B) = T; }
#define SIGN(A,B) ((B) >= 0.0 ? fabs(A) : -fabs(A))
/* initial bracketing of a minimum */
a = 0.0; b = 1.0; EVAL(a,fa); EVAL(b,fb);
if (fb > fa) { SWAP(a,b); SWAP(fa,fb); }
c = b + GOLD*(b-a); EVAL(c,fc);
while (fb > fc) {
a = b; b = c; fa = fb; fb = fc;
c = b + GOLD*(b-a); EVAL(c,fc);
}
/* Brent's minimization */
x = w = v = b; fx = fw = fv = fb; if (a > c) SWAP(a,c);
while (maxiter--) {
b = (a+c)/2.0; tol = eps * sqrt(1.0 + x*x);
if (fabs(x-b) <= (2.0*tol - (c-a)/2.0)) break;
if (fabs(e) > tol) {
r = (x-w)*(fx-fv);
q = (x-v)*(fx-fw);
s = (x-v)*q-(x-w)*r;
q = 2.0*(q-r); if (q > 0.0) s = -s; else q = -q;
t = e; e = d;
if (fabs(s) >= fabs(0.5*q*t) || s <= q*(a-x) || s >= q*(c-x)) {
e = (x >= b ? a-x : c-x); d = CGOLD * e;
} else {
d = s/q; u = x+d; if (u-a < 2.0*tol || c-u < 2.0*tol) d = SIGN(tol,b-x);
}
} else { e = (x >= b ? a-x : c-x); d = CGOLD * e; }
u = (fabs(d) >= tol ? x+d : x+SIGN(tol,d)); EVAL(u,fu);
if (fu <= fx) {
if (u >= x) a = x; else c = x;
v = w; w = x; x = u;
fv = fw; fw = fx; fx = fu;
} else {
if (u < x) a = u; else c = u;
if (fu <= fw || w == x) { v = w; w = u; fv = fw; fw = fu; }
else if (fu <= fv || v == x || v == w) { v = u; fv = fu; }
}
}
/* update direction vectors */
if (x != 0.0) for (i = 0; i < n; i++) { xi[i] *= x; p[i] = p[i] + xi[i]; }
return fx;
}
/* n-dimensional minimization (using Powell's method) */
double mmin(double p[], double **e, int n, double (*f)(double []), double eps)
{
int i, j, s; double fp, fo, fx, sd, t; double po[n], px[n], xi[n];
int maxiter = 1000; // maximal number of iterations
if (n == 1) { xi[0] = e[0][0]; return vmin(p, xi, n, f, eps); }
fp = (*f)(p);
while (maxiter--) {
for (j = 0; j < n; j++) po[j] = p[j]; fo = fp; s = 0; sd = 0.0;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) xi[j] = e[j][i];
t = fp; fp = vmin(p, xi, n, f, eps);
if (fabs(fp-t) > sd) { sd = fabs(fp-t); s = i; }
}
if (2.0*fabs(fo-fp) <= eps*eps*(fabs(fo)+fabs(fp))) return fp;
for (j = 0; j < n; j++) { px[j] = 2.0*p[j]-po[j]; xi[j] = p[j]-po[j]; }
fx = (*f)(px);
if (fx < fo && 2.0*(fo-2.0*fp+fx)*(fo-fp-sd)*(fo-fp-sd) < sd*(fo-fx)*(fo-fx)) {
fp = vmin(p, xi, n, f, eps);
for (j = 0; j < n; j++) {
for (i = s; i < n-1; i++) e[j][i] = e[j][i+1]; e[j][n-1] = xi[j];
}
}
}
return fp;
}
/******************* Vacuum tube models *******************************/
/* A way to refer to previous model's parameters */
#define PRIOR_MAGIC 0x00505259
#define PRMREF(m,k) ((((PRIOR_MAGIC<<4) + (m))<<4) + k)
#define PRIOR(k) PRMREF(1,k)
#define MAGIC(v) (((int)(v) >> 8) == PRIOR_MAGIC)
#define ppow(x,g) ((x > 0.0) ? pow(x, g) : 0.0)
/* Vacuum diode; Child-Langmuir law */
static double diode(double p[], double V[])
{
double I, Vp = V[0];
double K = p[0];
I = K * ppow(Vp, 1.5);
return I;
}
/* Vacuum diode; Child-Langmuir law with contact potential */
static double init_diode_cp[] = {PRIOR(0), 0.0};
static double diode_cp(double p[], double V[])
{
double I, Vp = V[0];
double K = p[0], Vc = p[1];
I = K * ppow(Vp+Vc, 1.5);
return I;
}
/* Vacuum triode; Child-Langmuir law */
static double triode(double p[], double V[])
{
double I, Vp = V[0], Vg = V[1];
double K = p[0], mu = p[1];
I = K * ppow(mu*Vg + Vp, 1.5);
return I;
}
/* Vacuum triode; Child-Langmuir law with contact potential */
static double init_triode_cp[] = {PRIOR(0), PRIOR(1), 0.0};
static double triode_cp(double p[], double V[])
{
double I, Vp = V[0], Vg = V[1];
double K = p[0], mu = p[1], Vc = p[2];
I = K * ppow(mu*Vg + Vp + Vc, 1.5);
return I;
}
/* Vacuum triode; Rydel model (4 parameters) */
static double init_rydel4[] = {PRIOR(0), 0.0, PRIOR(1), PRIOR(2)};
static double triode_rydel4(double p[], double V[])
{
double I, Vp = V[0], Vg = V[1];
double Ka = p[0], Kb = p[1], mu = p[2], Vc = p[3];
I = (Ka + Kb*Vg) * ppow(mu*Vg + Vp + Vc, 1.5);
return I;
}
/* Vacuum triode; Rydel model (5 parameters) */
static double init_rydel5[] = {PRIOR(0), PRIOR(1), PRIOR(2), PRIOR(3), 0.0};
static double triode_rydel5(double p[], double V[])
{
double I, Vp = V[0], Vg = V[1];
double Ka = p[0], Kb = p[1], mu = p[2], Vc = p[3], C = p[4];
I = (Ka + Kb*Vg) * ppow(mu*Vg + Vp + Vc, 1.5) * Vp/(Vp+C);
return I;
}
/* Vacuum triode; Koren model (4 parameters) */
static double init_koren4[] = {PRMREF(4,0), 5.0, PRMREF(4,1), 1.5};
static double triode_koren4(double p[], double V[])
{
double I, U, Vp = V[0], Vg = V[1];
double K = p[0], Kp = p[1], mu = p[2], gamma = p[3];
U = Vp * log(1.0 + exp(Kp + Kp*mu*Vg/Vp))/Kp;
I = K * ppow(U, gamma);
return I;
}
/* Vacuum triode; Koren model (5 parameters) */
static double init_koren5[] = {PRIOR(0), PRIOR(1), PRIOR(2), 0.0, PRIOR(3)};
static double triode_koren5(double p[], double V[])
{
double I, U, Vp = V[0], Vg = V[1];
double K = p[0], Kp = p[1], mu = p[2], Kv = p[3], gamma = p[4];
U = Vp * log(1.0 + exp(Kp + Kp*mu*Vg/sqrt(1000.0*Kv + Vp*Vp)))/Kp;
I = K * ppow(U, gamma);
return I;
}
/* Vacuum triode; modified Koren model (6 parameters) */
static double init_koren6[] = {PRMREF(2,0), 0.0, PRMREF(2,1), PRMREF(2,2), 0.0, PRMREF(2,3)};
static double triode_koren6(double p[], double V[])
{
double I, U, Vp = V[0], Vg = V[1];
double K = p[0], Kc = p[1], Kp = p[2], mu = p[3], nu = p[4], gamma = p[5];
U = Vp * log(1.0 + Kc + exp(Kp + Kp*(mu+nu*Vg/1000.0)*Vg/Vp))/Kp;
I = K * ppow(U, gamma);
return I;
}
/* Vacuum triode; modified Koren model (8 parameters) */
static double init_koren8[] = {PRIOR(0), PRIOR(1), PRIOR(2), PRIOR(3), PRIOR(4), 0.0, 0.0, PRIOR(5)};
static double triode_koren8(double p[], double V[])
{
double I, U, Vp = V[0], Vg = V[1];
double K = p[0], Kc = p[1], Kp = p[2], mu = p[3], nu = p[4], Kv = p[5], Vc = p[6], gamma = p[7];
U = Vp * log(1.0 + Kc + exp(Kp + Kp*(mu+nu*Vg/1000.0)*Vg/sqrt(Kv*Kv+(Vp-Vc)*(Vp-Vc))))/Kp;
I = K * ppow(U, gamma);
return I;
}
/******************* Vacuum tube model index **************************/
/* Tube model structure */
typedef struct {
int vtype; /* 2=diode, 3=triode, etc */
char *name; /* Long model name */
char *macro; /* Macro implementing Spice model */
int params; /* # of model parameters to fit */
double (*curve)(double p[], double V[]);
double *p; /* Parameter values: initial guess/model fit */
} model;
/* Tube model index */
model mindex[] = {
/* Vacuum diode models */
{2, "Child-Langmuir law", "diode", 1, diode},
{2, "Child-Langmuir law with contact potential", "diode_cp", 2, diode_cp, init_diode_cp},
/* Vacuum triode models */
{3, "Child-Langmuir law", "triode", 2, triode},
{3, "Child-Langmuir law with contact potential", "triode_cp", 3, triode_cp, init_triode_cp},
{3, "Rydel model (4 parameters)", "rydel4", 4, triode_rydel4, init_rydel4},
{3, "Rydel model (5 parameters)", "rydel5", 5, triode_rydel5, init_rydel5},
{3, "Koren model (4 parameters)", "koren4", 4, triode_koren4, init_koren4},
{3, "Koren model (5 parameters)", "koren5", 5, triode_koren5, init_koren5},
{3, "Modified Koren model (6 parameters)", "koren6", 6, triode_koren6, init_koren6},
{3, "Modified Koren model (8 parameters)", "koren8", 8, triode_koren8, init_koren8},
};
/******************* Vacuum tube model fit ****************************/
/* Curve data is passed as global variable */
static int _pts_;
static double **_data_;
static double *_weight_;
static model *_model_;
/* Minimization criterion is weighted least square */
static double chi2(double p[])
{
int i, n = _pts_;
double t, s = 0.0, norm = 0.0;
for (i = 0; i < n; i++) {
double w = _weight_[i];
double I = _data_[3][i];
double V[] = {_data_[0][i], _data_[1][i], _data_[2][i]};
t = I - (*(_model_->curve))(p, V); s += w*t*t; norm += w;
}
return s/norm;
}
/* Initialize global fit context */
void init_fit_context(model *m, double **data, int n)
{
int i;
double *w = vector(n);
/* point weights */
for (i = 0; i < n; i++) {
w[i] = 1.0;
if (grid_cut) {
double V = data[1][i];
if (V > 0.0) w[i] = 0.0;
}
if (power_cut) {
double V = data[0][i], I = data[3][i];
double P = V*I/1000.0;
w[i] *= (1.0 - tanh(16.0 * (P - 1.1*Pa)/Pa))/2.0;
}
if (loadline_cut) {
double V = data[0][i], I = data[3][i];
double G = (RL != 0.0) ? 1000.0/RL : 0.0;
double dI = (I-I0) + G * (V-V0);
w[i] *= exp(-16.0 * dI*dI/(I0*I0));
}
}
_pts_ = n;
_data_ = data;
_weight_ = w;
_model_ = m;
}
/* Fit parametric curve model to the data using simulated annealing */
double *fit_curve(model *m, double **data, int n)
{
int i, j, k, D = m->params;
double *p = vector(D+1), **e = matrix(D,D);
init_fit_context(m, data, n);
/* initialize parameter vector */
for (i = 0; i < D; i++) {
if (!m->p) { p[i] = 0.0; continue; }
if (!MAGIC(m->p[i])) { p[i] = m->p[i]; continue; }
j = ((int)(m->p[i]) & 0xF0) >> 4;
k = (int)(m->p[i]) & 0x0F;
p[i] = (m-j)->p[k];
}
/* initialize direction set to try new directions first */
for (i = 0; i < D; i++) for (j = 0; j < D; j++) e[i][j] = 0.0; j = 0;
for (i = 0; i < D; i++) if (!m->p || !MAGIC(m->p[i])) e[i][j++] = 1.0;
for (i = 0; i < D; i++) if ( m->p && MAGIC(m->p[i])) e[i][j++] = 1.0;
/* optimize */
p[D] = mmin(p, e, D, chi2, 1.0e-6); m->p = p;
free_vector(_weight_);
free_matrix(e);
return p;
}
/* Try all appropriate models and return the best one */
model *best_model(FILE *fp, double **data, int n)
{
double *p, min = HUGE;
int i, j, k, best = 0, invoke = 0;
for (i = 0, k = 0; i < sizeof(mindex)/sizeof(model); i++) {
model *m = &(mindex[i]);
int D = m->params;
if (m->vtype != vtype) continue;
else p = fit_curve(m, data, n);
if (p[D] == HUGE) continue;
if (p[D] < min) { min = p[D]; best = i; invoke = k; }
if (verbose) {
fprintf(stderr, "* %s: mean fit error %g mA\n", m->name, sqrt(p[D]));
fprintf(stderr, "* %s(", m->macro);
for (j = 0; j < D; j++)
fprintf(stderr, "%.10g%s", p[j], ((j < D-1) ? "," : ""));
fprintf(stderr, ")\n"); fflush(stderr);
}
if (fp) {
fprintf(fp, "add command -label \"%s \\[mean fit error %g mA\\]\"", m->name, sqrt(p[D]));
fprintf(fp, " -command { set macro \"%s\"; set mparams \"", m->macro);
for (j = 0; j < D; j++)
fprintf(fp, "%.10g%s", p[j], ((j < D-1) ? "," : ""));
fprintf(fp, "\" }\n");
}
k++;
}
if (fp) fprintf(fp, "invoke %i\n", invoke);
return &(mindex[best]);
}
/* Read model specification from a string */
model *read_model(const char *s, double **data, int n)
{
int i, j, idx;
char *macro = xstrdup(s), *p = strchr(macro, '('), *q;
if (!p) error("Invalid model specification '%s'", s); *(p++) = 0;
for (i = 0, idx = -1; i < sizeof(mindex)/sizeof(model); i++) {
model *m = &(mindex[i]);
int D = m->params;
if (strcmp(macro, m->macro)) continue; else idx = i;
m->p = vector(D+1);
for (j = 0; j < D; j++) {
m->p[j] = strtod(p, &q);
if ((p == q) || (*q && (*q != ')') && (*(q++) != ',')))
error("Error parsing model parameter '%s'", p);
p = q;
}
init_fit_context(m, data, n);
m->p[D] = chi2(m->p);
free_vector(_weight_);
break;
}
if (idx == -1) error("Model '%s' not found", macro);
return &(mindex[idx]);
}
/****************** Data I/O routines *********************************/
/* Linear regression: least square fit of a straight line y=ax+b*/
void linregr(double x[], double y[], int n, double *a, double *b)
{
int i;
double xa, ya, sx = 0.0, sy = 0.0, sxx = 0.0, sxy = 0.0;
for (i = 0; i < n; i++) {
sx += x[i]; sy += y[i];
}
xa = sx/n; ya = sy/n;
for (i = 0; i < n; i++) {
sxx += (x[i]-xa)*x[i];
sxy += (x[i]-xa)*y[i];
}
*a = sxy/sxx; *b = ya - (*a)*xa;
}
/* Get coordinate map for traced axis positions */
void axismap(double **X, int nx, double **Y, int ny, double A[2][2], double B[2])
{
double det, M[2][2], T[2][2];
linregr(X[0], X[1], nx, &(M[0][0]), &(T[0][0]));
linregr(X[0], X[2], nx, &(M[1][0]), &(T[1][0]));
linregr(Y[0], Y[1], ny, &(M[0][1]), &(T[0][1]));
linregr(Y[0], Y[2], ny, &(M[1][1]), &(T[1][1]));
det = M[0][0]*M[1][1]-M[0][1]*M[1][0];
A[0][0] = M[1][1]/det;
A[0][1] = -M[0][1]/det;
A[1][0] = -M[1][0]/det;
A[1][1] = M[0][0]/det;
if (fabs(M[0][0]) >= fabs(M[1][0])) B[0] = T[0][0]; else B[0] = T[0][1];
if (fabs(M[1][1]) >= fabs(M[0][1])) B[1] = T[1][1]; else B[1] = T[1][0];
}
/* Find parameter index in a template */
int pindex(const char *t, const char *p)
{
int i = 0;
char *q = strstr(t, p);
if (!q) return -1;
while (q-- > t) { if (*q == ' ') i++; }
return i;
}
/* Read curve data in tagged format (untranslated axis units) */
double **read_tagged_data(FILE *fp, const char *format, int *pts)
{
int i;
double A[2][2], B[2], **m;
char *tag[3] = {NULL, NULL, NULL};
int c[3], n[3] = {0, 0, 0}, size[3] = {32, 32, 128};
double **D[3] = {matrix(3, size[0]), matrix(3, size[1]), matrix(3, size[2])};
size_t bsize = 128;
char l[13]; double t[3];
char *buffer = (char *)xmalloc(bsize);
/* Read curve data */
while (getline(&buffer, &bsize, fp) != -1) {
if (*buffer == '#' || *buffer == '\n') continue;
if (*buffer == ';') break;
for (i = 0; i < 3; i++) if (n[i] >= size[i]) {
D[i] = grow_matrix(D[i], 3, size[i]<<=1);
}
t[0] = t[1] = t[2] = 0.0;
if (sscanf(buffer, " %12[^ =]=%lf %lf %lf", l, &(t[0]), &(t[1]), &(t[2])) < 4)
error("syntax error in curve data");
if ((i = pindex(format, l)) == -1) continue;
if (!tag[i]) tag[i] = xstrdup(l);
D[i][0][n[i]] = t[0];
D[i][1][n[i]] = t[1];
D[i][2][n[i]] = t[2];
n[i]++;
}
free(buffer);
/* Translate data */
*pts = n[2]; m = matrix(4, *pts);
axismap(D[0], n[0], D[1], n[1], A, B);
for (i = 0; i < 3; i++)
if ((c[i] = pindex("Vp Vg Vs Ip|Ig|Is", tag[i])) == -1)
error("Unknown curve parameter '%s'", tag[i]);
for (i = 0; i < *pts; i++) {
double x = D[2][1][i] - B[0], y = D[2][2][i] - B[1];
m[0][i] = m[1][i] = m[2][i] = m[3][i] = 0.0;
m[c[0]][i] = A[0][0]*x + A[0][1]*y;
m[c[1]][i] = A[1][0]*x + A[1][1]*y;
m[c[2]][i] = D[2][0][i];
}
free_matrix(D[0]);
free_matrix(D[1]);
free_matrix(D[2]);
return m;
}
/* Read curve data in plain format */
double **read_data(FILE *fp, int *pts)
{
int n = 0, size = 128;
double **m = matrix(4, size);
size_t bsize = 128;
char *buffer = (char *)xmalloc(bsize);
/* Read curve data */
while (getline(&buffer, &bsize, fp) != -1) {
if (*buffer == '#' || *buffer == '\n') continue;
if (*buffer == ';') break;
if (n >= size) { m = grow_matrix(m, 4, size<<=1); }
m[0][n] = m[1][n] = m[2][n] = m[3][n] = 0.0;
switch (vtype) {
case 2:
if (sscanf(buffer, " %lf %lf",
&(m[0][n]), &(m[3][n])) < 2)
error("missing parameters in diode data");
break;
case 3:
if (sscanf(buffer, " %lf %lf %lf",
&(m[1][n]), &(m[0][n]), &(m[3][n])) < 3)
error("missing parameters in triode data");
break;
case 4:
case 5:
if (sscanf(buffer, " %lf %lf %lf %lf",
&(m[2][n]), &(m[1][n]), &(m[0][n]), &(m[3][n])) < 4)
error("missing parameters in tetrode/pentode data");
break;
}
n++;
}
free(buffer);
*pts = n; return m;
}
/* Write curve data in plain format */
void write_data(FILE *fp, double **m, int n)
{
int i;