-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathstats.mod
2290 lines (2165 loc) · 74 KB
/
stats.mod
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: stats.mod,v 1.227 2012/09/07 14:25:41 samn Exp $
:* COMMENT
COMMENT
randwd randomly chooses n bits to set to 1
hamming v.hamming(v1) is hamming distance between 2 vecs
flipbits v.flipbits(scratch,num) flips num rand chosen bits
flipbalbits v.flipbalbits(scratch,num) balanced flipping
vpr v.vpr prints out vector as 1 (x[i]>0) or 0 (x[i]<=0)
fac not vec related - returns factorial
logfac not vec related - returns log factorial
vseed set some C level randomizer seeds
slope(num) does a linear regression to find the slope, assuming num=timestep of vector
vslope(v2) does a linear regression to find the slope, assuming num=timestep of vector
stats(num,[out]) does a linear regression, assuming num=timestep of vector
vstats(v2,[out]) does a linear regression, using v2 as the x-coords
setrnd(v,flag) does set rand using 1:rand, 2:drand48
v.hash(list) // make a hash out values in vecs in list
v.unnan([nan_value,][inf_value]) // remove nan's and inf's from a vector
ENDCOMMENT
NEURON {
SUFFIX stats
GLOBAL INSTALLED,seed,kmeasure,verbose,self_ok_combi,hretval,flag,transpose,newline
}
PARAMETER {
: BVBASE = 0. : defined in vecst.mod
INSTALLED=0
kmeasure=0
verbose=0
self_ok_combi=0
hretval=0
transpose=0
newline=90
flag=0 : flag can be used by any of the routines for different things
}
ASSIGNED { seed }
VERBATIM
#include "misc.h"
#include <stdint.h> /* uint32_t, uintptr_t */
#define MIN_MERGESORT_LIST_SIZE 32
union dblint {
int i[2];
double d;
};
static u_int32_t ilow=0;
static u_int32_t ihigh=0; // same as ihigh in (/usr/site/nrniv/nrn/src/ivoc/ivocrand.cpp:75)
static double *x1x, *y1y, *z1z;
static int compare_ul(const void* l1, const void* l2) {
int retval;
unsigned long d;
d = (*((const unsigned long*) l1)) - (*((const unsigned long*) l2));
if(d==0) return 1;
if(d < 0) return -1;
return 0;
}
ENDVERBATIM
:* v1.slope(num) does a linear regression to find the slope, assuming num=timestep of vector
VERBATIM
static double slope(void* vv) {
int i, n;
double *x, *y;
double timestep, sigxy, sigx, sigy, sigx2;
/* how to get the instance data */
n = vector_instance_px(vv, &y);
if(ifarg(1)) {
timestep = *getarg(1);
} else { printf("You must supply a timestep\n"); return 0; }
sigxy= sigx= sigy= sigx2=0; // initialize these
x = (double *) malloc(sizeof(double)*n);
for(i=0; i<n; i++) {
x[i] = timestep*i;
sigxy += x[i] * y[i];
sigx += x[i];
sigy += y[i];
sigx2 += x[i]*x[i];
}
free(x);
return (n*sigxy - sigx*sigy)/(n*sigx2 - sigx*sigx);
}
ENDVERBATIM
:* v1.moment(v2) stores moments:
VERBATIM
static double moment (void* vv) {
int i, j, n, fl;
double *mdata, *y;
double ave,adev,sdev,svar,skew,curt,s,p;
n = vector_instance_px(vv, &mdata);
fl=0;
if (n<=1) {printf("n must be at least 2 in stats:moment()"); hxe();}
if(ifarg(1)) {
if (hoc_is_object_arg(1)) {
y=vector_newsize(vector_arg(1), 6); fl=1;
} else {
printf("vec.moment(ovec) stores in ovec: ave,adev,sdev,svar,skew,kurt\n");
return 0;
}
}
for (j=0,s=0;j<n;j++) s+=mdata[j];
ave=s/n; adev=svar=skew=curt=0.0;
for (j=0;j<n;j++) { adev+=fabs(s=mdata[j]-ave); svar+=(p=s*s); skew+=(p*=s); curt+=(p*=s); }
adev/=n; svar/=(n-1); sdev=sqrt(svar);
if (svar) {
skew /= (n*svar*sdev);
curt= curt/(n*svar*svar)-3.0;
} else {printf("No skew/kurtosis when variance = 0 (in stats::moment())\n"); hxe();}
if (fl) {y[0]=ave; y[1]=adev; y[2]=sdev; y[3]=svar; y[4]=skew; y[5]=curt;}
return curt;
}
ENDVERBATIM
:* v1.vslope(v2) does a linear regression, using v2 as the x-coords
VERBATIM
static double vslope (void* vv) {
int i, n;
double *x, *y;
double timestep, sigxy, sigx, sigy, sigx2;
/* how to get the instance data */
n = vector_instance_px(vv, &y);
if(ifarg(1)) {
if(vector_arg_px(1, &x) != n ) {
hoc_execerror("Vector size doesn't match.", 0);
}
sigxy= sigx= sigy= sigx2=0; // initialize these
for(i=0; i<n; i++) {
sigxy += x[i] * y[i];
sigx += x[i];
sigy += y[i];
sigx2 += x[i]*x[i];
}
}
return (n*sigxy - sigx*sigy)/(n*sigx2 - sigx*sigx);
}
ENDVERBATIM
VERBATIM
//computes mean,max squared error of data points
//off a line model with m=slope , b=y_intercept
//x is independent variable
//y is dependent variable
//n is # of data points
//meansqerr is output
//maxsqerr is output
double getsqerr(double* x,double* y,double m,double b,int n,double* meansqerr,double* maxsqerr){
int i; double val;
if(!n){
return -1.0;
}
val=0.0;
*meansqerr=0.0;
*maxsqerr=0.0;
for(i=0;i<n;i++){
val = y[i] - (m*x[i]+b);
val = val*val;
if(val>*maxsqerr) *maxsqerr = val;
*meansqerr += val;
}
*meansqerr=*meansqerr/(double)n;
return *meansqerr;
}
ENDVERBATIM
:* v1.stats(num) does a linear regression, assuming num=timestep of vector
VERBATIM
static double stats(void* vv) {
int i, n;
double *x, *y, *out;
double timestep, sigxy, sigx, sigy, sigx2, sigy2;
double r, m, b, dmeansqerr,dmaxsqerr;
/* how to get the instance data */
n = vector_instance_px(vv, &y);
if(ifarg(1)) {
timestep = *getarg(1);
} else { printf("You must supply a timestep\n"); return 0; }
sigxy= sigx= sigy= sigx2=sigy2= 0; // initialize these
x = (double *) malloc(sizeof(double)*n);
for(i=0; i<n; i++) {
x[i] = timestep*i;
sigxy += x[i] * y[i];
sigx += x[i];
sigy += y[i];
sigx2 += x[i]*x[i];
sigy2 += y[i]*y[i];
}
m = (n*sigxy - sigx*sigy)/(n*sigx2 - sigx*sigx);
b = (sigy*sigx2 - sigx*sigxy)/(n*sigx2 - sigx*sigx);
r = (n*sigxy - sigx*sigy)/(sqrt(n*sigx2-sigx*sigx) * sqrt(n*sigy2-sigy*sigy));
getsqerr(x,y,m,b,n,&dmeansqerr,&dmaxsqerr); //mean,max squared error
if(ifarg(2)){ //save results to output
out=vector_newsize(vector_arg(2),5);
out[0]=m; out[1]=b; out[2]=r; out[3]=dmeansqerr; out[4]=dmaxsqerr;
} else {
printf("Examined %d data points\n", n);
printf("slope = %f\n", m);
printf("intercept = %f\n", b);
printf("R = %f\n", r);
printf("R-squared = %f\n", r*r);
printf("MeanSQErr = %f\n",dmeansqerr);
printf("MaxSQErr = %f\n",dmaxsqerr);
}
free(x);
return 1;
}
typedef struct pcorst_ {
int pidse[2];
double* X;
double* Y;
double sigx;
double sigy;
double sigx2;
double sigy2;
double sigxy;
} pcorst;
void* PCorrelTHFunc(void *arg) {
pcorst* p;
int i;
double *X,*Y;
p=(pcorst*)arg;
// X=&p->X[p->pidse[0]]; Y=&p->Y[p->pidse[1]];
X = p->X; Y = p->Y;
p->sigx=p->sigy=p->sigxy=p->sigx2=p->sigy2=0.0;
for(i=p->pidse[0]; i<p->pidse[1]; i++) {
// p->sigxy += *X * *Y;
// p->sigx += *X;
// p->sigy += *Y;
// p->sigx2 += *X * *X;
// p->sigy2 += *Y * *Y;
// X++; Y++;
p->sigxy += X[i] * Y[i];
p->sigx += X[i];
p->sigy += Y[i];
p->sigx2 += X[i] * X[i];
p->sigy2 += Y[i] * Y[i];
}
return NULL;
}
/* v1.pcorrels2(v2) does a Pearson correlation*/
#if defined(t)
static double pcorrelsmt(double *x, double* y, int n,int nth) {
int i,nperth,idx,rc;
double sigxy, sigx, sigy, sigx2, sigy2, ret;
pcorst** pp;
pthread_t* pth;
pthread_attr_t attr;
ret=sigxy=sigx=sigy=sigx2=sigy2=0.0; // initialize these
nperth = n / nth;
//allocate thread args
pp = (pcorst**)malloc(sizeof(pcorst*)*nth);
idx=0;
for(i=0;i<nth;i++) {
pp[i] = (pcorst*)calloc(1,sizeof(pcorst));
pp[i]->X = x;
pp[i]->Y = y;
pp[i]->pidse[0] = idx;
pp[i]->pidse[1] = idx + nperth;
idx += nperth;
}
i--; if(pp[i]->pidse[1] < n ||
pp[i]->pidse[1] > n) pp[i]->pidse[1] = n; //make sure all values used
//allocate thread IDs
pth=(pthread_t*)malloc(sizeof(pthread_t)*nth);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
//start threads
for(i=0;i<nth;i++) if((rc=pthread_create(&pth[i], NULL, PCorrelTHFunc, (void*)pp[i]))) {
printf("pcorrelsmt ERRA: couldn't create thread : %d!\n",rc);
goto PCMTFREE;
}
pthread_attr_destroy(&attr);
//wait for them to finish
for(i=0;i<nth;i++) if((rc=pthread_join(pth[i], NULL))) {
printf("pcorrelsmt ERRB: couldn't join thread : %d!\n",rc);
goto PCMTFREE;
}
//put together the results
for(i=0;i<nth;i++) {
sigx += pp[i]->sigx;
sigy += pp[i]->sigy;
sigxy += pp[i]->sigxy;
sigx2 += pp[i]->sigx2;
sigy2 += pp[i]->sigy2;
}
sigxy -= (sigx * sigy) / n;
sigx2 -= (sigx * sigx) / n;
sigy2 -= (sigy * sigy) / n;
if(sigx2 <= 0) goto PCMTFREE;
if(sigy2 <= 0) goto PCMTFREE;
ret = sigxy / sqrt(sigx2*sigy2);
PCMTFREE:
//free memory
for(i=0;i<nth;i++) free(pp[i]);
free(pp);
free(pth);
return ret; // return results
}
#endif
/* v1.pcorrels2(v2) does a Pearson correlation*/
static double pcorrels2 (double *x, double* y, int n) {
int i;
double sigxy, sigx, sigy, sigx2, sigy2;
sigxy=sigx=sigy=sigx2=sigy2=0.0; // initialize these
for(i=0; i<n; i++) {
sigxy += x[i] * y[i];
sigx += x[i];
sigy += y[i];
sigx2 += x[i]*x[i];
sigy2 += y[i]*y[i];
}
sigxy -= (sigx * sigy) / n;
sigx2 -= (sigx * sigx) / n;
sigy2 -= (sigy * sigy) / n;
if(sigx2 <= 0) return 0;
if(sigy2 <= 0) return 0;
sigxy = sigxy / sqrt(sigx2*sigy2);
return sigxy;
}
static double pcorrel (void* vv) {
int i, n;
double *x, *y;
n = vector_instance_px(vv, &x);
if ((i=vector_arg_px(1, &y)) != n ) {printf("pcorrelsERRA: %d %d\n",n,i); hxe();}
if(ifarg(2)) {
#if defined(t)
return pcorrelsmt(x,y,n,(int)*getarg(2));
#else
printf("using NEURON version 6; pcorrelsmt() not compiled\n");
return 0.0;
#endif
} else {
return pcorrels2(x,y,n);
}
}
ENDVERBATIM
: based on python scipy code in stats.py in pearsonr function
: get the probability of null hypothesis (that correlation(pearson,spearman,etc.) btwn variables == 0.0)
: $1 == sample size (n)
: $2 == correlation coefficient (r) , -1.0 <= r <= 1.0
FUNCTION rpval () {
VERBATIM
double n , r, df , TINY , ts , mpval;
n = *getarg(1);
r = *getarg(2);
if( r < -1.0 || r > 1.0 ){
printf("ppval ERRA: r=%g must be : -1.0 <= r <= 1.0\n",r);
return -1.0;
}
if( n < 3 ){
printf("ppval ERRB: n too small, can't calc probability on samples with < 3 values!\n");
return -1.0;
}
df = n-2; // degres of freedom
// Use a small floating point value to prevent divide-by-zero nonsense
// fixme: TINY is probably not the right value and this is probably not
// the way to be robust. The scheme used in spearmanr is probably better.
TINY = 1.0e-20;
ts = r*sqrt(df/((1.0-r+TINY)*(1.0+r+TINY)));
mpval = betai(0.5*df,0.5,df/(df+ts*ts));
return mpval;
ENDVERBATIM
}
VERBATIM
static const double* sortdata = NULL; /* used in the quicksort algorithm */
/* Helper function for sort. Previously, this was a nested function under
* sort, which is not allowed under ANSI C.
*/
static
int compare(const void* a, const void* b)
{ const int i1 = *(const int*)a;
const int i2 = *(const int*)b;
const double term1 = sortdata[i1];
const double term2 = sortdata[i2];
if (term1 < term2) return -1;
if (term1 > term2) return +1;
return 0;
}
void csort (int n, const double mdata[], int index[])
/* Sets up an index table given the data, such that mdata[index[]] is in
* increasing order. Sorting is done on the indices; the array mdata
* is unchanged.
*/
{ int i;
sortdata = mdata;
for (i = 0; i < n; i++) index[i] = i;
qsort(index, n, sizeof(int), compare);
}
static double* getrank (int n, double mdata[])
/* Calculates the ranks of the elements in the array mdata. Two elements with
* the same value get the same rank, equal to the average of the ranks had the
* elements different values. The ranks are returned as a newly allocated
* array that should be freed by the calling routine. If getrank fails due to
* a memory allocation error, it returns NULL.
*/
{ int i;
double* rank;
int* index;
rank = (double*)malloc(n*sizeof(double));
if (!rank) return NULL;
index = (int*)malloc(n*sizeof(int));
if (!index)
{ free(rank);
return NULL;
}
/* Call csort to get an index table */
csort (n, mdata, index);
/* Build a rank table */
for (i = 0; i < n; i++) rank[index[i]] = i;
/* Fix for equal ranks */
i = 0;
while (i < n)
{ int m;
double value = mdata[index[i]];
int j = i + 1;
while (j < n && mdata[index[j]] == value) j++;
m = j - i; /* number of equal ranks found */
value = rank[index[i]] + (m-1)/2.;
for (j = i; j < i + m; j++) rank[index[j]] = value;
i += m;
}
free (index);
return rank;
}
/*
The spearman routine calculates the Spearman rank correlation between two vectors.
n (input) int The number of elements in a data vector
data1 (input) double array -- the first vector
data2 (input) double array -- the second vector
*/
static double spearman(int n, double* data1, double* data2)
{ int i;
int m = 0;
double* rank1;
double* rank2;
double result = 0.;
double denom1 = 0.;
double denom2 = 0.;
double avgrank;
double* tdata1;
double* tdata2;
tdata1 = (double*)malloc(n*sizeof(double));
if(!tdata1) return 0.0; /* Memory allocation error */
tdata2 = (double*)malloc(n*sizeof(double));
if(!tdata2) /* Memory allocation error */
{ free(tdata1);
return 0.0;
}
for (i = 0; i < n; i++)
{ tdata1[m] = data1[i];
tdata2[m] = data2[i];
m++;
}
if (m==0) return 0;
rank1 = getrank(m, tdata1);
free(tdata1);
if(!rank1) return 0.0; /* Memory allocation error */
rank2 = getrank(m, tdata2);
free(tdata2);
if(!rank2) /* Memory allocation error */
{ free(rank1);
return 0.0;
}
avgrank = 0.5*(m-1); /* Average rank */
for (i = 0; i < m; i++)
{ const double value1 = rank1[i];
const double value2 = rank2[i];
result += value1 * value2;
denom1 += value1 * value1;
denom2 += value2 * value2;
}
/* Note: denom1 and denom2 cannot be calculated directly from the number
* of elements. If two elements have the same rank, the squared sum of
* their ranks will change.
*/
free(rank1);
free(rank2);
result /= m;
denom1 /= m;
denom2 /= m;
result -= avgrank * avgrank;
denom1 -= avgrank * avgrank;
denom2 -= avgrank * avgrank;
if (denom1 <= 0) return 0; /* include '<' to deal with roundoff errors */
if (denom2 <= 0) return 0; /* include '<' to deal with roundoff errors */
result = result / sqrt(denom1*denom2);
return result;
}
static double scorrel(void* vv) {
int i, n;
double *x, *y;
n = vector_instance_px(vv, &x);
if ((i=vector_arg_px(1, &y)) != n ) {printf("scorrelERRA: %d %d\n",n,i); hxe();}
return spearman(n,x,y);
}
//* Kendall's correlation routines
//** Erfcc() Returns the complementary error function erfc(x) with fractional error
// everywhere less than 1.2 x 10^-7.
// from place.mod, is that from numerical recipes??
double Erfcc (double x) {
double mt,z,ans;
z=fabs(x);
mt=1.0/(1.0+0.5*z);
ans=mt*exp(-z*z-1.26551223+mt*(1.00002368+mt*(0.37409196+mt*(0.09678418+\
mt*(-0.18628806+mt*(0.27886807+mt*(-1.13520398+mt*(1.48851587+\
mt*(-0.82215223+mt*0.17087277)))))))));
return x >= 0.0 ? ans : 2.0-ans;
}
//** Rktau() R version of kendall tau, doesnt have huge memory footprint
//function returns kendall's tau
double Rktau (double* x, double* y, int n){
int i,j; double c,vx,vy,sx,sy,var,z,tau;
c = vx = vy = 0.0;
for(i = 0; i < n; i++) {
for(j = 0; j < i; j++) {
sx = (x[i] - x[j]);
sx = ((sx > 0) ? 1 : ((sx == 0)? 0 : -1));
sy = (y[i] - y[j]);
sy = ((sy > 0) ? 1 : ((sy == 0)? 0 : -1));
vx += sx * sx;
vy += sy * sy;
c += sx * sy;
}
}
if(vx>0 && vy>0) {
tau = c / sqrt(vx*vy);
return tau;
}
return 0.;
}
//** vec1.kcorrel(vec2,[fast version -- useful for large arrays, vec of size 1 holding p-value])
// kendall's tau correlation
static double kcorrel (void* vv) {
int i, n;
double *x, *y, *prob, *i1d, *i2d, *ps, var, z, tau;
n = vector_instance_px(vv, &x);
if ((i=vector_arg_px(1, &y)) != n ) {printf("kcorrel ERRA: %d %d\n",n,i); hxe();}
if(ifarg(2) && *getarg(2)) {
i1d=dcrset(n*3); i2d=&i1d[n]; ps=&i2d[n]; tau=kcorfast(x,y,i1d,i2d,n,ps);
} else {
tau = Rktau(x,y,n);
}
if(!(ifarg(3) && vector_arg_px(3,&prob))) prob = 0x0; //does user want to store p-value?
if(prob) { //get p-value
var = (4.0 * n + 10.0) / (9.0 * n * (n - 1.0));
z = tau / sqrt(var);
*prob = Erfcc(fabs(z)/1.4142136); //when prob small, chance of tau having its value by chance is small
}
return tau;
}
//** mycompare() comparison function for qsort -- sorts in ascending order
static int mycompare (const void* a, const void* b)
{ double d1,d2;
d1 = *(double*)a;
d2 = *(double*)b;
if (d1 < d2) return -1;
if (d1 > d2) return +1;
return 0;
}
//** mergesort_array()
// recursive mergesort -- sorts a by splitting into sublists, sorting, and recombining
void mergesort_array (double a[], int size, double temp[],unsigned long* swapcount) {
int i1, i2, i, tempi, j, vv;
double *right,*left;
if(size<=1) return; //base case -- 1 element is sorted by definition
if (0 && size <MIN_MERGESORT_LIST_SIZE){//can use insertion sort for small arrays -- but first need to put in swapcount incs
/* Use insertion sort */
for (i=0; i < size; i++) {
vv = a[i];
for (j = i - 1; j >= 0; j--) {
if (a[j] <= vv) break;
a[j + 1] = a[j];
}
a[j + 1] = vv;
}
return;
}
mergesort_array(a, size/2, temp,swapcount); //sort left half
mergesort_array(a + size/2, size - size/2, temp,swapcount); //sort right half
//merge halves together
i=tempi=0; i1 = size/2; i2 = size - size/2;
left = a; right = &a[size/2];
while(i1>0 && i2>0) {
if(*right < *left) {
*swapcount += i1;
temp[i] = *right++;
i2--;
} else {
temp[i] = *left++;
i1--;
}
i++;
}
if(i2>0) {
while(i2-->=0 && i<size) temp[i++] = *right++; //copy leftovers from right side
} else {
while(i1-->=0 && i<size) temp[i++] = *left++; //copy leftovers from left side
}
memcpy(a, temp, size*sizeof(double));//copy sorted results to a
}
//** qsort2() parallel sort
//parallel sort of p1in,p2in by sorting in lockstep. output into p1out,p2out.
//note that only p1out will be in ascending order on termination.
int qsort2 (double *p1in, double* p2in, int n,double* p1out,double* p2out) {
int i;
scr=scrset(n);
for (i=0;i<n;i++) scr[i]=i;
nrn_mlh_gsort(p1in, (int*)scr, n, cmpdfn);
for (i=0;i<n;i++) {
p1out[i]=p1in[scr[i]];
p2out[i]=p2in[scr[i]];
}
return 1;
}
//** getMs() used in kcorfast to count # of ties
unsigned long getMs (double* data,int n) { //Assumes data is sorted.
unsigned long Ms, tieCount;
int i;
Ms = tieCount = 0;
for(i=1;i<n;i++) {
if(data[i] == data[i-1]) {
tieCount++;
} else if(tieCount) {
Ms += (tieCount*(tieCount+1))/2;
tieCount = 0;
}
}
if(tieCount) {
Ms += (tieCount*(tieCount+1)) / 2;
}
return Ms;
}
//** kcorfast()
// O(n logn) version of kendall's tau, based on Knight 1966 paper and David Simcha's D
// implementation
// i1d,i2d,ps are scratch arrays that have same size as input1,input2
double kcorfast (double* input1, double* input2, double* i1d , double* i2d,int n,double* ps) {
int i;
unsigned long nPair, N, m1, m2, tieCount, swapCount;
long s;
double denom1,denom2;
m1 = m2 = 0; N = n;
nPair = N * ( N - 1 ) / 2; //total # of pairs
qsort2(input1,input2,n,i1d,i2d); //parallel sort by input1
s = nPair;
if(verbose>2) printf("nPair=%lu\n",nPair);
if(verbose>3){printf("i1d after qsort2: "); for(i=0;i<n;i++) printf("%g ",i1d[i]); printf("\n");
printf("i2d after qsort2: "); for(i=0;i<n;i++) printf("%g ",i2d[i]); printf("\n");}
tieCount = 0;
for(i=1;i<n;i++) {
if(i1d[i] == i1d[i-1]) {
tieCount++;
} else if(tieCount > 0) {
qsort(&i2d[i-tieCount-1],tieCount+1,sizeof(double),mycompare);
m1 += tieCount * (tieCount + 1) / 2;
s += getMs(&i2d[i-tieCount-1],tieCount+1);
tieCount = 0;
}
}
if(verbose>2) printf("tieCount=%lu\n",tieCount);
if(tieCount > 0) {
qsort(&i2d[n-tieCount-1],tieCount+1,sizeof(double),mycompare);
m1 += tieCount * (tieCount + 1) / 2;
s += getMs(&i2d[n-tieCount-1],tieCount+1);
}
if(verbose>2) printf("tieCount=%lu\n",tieCount);
swapCount = 0;
mergesort_array(i2d,n,ps,&swapCount); //sort input2 & count # of swaps to get into sorted order
if(verbose>3) { printf("i2d after mergesort: "); for(i=0;i<n;i++) printf("%g ",ps[i]); printf("\n"); }
if(verbose>2) printf("swapCount=%lu\n",swapCount);
m2 = getMs(i2d,n); if(verbose>2) printf("s=%lu m1=%lu m2=%lu\n",s,m1,m2);
s -= (m1 + m2) + 2 * swapCount;
denom1=nPair-m1; denom2=nPair-m2; if(verbose>2) printf("s=%lu d1=%g d2=%g\n",s,denom1,denom2);
if(denom1>0. && denom2>0.) return s / sqrt(denom1*denom2); else return 0.;
}
//root mean square of vector's elements
static double rms (void* vv) {
int i,n;
double *x,sum;
if(!(n=vector_instance_px(vv, &x))) {printf("rms ERRA: 0 sized vector!\n"); hxe();}
sum=0.0;
for(i=0;i<n;i++) sum += x[i]*x[i];
sum/=(double)n;
if(sum>0.) return sqrt(sum); else return 0.0;
}
//cumulative sum of vector's elements
static double cumsum (void* vv) {
int i,n;
double *x,*y;
if(!(n=vector_instance_px(vv, &x))) {printf("cumsum ERRA: 0 sized vector!\n"); hxe();}
if(vector_arg_px(1, &y) != n) {printf("cumsum ERRB: output vec size needs size of %d\n",n); hxe();}
memcpy(y,x,sizeof(double)*n);
for(i=1;i<n;i++) y[i] += y[i-1];
return 1.0;
}
ENDVERBATIM
:* vec.unnan() will reset nans, infs, neginfs to selected values -- default 0,0,0
VERBATIM
static double unnan (void *vv) {
int i,nx,cnt; double newnan,newinf,neginf;
union dblint xx;
double *x;
newnan=newinf=neginf=0;
nx = vector_instance_px(vv, &x);
if (ifarg(1)) newinf=newnan=*getarg(1);
if (ifarg(2)) newinf=*getarg(2);
if (ifarg(3)) neginf=*getarg(3);
for (i=0,cnt=0;i<nx;i++) {
xx.d=x[i];
if (xx.i[0]==0x0 && xx.i[1]==0xfff80000) {x[i]=newnan; cnt++;}
if (xx.i[0]==0x0 && xx.i[1]==0x7ff00000) {x[i]=newinf; cnt++;}
if (xx.i[0]==0x0 && xx.i[1]==0xfff00000) {x[i]=neginf; cnt++;}
}
return (double)cnt;
}
ENDVERBATIM
:* v1.vstats(v2) does a linear regression, using v2 as the x-coords
VERBATIM
static double vstats(void* vv) {
int i, n;
double *x, *y, *out;
double sigxy, sigx, sigy, sigx2, sigy2;
double r, m, b, dmeansqerr,dmaxsqerr;
/* how to get the instance data */
n = vector_instance_px(vv, &y);
if(ifarg(1)) {
if(vector_arg_px(1, &x) != n ) {
hoc_execerror("Vector size doesn't match.", 0);
}
sigxy= sigx= sigy= sigx2=sigy2=0; // initialize these
for(i=0; i<n; i++) {
sigxy += x[i] * y[i];
sigx += x[i];
sigy += y[i];
sigx2 += x[i]*x[i];
sigy2 += y[i]*y[i];
}
m = (n*sigxy - sigx*sigy)/(n*sigx2 - sigx*sigx);
b = (sigy*sigx2 - sigx*sigxy)/(n*sigx2 - sigx*sigx);
r = (n*sigxy - sigx*sigy)/(sqrt(n*sigx2-sigx*sigx) * sqrt(n*sigy2-sigy*sigy));
getsqerr(x,y,m,b,n,&dmeansqerr,&dmaxsqerr);//mean,max squared error
if(ifarg(2)){ //save results to output
out=vector_newsize(vector_arg(2),5);
out[0]=m; out[1]=b; out[2]=r; out[3]=dmeansqerr; out[4]=dmaxsqerr;
} else {
printf("Examined %d data points\n", n);
printf("slope = %f\n", m);
printf("intercept = %f\n", b);
printf("R = %f\n", r);
printf("R-squared = %f\n", r*r);
printf("MeanSQErr = %f\n",dmeansqerr);
printf("MaxSQErr = %f\n",dmaxsqerr);
}
return 1;
} else {
printf("You must supply an x vector\n");
return 0;
}
}
ENDVERBATIM
:* v1.randwd(num[,v2]) will randomly flip num bits from BVBASE to 1
: does v1.fill(BVBASE); optionally fill v2 with the indices
VERBATIM
static double randwd(void* vv) {
int i, ii, jj, nx, ny, flip, flag;
double* x, *y;
/* how to get the instance data */
nx = vector_instance_px(vv, &x);
flip = (int) *getarg(1);
if (ifarg(2)) { /* write a diff vector to z */
flag = 1; ny = vector_arg_px(2, &y);
if (ny!=flip) { hoc_execerror("Opt vector must be size for # of flips", 0); }
} else { flag = 0; }
if (flip>=nx) { hoc_execerror("# of flips exceeds (or ==) vector size", 0); }
for (i=0; i < nx; i++) { x[i] = BVBASE; }
for (i=0,jj=0; i < flip; i++) { /* flip these bits */
ii = (int) ((nx+1)*drand48());
if (x[ii]==BVBASE) {
x[ii] = 1.;
if (flag) { y[jj] = ii; jj++; }
} else {
i--;
}
}
return flip;
}
ENDVERBATIM
:* v1.hash(veclist)
VERBATIM
static double hash (void* vv) {
int i, j, nx, nv[VRRY], num, vfl;
union dblint xx;
Object* ob;
double *x, *vvo[VRRY], big, y, prod;
nx = vector_instance_px(vv, &x);
if (ifarg(1)) {
vfl=0;
ob=*hoc_objgetarg(1);
num = ivoc_list_count(ob);
if (num>VRRY) {printf("vecst:hash ERR: can only handle %d vecs: %d\n",VRRY,num); hxe();}
for (i=0;i<num;i++) { nv[i] = list_vector_px(ob, i, &vvo[i]);
if (nx!=nv[i]) { printf("vecst:hash ERR %d %d %d\n",i,nx,nv[i]);hxe();}}
} else {
vfl=1; num=nx; nx=1; // outer loop will go only once
}
big=pow(DBL_MAX,1./(double)num); // base biggest # on nth root of num of values being used
for (i=0;i<nx;i++) {
for (j=0,prod=1;j<num;j++) {
if (vfl) { xx.d=x[j]; // break the double up into 2 unsigned ints
} else { xx.d=vvo[j][i]; }
if (xx.i[0]==0) { xx.i[0]=xx.i[1]; xx.i[0]<<=4; } // high order bits may be 0
if (xx.i[1]==0) { xx.i[1]=xx.i[0]; xx.i[1]<<=4; } // low order bits unlikely 0
mcell_ran4_init(xx.i[1]);
mcell_ran4((uint32_t*)&xx.i[0], &y, 1, big); // generate a pseudorand number based on these
prod*=y; // keep multiplying these out
}
if (! vfl) x[i]=prod; else return prod; // just return the 1 value
}
return (double)nx;
}
ENDVERBATIM
:* v1.smash(veclist,base)
: smash squeezes a set of numbers into a single double by considering them as digits
: in base base -- x[i]+=vvo[i][j]*wt; where wt is base^i
: note that handles transpose -- ie can smash on (transpose==1) or across each vec in a veclist
VERBATIM
static double smash (void* vv) {
int i, j, nx, nv[VRRY], num;
Object* ob;
double *x, *vvo[VRRY], wt, wtj;
nx = vector_instance_px(vv, &x);
ob=*hoc_objgetarg(1);
if (ifarg(2)) wtj=*getarg(2); else wtj=10.;
num = ivoc_list_count(ob);
if (num>VRRY) {printf("vecst:smash ERRA: can only handle %d vecs: %d\n",VRRY,num); hxe();}
if (transpose) if (nx!=num) { printf("vecst:smash ERRB %d %d %d\n",i,nx,nv[i]);hxe(); }
for (i=0;i<num;i++) {
nv[i] = list_vector_px(ob, i, &vvo[i]);
if (!transpose) if (nx!=nv[i]) { printf("vecst:smash ERRB %d %d %d\n",i,nx,nv[i]);hxe(); }
}
if (transpose) {
for (i=0;i<num;i++) { // num==nx: each vector indiviudally
for (j=0,x[i]=0,wt=1;j<nv[i];j++,wt*=wtj) x[i]+=vvo[i][j]*wt;
}
} else for (i=0;i<nx;i++) {
for (j=0,x[i]=0,wt=1;j<num;j++,wt*=wtj) x[i]+=vvo[j][i]*wt;
}
return (double)nx;
}
ENDVERBATIM
:* v1.smash1([wtjump,mod])
: similar to smash() but operates on a single vector; also cycles every (optional) 'mod'
: iterations to reset the weighting back to 1; presumably mod and base (wtjump) should
: have no shared factors
VERBATIM
static double smash1 (void* vv) {
int i, j, nx, nv[VRRY], num, mod;
double *x, wt, wtj, res;
nx = vector_instance_px(vv, &x);
if (ifarg(1)) wtj=*getarg(1); else wtj=10.;
if (ifarg(2)) mod=(int)*getarg(2); else mod=0;
for (j=0,res=0,wt=1;j<nx;j++,wt*=wtj) {
res+=x[j]*wt;
if (mod && j%mod==0) wt=1;
}
return res;
}
ENDVERBATIM
:* v1.dpro(veclist[,step,gap]) -- another hashing function?
VERBATIM
static double dpro (void* vv) {
int i, j, nx, nv[VRRY], num, step, gap;
Object* ob;
double *x, *vvo[VRRY], wt;
nx = vector_instance_px(vv, &x);
ob=*hoc_objgetarg(1);
if (ifarg(2)) step=(int)*getarg(2); else step=1;
if (ifarg(3)) gap=(int)*getarg(3); else gap=1;
num = ivoc_list_count(ob);
if (num>VRRY) {printf("stats:dpro ERR: can only handle %d vecs: %d\n",VRRY,num); hxe();}
for (i=0;i<num;i++) {
nv[i] = list_vector_px(ob, i, &vvo[i]);
if (nx!=nv[i]) { printf("stats:dpro ERR %d %d %d\n",i,nx,nv[i]);hxe(); }
}
for (i=0;i<nx;i+=step) {
for (j=0,x[i]=0,wt=1;j<num;j++) {
x[i]+=vvo[j][i]*wt;
}
}
return (double)nx;
}
ENDVERBATIM
:* v1.setrnd(flag) performs setrand()
: note that seed is kept as a global so that it can be easily set from hoc
: to repeat a sequence
: flag: 1 rand(); 2 drand48(); 3 scop_random(); 4 mcell_ran4(); 5 integers via mcell_ran4()
: v1.setrnd(4[,MAX_VAL DEFAULT=1, SEED])
: v1.setrnd(4,vec[,step,seed]) // find location of vec value >= randvar and mul by step
: v1.setrnd(4.5,min,max[,seed]) // [min,max)
: v1.setrnd(5[,n,seed]) -- integers [0,100) or [0,n]
: v1.setrnd(5[,min,max,seed]) -- integers [min,max] -- if seed=0 it's not reset
: v1.setrnd(5,ind[,seed]) -- random values from ind
: v1.setrnd(6) -- unique integers as follows:
: v1.setrnd(6,min,max[,seed]) -- unique in [min,max]
: v1.setrnd(6,min,max,exclude_vec[,seed]) -- unique in [min,max] excluding values in exclude_vec
VERBATIM
static double setrnd (void* vv) {
int flag, i,j,k,n,cnt; unsigned int nx, nx1, nex, lt, rt, mid;
double *x, y, *ex, *ex2, min, max, dfl, tmp, step, num;
unsigned long value;
value=1;
nx = vector_instance_px(vv, &x);
flag = (int)(dfl=*getarg(1));
if (flag==1) {
for (i=0; i < nx; i++) x[i] = (double)rand()/RAND_MAX;
} else if (flag==2) {
for (i=0; i < nx; i++) x[i] = drand48();
} else if (flag==3) { // scop_random()'s cheap and dirty rand
unsigned long a = 2147437301, c = 453816981, m = ~0;
value = (unsigned long) seed;
for (i=0; i < nx; i++) {
value = a * value + c;
x[i] = (fabs((double) value / (double) m));
}
seed=(double)value;
} else if (flag==4) { // mcell_ran4() doubles
ex=0x0; i=2;
if (ifarg(i)) {
if (hoc_is_object_arg(i)) {
nex=vector_arg_px(i++,&ex); // vector to look in
step=ifarg(i)?*getarg(i):1.0;
max=1.0; i++;
} else {
if (dfl==4.5 || ifarg(4)) { // flag 4.5 resolves ambiguity of arg3 max or seed
min=*getarg(i++);
max=*getarg(i++)-min;
dfl=4.5;
} else {
max=*getarg(i++);
}
}
} else max=1.0; // default
if (ifarg(i)) { y=*getarg(i++); if (y) ihigh=(unsigned int)y; } // look for seed
if (max==0) { for (i=0;i<nx;i++) x[i]=0.;
} else mcell_ran4(&ihigh, x, nx, max);