-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathte-datainit.cpp
1892 lines (1670 loc) · 64.9 KB
/
te-datainit.cpp
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 2012, Olav Stetter
//
// This file is part of TE-Causality.
//
// TE-Causality is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// TE-Causality is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with TE-Causality. If not, see <http://www.gnu.org/licenses/>.
#include "te-datainit.h"
#define FMODEL_SPIKECOUNT 1
#define FMODEL_HOWMANYAREACTIVE 2
#define FMODEL_LEOGANG 3
#define FMODEL_ERROR -1
#define HEIGHT_OF_ASCII_PLOTS 12
#define OUTPUTNUMBER_PRECISION 15
#undef SPIKE_INPUT_DATA_IS_BINARY
#undef TIME_SERIES_INPUT_DATA_IS_BINARY
#define NUMBER_OF_ROWS_TO_SKIP_IN_TIME_SERIES_INPUT_FILE 0 // 1 for Jordi's files
#undef ENABLE_BASELINE_CORRECTION
#define BASELINE_CORRECTION_BANDWIDTH 2000
#define SPEEDUP_BASELINE_CORRECTION
#define MAX_NUMBER_OF_BAD_DATA_LINES 20
#undef ENABLE_MOVING_WINDOW_AVERAGING_HACK_FOR_JORDIS_DATA
// set output stream depending on wether SimKernel's sim.h is included
// (see also te-datainit.h)
#undef IOSTREAMH
#undef IOSTREAMC
#undef IOSTREAMV
#ifdef SIM_IO_H
// SimKernel found.
#define IOSTREAMH Sim& output
#define IOSTREAMC output.io
#define IOSTREAMV output
#define IOSTREAMENDL Endl
#else
// SimKernel not found, using standard output.
#define IOSTREAMH std::ostream& output
#define IOSTREAMC output
#define IOSTREAMV output
#define IOSTREAMENDL std::endl
#endif
using namespace std;
double** load_time_series_from_file(std::string inputfile_name, unsigned int size, long samples, double input_scaling, bool OverrideRescalingQ, double std_noise, double fluorescence_saturation, double cutoff, gsl_rng* GSLrandom, IOSTREAMH)
{
// reserve and clear memory for result ("try&catch" is still missing!)
double **xresult = NULL;
char* in_from_file_array = NULL;
double* tempdoublearray = NULL;
try {
xresult = new double*[size];
for(unsigned int i=0; i<size; i++)
{
xresult[i] = NULL;
xresult[i] = new double[samples];
memset(xresult[i], 0, samples*sizeof(double));
}
in_from_file_array = new char[samples];
tempdoublearray = new double[samples];
}
catch(...) {
IOSTREAMC <<IOSTREAMENDL<<"error in load_time_series_from_file: cannot allocate enough memory!"<<IOSTREAMENDL;
exit(1);
}
// open input file
char* name = new char[inputfile_name.length()+1];
strcpy(name,inputfile_name.c_str());
#ifdef TIME_SERIES_INPUT_DATA_IS_BINARY
IOSTREAMC <<"-> setting up binary input ..."<<IOSTREAMENDL;
std::ifstream inputfile(name, std::ios::binary);
#else
IOSTREAMC <<"-> setting up plain text input ..."<<IOSTREAMENDL;
std::ifstream inputfile(name);
#endif
delete[] name;
if (inputfile == NULL) {
IOSTREAMC <<IOSTREAMENDL<<"error in load_time_series_from_file: cannot find input file!"<<IOSTREAMENDL;
exit(1);
}
// test file length
#ifndef TIME_SERIES_INPUT_DATA_IS_BINARY
long apparent_size = 1;
long apparent_samples = 0;
string line;
int temp_pos;
bool first_line = true;
while (getline(inputfile, line)) {
apparent_samples++;
if(first_line) {
while((temp_pos = line.find(",")) != std::string::npos) {
apparent_size++;
line.replace(temp_pos,1," ");
}
}
first_line = false;
}
inputfile.clear();
inputfile.seekg(0);
#if NUMBER_OF_ROWS_TO_SKIP_IN_TIME_SERIES_INPUT_FILE>0
IOSTREAMC <<"Warning in load_time_series_from_file: Set to skip first ";
IOSTREAMC <<NUMBER_OF_ROWS_TO_SKIP_IN_TIME_SERIES_INPUT_FILE<<" rows of each column."<<IOSTREAMENDL;
#endif
apparent_size -= NUMBER_OF_ROWS_TO_SKIP_IN_TIME_SERIES_INPUT_FILE; // because 1st line is sample number
IOSTREAMC <<"-> it appears that the file contains "<<apparent_size<<" nodes and "<<apparent_samples;
IOSTREAMC <<" samples each."<<IOSTREAMENDL;
if(apparent_size < 1) {
IOSTREAMC <<IOSTREAMENDL<<"error in load_time_series_from_file: could not detect number of nodes in file!"<<IOSTREAMENDL;
inputfile.close();
exit(1);
}
if(apparent_samples < 2) {
IOSTREAMC <<IOSTREAMENDL<<"error in load_time_series_from_file: could not detect number of samples in file!"<<IOSTREAMENDL;
inputfile.close();
exit(1);
}
if(apparent_size != size) {
IOSTREAMC <<IOSTREAMENDL<<"error in load_time_series_from_file: number of nodes in file does not match given size!"<<IOSTREAMENDL;
inputfile.close();
exit(1);
}
if(apparent_samples < samples) {
IOSTREAMC <<IOSTREAMENDL<<"error in load_time_series_from_file: number of lines in file is lower than given sample number!"<<IOSTREAMENDL;
inputfile.close();
exit(1);
}
#else
inputfile.seekg(0,std::ios::end);
if(long(inputfile.tellg()) != size*samples)
{
IOSTREAMC <<IOSTREAMENDL<<"error in load_time_series_from_file: file length of input does not match given parameters!"<<IOSTREAMENDL;
exit(1);
}
inputfile.seekg(0,std::ios::beg);
#endif
// import and rescale data
IOSTREAMC <<"reading data..."<<IOSTREAMENDL;
#ifdef TIME_SERIES_INPUT_DATA_IS_BINARY
for(int j=0; j<size; j++)
{
inputfile.read(in_from_file_array, samples);
// OverrideRescalingQ = true
// Dies ignoriert also "appliedscaling", "noise", "HighPassFilterQ" und "cutoff"
// Therefore, "bins" takes the role of an upper cutoff
if (OverrideRescalingQ)
for(long k=0; k<samples; k++)
// xdata[j][k] = in_from_file_array[k];
xresult[j][k] = double(in_from_file_array[k]);
else // OverrideRescalingQ = false
{
for (long k=0; k<samples; k++)
{
// transform to unsigned notation
tempdoublearray[k] = double(in_from_file_array[k]);
if (in_from_file_array[k]<0) tempdoublearray[k] += 256.;
// transform back to original signal (same as in Granger case)
tempdoublearray[k] /= input_scaling;
// assuming a saturation with hill function of order 1
if (fluorescence_saturation > 0.)
tempdoublearray[k] = tempdoublearray[k]/(tempdoublearray[k] + fluorescence_saturation);
// adding noise
if (std_noise > 0.)
tempdoublearray[k] += gsl_ran_gaussian(GSLrandom,std_noise);
// apply cutoff
if ((cutoff>0)&&(tempdoublearray[k]>cutoff)) tempdoublearray[k] = cutoff;
}
}
memcpy(xresult[j],tempdoublearray,samples*sizeof(double));
}
#else
int next_pos;
int length;
for (long tt=0; tt<samples; tt++) {
// if((tt%5000)==0) {
// cout <<"debug: reading sample #"<<tt<<" ..."<<endl;
// }
getline(inputfile, line);
length = line.length();
// cout <<"debug: read = "<<line<<endl;
// before accepting the values, see if the number of commas matches
temp_pos = -1;
int comma_count = 0;
while((temp_pos = line.find(",",temp_pos+1)) != std::string::npos) {
comma_count++;
}
// for (int i=0; i<size+NUMBER_OF_ROWS_TO_SKIP_IN_TIME_SERIES_INPUT_FILE+1; i++) {
// temp_pos = line.find(",",temp_pos+1);
// if(temp_pos!=std::string::npos) comma_count++;
// }
long skipped_rows_count = 0;
if(comma_count+1 != size+NUMBER_OF_ROWS_TO_SKIP_IN_TIME_SERIES_INPUT_FILE) {
IOSTREAMC <<"warning in load_time_series_from_file: skipping line #"<<tt;
IOSTREAMC <<", because the number of entries is "<<comma_count<<" instead of ";
IOSTREAMC <<size+NUMBER_OF_ROWS_TO_SKIP_IN_TIME_SERIES_INPUT_FILE<<"!"<<IOSTREAMENDL;
// copying old values
assert(tt>0);
for (int i=0; i<size; i++) {
xresult[i][tt] = xresult[i][tt-1];
}
skipped_rows_count++;
assert(skipped_rows_count<MAX_NUMBER_OF_BAD_DATA_LINES);
}
else {
temp_pos = -1;
for (int i=0; i<size+NUMBER_OF_ROWS_TO_SKIP_IN_TIME_SERIES_INPUT_FILE; i++) {
next_pos = line.find(",",temp_pos+1);
if(next_pos==std::string::npos) {
next_pos = length - 1;
}
// line.replace(next_pos,1," ");
if (i >= NUMBER_OF_ROWS_TO_SKIP_IN_TIME_SERIES_INPUT_FILE) {
xresult[i-NUMBER_OF_ROWS_TO_SKIP_IN_TIME_SERIES_INPUT_FILE][tt] = \
atof(line.substr(temp_pos+1,next_pos-temp_pos+1).c_str());
// cout <<"debug: xresult[i][tt] = "<<xresult[i-NUMBER_OF_ROWS_TO_SKIP_IN_TIME_SERIES_INPUT_FILE][tt]<<endl;
}
temp_pos = next_pos;
}
// exit(1);
// if((tt%50000)==0) {
// cout <<"debug: sample #"<<tt<<": data of first three is: "<<xresult[0][tt]<<", "<<xresult[1][tt]<<", "<<xresult[2][tt]<<endl;
// }
}
}
#endif
inputfile.close();
#ifdef ENABLE_MOVING_WINDOW_AVERAGING_HACK_FOR_JORDIS_DATA
// apply a moning window correction (calculation see 24.10.11)
const long mwa_sigma = 2;
const long athird = samples/mwa_sigma; // implicit floor
IOSTREAMC <<"HACK WARNING: Moving window averaging activated, with a width of sigma = "<<mwa_sigma<<IOSTREAMENDL;
long shift, first, last, s2;
double* copy_array = NULL;
copy_array = new double[samples];
for (int i=0; i<size; i++) {
memcpy(copy_array,xresult[i],samples*sizeof(double));
for (long s=0; s<samples; s++) {
shift = s/athird; // implicit floor
if (shift < mwa_sigma) {
s2 = s - shift*athird;
first = mwa_sigma*s2 + shift;
last = min(samples-1, mwa_sigma*(s2+1) + shift -1);
// if (i==0) cout <<"debug: s="<<s<<": first="<<first<<", last="<<last<<endl;
xresult[i][s] = mean(copy_array, first, last);
}
}
}
delete[] copy_array;
#endif
// baseline correction
#ifdef ENABLE_BASELINE_CORRECTION
IOSTREAMC <<"applying baseline correction..."<<IOSTREAMENDL;
for (int i=0; i<size; i++) {
apply_baseline_correction(xresult[i],samples);
}
// std::cout <<"debug: result for first node: ";
// for (long tt=0; tt<samples; tt+=(long)(samples/13.)) {
// std::cout <<xresult[0][tt]<<std::endl;
// }
// exit(0);
// applying offset such that averaged signal is never negative
IOSTREAMC <<"applying offset such that averaged signal is never negative..."<<IOSTREAMENDL;
double min_xmean = std::numeric_limits<double>::max();
double temp_xmean;
// first, find lowest xmean value...
for(long tt=0; tt<samples; tt++) {
temp_xmean = 0.;
for (int i=0; i<size; i++) {
temp_xmean += xresult[i][tt];
}
temp_xmean /= size;
if(temp_xmean < min_xmean) min_xmean = temp_xmean;
}
// then, apply resulting offset
for(long tt=0; tt<samples; tt++) {
for (int i=0; i<size; i++) {
xresult[i][tt] -= min_xmean;
}
}
#else
IOSTREAMC <<"baseline correction disabled."<<IOSTREAMENDL;
#endif
// // determine available samples per globalbin for TE normalization later
// memset(AvailableSamples, 0, globalbins*sizeof(unsigned long));
// for (unsigned long t=StartSampleIndex; t<EndSampleIndex; t++)
// AvailableSamples[xglobal[t]]++;
//
// if (EqualSampleNumberQ || (MaxSampleNumberPerBin>0))
// {
// unsigned long maxsamples = ULONG_MAX;
// for (rawdata g=0; g<globalbins; g++)
// if (AvailableSamples[g]<maxsamples) maxsamples = AvailableSamples[g];
// IOSTREAMC <<"DEBUG: maxsamples = "<<maxsamples<<IOSTREAMENDL;
//
// if ((MaxSampleNumberPerBin>maxsamples) && !EqualSampleNumberQ)
// maxsamples = MaxSampleNumberPerBin;
// if ((MaxSampleNumberPerBin<maxsamples)&&(MaxSampleNumberPerBin>0))
// maxsamples = MaxSampleNumberPerBin;
// IOSTREAMC <<"DEBUG: cut to maxsamples = "<<maxsamples<<IOSTREAMENDL;
//
// unsigned long* AlreadySelectedSamples = new unsigned long[globalbins];
// memset(AlreadySelectedSamples, 0, globalbins*sizeof(unsigned long));
// for (unsigned long t=StartSampleIndex; t<EndSampleIndex; t++)
// if ((++AlreadySelectedSamples[xglobal[t]])>maxsamples)
// xglobal[t] = globalbins; // ..and therefore exclude from calculation
//
// // re-determine available samples per globalbin (inefficient)
// memset(AvailableSamples, 0, globalbins*sizeof(unsigned long));
// for (unsigned long t=StartSampleIndex; t<EndSampleIndex; t++)
// if (xglobal[t]<globalbins) AvailableSamples[xglobal[t]]++;
//
// delete[] AlreadySelectedSamples;
// }
// free allocated memory
// gsl_rng_free(GSLrandom);
delete[] in_from_file_array;
// delete[] xglobaltemp;
delete[] tempdoublearray;
// delete[] tempdoublearraycopy;
return xresult;
};
rawdata* generate_discretized_global_time_series(double** const time_series, unsigned int size, long samples, unsigned int globalbins, double GlobalConditioningLevel, unsigned long* AvailableSamples, long StartSampleIndex, long EndSampleIndex, bool EqualSampleNumberQ, long MaxSampleNumberPerBin, IOSTREAMH)
{
rawdata* xglobal = new rawdata[samples];
memset(xglobal, 0, samples*sizeof(rawdata));
double* xglobaltemp = generate_mean_time_series(time_series, size, samples);
// EVIL SAALBACH HACK FOR TIME CODE GLOBAL SIGNAL: -------------------------------------------- !!!!!!!!!!
// xglobaltemp[0] = 0.;
// for (unsigned long t=0; t<samples; t++)
// xglobaltemp[t] = double(int(t)%int(60*24/tauF));
// // xglobaltemp[t] = double(mod(t,60*24/tauF));
// IOSTREAMC <<"DEBUG OF EVIL TIME CODE HACK: last globaltemp value = "<<xglobaltemp[samples-1]<<IOSTREAMENDL;
if (GlobalConditioningLevel > 0.)
{
unsigned long below = 0;
for (long t=0; t<samples; t++)
{
if (xglobaltemp[t] > GlobalConditioningLevel) xglobal[t] = 1;
else
{
xglobal[t] = 0;
below++;
}
}
IOSTREAMC <<" -> global conditioning level "<<GlobalConditioningLevel<<": "<<(100.*below)/samples;
IOSTREAMC <<"% are below threshold. "<<IOSTREAMENDL;
}
else discretize(xglobaltemp,xglobal,samples,globalbins);
// // EVIL HACK FOR SHIFTED GLOBAL BINS: -------------------------------------------- !!!!!!!!!!
// IOSTREAMC <<"Warning: Evil global bin shifting hack enabled!!"<<IOSTREAMENDL;
// const double gminlevel = -0.25;
// const double gmaxlevel = 0.85;
// discretize(xglobaltemp,xglobal,gminlevel,gmaxlevel,samples,globalbins);
// EVIL HACK FOR SHIFTED GLOBAL BINS v2: -------------------------------------------- !!!!!!!!!!
// (calculation see 03.10.12)
// IOSTREAMC <<"Warning: Evil global bin shifting hack v2 enabled!!"<<IOSTREAMENDL;
// const double gmaxlevel = largest(xglobaltemp, samples);
// IOSTREAMC <<" -> Found maximum of xmean of x = "<<gmaxlevel<<IOSTREAMENDL;
// const double ghistopeak = Util_FindPeakInHistogram(xglobaltemp, samples, smallest(xglobaltemp, samples), gmaxlevel, 60);
// IOSTREAMC <<" -> Found peak in histogram at x = "<<ghistopeak<<IOSTREAMENDL;
// const double gminlevel = (double(globalbins)*ghistopeak - gmaxlevel)/(double(globalbins)-1.0);
// IOSTREAMC <<" -> Set new lower bound of histogram to x = "<<gminlevel<<IOSTREAMENDL;
// discretize(xglobaltemp,xglobal,gminlevel,gmaxlevel,samples,globalbins);
// determine available samples per globalbin for TE normalization later
memset(AvailableSamples, 0, globalbins*sizeof(unsigned long));
for (unsigned long t=StartSampleIndex; t<=EndSampleIndex; t++)
AvailableSamples[xglobal[t]]++;
if (EqualSampleNumberQ || (MaxSampleNumberPerBin>0)) {
IOSTREAMC <<"Warning: Sample number overrides enabled!"<<IOSTREAMENDL;
long maxsamples = LONG_MAX;
for (rawdata g=0; g<globalbins; g++)
if (AvailableSamples[g]<maxsamples) maxsamples = AvailableSamples[g];
IOSTREAMC <<"DEBUG: maxsamples = "<<maxsamples<<IOSTREAMENDL;
if ((MaxSampleNumberPerBin>maxsamples) && !EqualSampleNumberQ)
maxsamples = MaxSampleNumberPerBin;
if ((MaxSampleNumberPerBin<maxsamples)&&(MaxSampleNumberPerBin>0))
maxsamples = MaxSampleNumberPerBin;
IOSTREAMC <<"DEBUG: Cut to maxsamples = "<<maxsamples<<IOSTREAMENDL;
unsigned long* AlreadySelectedSamples = new unsigned long[globalbins];
memset(AlreadySelectedSamples, 0, globalbins*sizeof(unsigned long));
for (unsigned long t=StartSampleIndex; t<EndSampleIndex; t++)
if ((++AlreadySelectedSamples[xglobal[t]])>maxsamples)
xglobal[t] = globalbins; // ..and therefore exclude from calculation
// re-determine available samples per globalbin (inefficient)
memset(AvailableSamples, 0, globalbins*sizeof(unsigned long));
for (unsigned long t=StartSampleIndex; t<EndSampleIndex; t++)
if (xglobal[t]<globalbins) AvailableSamples[xglobal[t]]++;
delete[] AlreadySelectedSamples;
}
free_time_series_memory(xglobaltemp);
return xglobal;
}
rawdata** generate_discretized_version_of_time_series(double** const in, unsigned int size, long nr_samples, unsigned int nr_bins, rawdata* xglobal)
{
rawdata** xout;
xout = new rawdata*[size];
for(unsigned int ii=0; ii<size; ii++)
{
xout[ii] = new rawdata[nr_samples];
discretize(in[ii], xout[ii], nr_samples, nr_bins, xglobal);
}
return xout;
};
void discretize(const double* in, rawdata* out, long nr_samples, unsigned int nr_bins, rawdata* xglobal)
{
discretize(in, out, smallest(in,nr_samples,xglobal), largest(in,nr_samples,xglobal), nr_samples, nr_bins);
};
void discretize(const double* in, rawdata* out, double min, double max, long nr_samples, unsigned int nr_bins)
{
double xstepsize = (max-min)/nr_bins;
int xint;
for (unsigned long t=0; t<nr_samples; t++)
out[t] = discretize(in[t],min,max,nr_bins);
};
rawdata discretize(double in, double min, double max, unsigned int nr_bins)
{
assert(max>min);
assert(nr_bins>0);
// correct discretization according to 'te-test.nb'
// incorporated later: double xstepsize = (max-min)/nr_bins;
// IOSTREAMC <<"max = "<<max<<IOSTREAMENDL;
// IOSTREAMC <<"min = "<<min<<IOSTREAMENDL;
// IOSTREAMC <<"bins here = "<<nr_bins<<IOSTREAMENDL;
// IOSTREAMC <<"stepsize = "<<xstepsize<<IOSTREAMENDL;
int xint;
// assert(in<=max); ...does not have to be true, and does not matter, data is included in highest bin then
// assert(in>=min);
if (in>=max) xint = nr_bins-1;
else
{
if (in<=min) xint = 0;
// with stepsize variable: else xint = (int)((in-min)/xstepsize);
// without:
else xint = (int)((in-min)*double(nr_bins)/(max-min));
}
if (xint >= nr_bins) xint = nr_bins-1; // need to have this for some silly numerical reason...
assert((xint>=0)&&(rawdata(xint)<nr_bins)); // ...just to be sure...
return rawdata(xint);
};
// Orlandi: Adding option for predefined binning limits
rawdata** generate_discretized_version_of_time_series(double** const in, unsigned int size, long nr_samples, const std::vector<double>& binEdges, bool RelativeBinEdgesQ)
{
rawdata** xout;
xout = new rawdata*[size];
for(unsigned int ii=0; ii<size; ii++)
{
xout[ii] = new rawdata[nr_samples];
discretize(in[ii], xout[ii], nr_samples, binEdges, RelativeBinEdgesQ);
}
return xout;
};
void discretize(const double* in, rawdata* out, long nr_samples, const std::vector<double>& binEdges, bool RelativeBinEdgesQ)
{
std::vector<double> binEdgesAbsolute (binEdges);
// determine actual bin edges, if they were defined relatively in the control file
if(RelativeBinEdgesQ) {
const double min = smallest(in, nr_samples);
const double max = largest(in, nr_samples);
// rescale bin edges
for(std::vector<double>::size_type i = 0; i != binEdges.size(); i++) {
binEdgesAbsolute[i] = (max-min)*binEdgesAbsolute[i] + min;
// std::cout <<"DEBUG: binEdgesAbsolute[i] = "<<binEdgesAbsolute[i]<<std::endl;
}
}
for (unsigned long t=0; t<nr_samples; t++)
out[t] = discretize(in[t], binEdgesAbsolute);
};
// For now the bottom and top edges are doing nothing, they act like (-inf and inf)
rawdata discretize(double in, const std::vector<double>& binEdges)
{
// By default set it to the top bin
int xint = binEdges.size()-2;
// Correct to the right bin
for(std::vector<double>::size_type i = 1; i != binEdges.size(); i++) {
if(in < binEdges[i]) {
xint = i-1;
break;
}
}
assert((xint>=0)&&(rawdata(xint)<(binEdges.size()-1))); // ...just to be sure...*/
return rawdata(xint);
};
void apply_high_pass_filter_to_time_series(double** time_series, unsigned int size, long nr_samples)
{
for(unsigned int ii=0; ii<size; ii++)
apply_high_pass_filter_to_time_series(time_series[ii], nr_samples);
};
void apply_high_pass_filter_to_time_series(double* time_series, long nr_samples)
{
double* arraycopy = new double[nr_samples];
// of course, this is just a difference signal, so not really filtered
memcpy(arraycopy,time_series,nr_samples*sizeof(double));
time_series[0] = 0.;
for(long k=1; k<nr_samples; k++)
time_series[k] = arraycopy[k] - arraycopy[k-1];
delete[] arraycopy;
};
double** generate_time_series_from_spike_data(std::string inputfile_spiketimes, std::string inputfile_spikeindices, unsigned int size, unsigned int tauImg, long samples, std::string fluorescence_model, double std_noise, double fluorescence_saturation, double cutoff, double DeltaCalciumOnAP, double tauCa, gsl_rng* GSLrandom, IOSTREAMH)
{
// reserve and clear memory for result ("try&catch" is still missing!)
double **xresult = new double*[size];
for(unsigned int i=0; i<size; i++)
{
xresult[i] = new double[samples];
memset(xresult[i], 0, samples*sizeof(double));
}
// open files
char* nameI = new char[inputfile_spikeindices.length()+1];
strcpy(nameI,inputfile_spikeindices.c_str());
#ifdef SPIKE_INPUT_DATA_IS_BINARY
std::ifstream inputfileI(nameI, std::ios::binary);
#else
std::ifstream inputfileI(nameI);
#endif
if (inputfileI == NULL) {
IOSTREAMC <<IOSTREAMENDL<<"error: cannot find spike indices file!"<<IOSTREAMENDL;
exit(1);
}
delete[] nameI;
char* nameT = new char[inputfile_spiketimes.length()+1];
strcpy(nameT,inputfile_spiketimes.c_str());
#ifdef SPIKE_INPUT_DATA_IS_BINARY
IOSTREAMC <<"-> setting up binary input"<<IOSTREAMENDL;
std::ifstream inputfileT(nameT, std::ios::binary);
#else
IOSTREAMC <<"-> setting up plain text input"<<IOSTREAMENDL;
std::ifstream inputfileT(nameT);
#endif
if (inputfileT == NULL) {
IOSTREAMC <<IOSTREAMENDL<<"error: cannot find spike times file!"<<IOSTREAMENDL;
exit(1);
}
delete[] nameT;
// determine file length, then allocate memory
long nr_spikes = 0;
#ifdef SPIKE_INPUT_DATA_IS_BINARY
inputfileI.seekg(0,std::ios::end);
nr_spikes = inputfileI.tellg()/sizeof(int);
inputfileI.seekg(0,std::ios::beg);
#else
string line;
long tempsize = 0;
// while (!inputfileI.eof()) {
while (getline(inputfileI, line)) {
// cout <<"not the end of file!"<<flush;
// getline(inputfileI, line);
// cout <<"readin:"<<line<<endl;
tempsize++;
}
nr_spikes = tempsize;
inputfileI.clear();
inputfileI.seekg(0);
#endif
IOSTREAMC <<"-> number of spikes in index file: "<<nr_spikes<<IOSTREAMENDL;
int* xindex = new int[nr_spikes];
double* xtimes = new double[nr_spikes];
// read spike data
#ifdef SPIKE_INPUT_DATA_IS_BINARY
inputfileI.read((char*)xindex, nr_spikes*sizeof(int));
inputfileT.read(reinterpret_cast<char*>(xtimes), nr_spikes*sizeof(double));
#else
for (long tt=0; tt<nr_spikes; tt++) {
getline(inputfileI, line);
// cout <<"read="<<line<<endl;
xindex[tt] = atoi(line.c_str());
getline(inputfileT, line);
// cout <<"read="<<line<<endl;
xtimes[tt] = atof(line.c_str());
}
#endif
// close files
inputfileI.close();
inputfileT.close();
// debug output
// for(long t=0; t<min((long)20,nr_spikes); t++)
// IOSTREAMC <<"DEBUG: xindex = "<<xindex[t]<<", xtimes = "<<xtimes[t]<<IOSTREAMENDL;
// exit(0);
// test if read data appears valid
for (long tt=0; tt<nr_spikes; tt++) {
assert((xindex[tt]>=0)&&(xindex[tt]<size)); // indices are in allowed range
if(tt>0) assert(xtimes[tt]>=xtimes[tt-1]); // spike times are an ordered sequence
if(tt<nr_spikes-1) assert(xtimes[tt]<=xtimes[tt+1]);
}
// choose switch key for the fluorescence model
int fluorescence_model_key = FMODEL_ERROR;
if (fluorescence_model == "SpikeCount") fluorescence_model_key = FMODEL_SPIKECOUNT;
if (fluorescence_model == "HowManyAreActive") fluorescence_model_key = FMODEL_HOWMANYAREACTIVE;
if (fluorescence_model == "Leogang") fluorescence_model_key = FMODEL_LEOGANG;
if(fluorescence_model_key == FMODEL_ERROR) {
IOSTREAMC <<IOSTREAMENDL<<"error: unknown fluorescence model!"<<IOSTREAMENDL;
exit(1);
}
// generate fluorescence data
IOSTREAMC <<"-> generate fluorescence data using model: "<<fluorescence_model<<IOSTREAMENDL;
// const int int_tauF = (int)round(tauF); // in ms
unsigned long startindex = 1;
unsigned long endindex = 0; // therefore, we miss the first spike!
long dataindex = 0;
unsigned long tinybit_spikenumber;
// unsigned long ttExactMS = 0;
for (unsigned long ttExactMS=0; ttExactMS<tauImg*samples; ttExactMS+=tauImg)
{
// determine starting and ending spike index of current frame
while ((endindex+1<nr_spikes)&&(xtimes[endindex+1]<=ttExactMS+tauImg))
endindex++;
tinybit_spikenumber = std::max(endindex-startindex+1,(unsigned long)0);
// IOSTREAMC <<"DEBUG: ttExactMS = "<<ttExactMS<<", startindex = "<<startindex<< \
// ", endindex = "<<endindex<<", tinybit_spikenumber = "<<tinybit_spikenumber<<IOSTREAMENDL;
for (int ii=0; ii<size; ii++)
{
switch (fluorescence_model_key)
{
case FMODEL_SPIKECOUNT:
if(tinybit_spikenumber>0)
xresult[ii][dataindex] = double(count(xindex,startindex,endindex,ii));
// test: xresult[ii][dataindex] = double(tinybit_spikenumber);
break;
case FMODEL_HOWMANYAREACTIVE:
if(tinybit_spikenumber>0)
xresult[ii][dataindex] = double(has_index(xindex,startindex,endindex,ii));
break;
case FMODEL_LEOGANG:
xresult[ii][dataindex] = (1.-double(tauImg)/tauCa)*xresult[ii][std::max(dataindex-1,long(0))] + \
DeltaCalciumOnAP*double(count(xindex,startindex,endindex,ii));
break;
// default:
// IOSTREAMC <<"error in generate_time_series_from_spike_data: invalid fluorescence model"<<IOSTREAMENDL;
// exit(1);
}
}
if(startindex <= endindex)
startindex = 1 + endindex;
dataindex++;
}
// apply saturation (Hill function of order 1 as usual)
if(fluorescence_saturation > 0.)
for (unsigned int ii=0; ii<size; ii++)
for (long tt=0; tt<samples; tt++)
xresult[ii][tt] = xresult[ii][tt]/(xresult[ii][tt]+fluorescence_saturation);
// apply additive noise term
if(std_noise > 0.)
{
// initialize random number generator
// gsl_rng* GSLrandom;
// gsl_rng_env_setup();
// GSLrandom = gsl_rng_alloc(GSL_RANDOM_NUMBER_GENERATOR);
// gsl_rng_set(GSLrandom, 1234);
for (unsigned int ii=0; ii<size; ii++)
for (long tt=0; tt<samples; tt++)
xresult[ii][tt] += gsl_ran_gaussian(GSLrandom,std_noise);
// free allocated memory
// gsl_rng_free(GSLrandom);
}
delete[] xindex;
delete[] xtimes;
return xresult;
};
unsigned long count(int* array, unsigned long starti, unsigned long endi, int what)
{
unsigned long occur = 0;
for (unsigned long i=starti; i<=endi; i++)
if (array[i] == what) occur++;
return occur;
};
bool has_index(int* array, unsigned long starti, unsigned long endi, int what)
{
for (unsigned long i=starti; i<=endi; i++)
if (array[i] == what) return true;
return false;
};
double smallest(const double* array, long length, rawdata* xglobal)
{
// double min = array[0];
// for (long i=1; i<length; i++)
double min = std::numeric_limits<double>::max();
for (long i=0; i<length; i++) {
if(xglobal == NULL || xglobal[i] == 0) {
if(array[i]<min) min = array[i];
// else std::cout <<"DEBUG: smallest skipped one."<<std::endl;
}
}
// if(xglobal != NULL) std::cout <<"DEBUG: smallest(...) = "<<min<<std::endl;
return min;
};
double largest(const double* array, long length, rawdata* xglobal)
{
// double max = array[0];
// for (long i=1; i<length; i++)
double max = -1.0 * std::numeric_limits<double>::max();
for (long i=0; i<length; i++) {
if(xglobal == NULL || xglobal[i] == 0) {
if(array[i]>max) max = array[i];
// else std::cout <<"DEBUG: largest skipped one."<<std::endl;
}
}
// if(xglobal != NULL) std::cout <<"DEBUG: largest(...) = "<<max<<std::endl;
return max;
};
rawdata smallest(const rawdata* array, long length)
{
rawdata min = array[0];
for (long i=1; i<length; i++)
if(array[i]<min) min = array[i];
return min;
};
rawdata largest(const rawdata* array, long length)
{
rawdata max = array[0];
for (long i=1; i<length; i++)
if(array[i]>max) max = array[i];
return max;
};
double smallest(const double** array, unsigned int size, long length)
{
double min = array[0][0];
for (unsigned int i=1; i<size; i++)
min = std::min(min,smallest(array[i],length));
return min;
};
double largest(const double** array, unsigned int size, long length)
{
double max = array[0][0];
for (unsigned int i=1; i<size; i++)
max = std::max(max,largest(array[i],length));
return max;
};
double total(const double* array, long length)
{
return total(array,0,length-1);
};
double total(const double* array, long first, long last)
{
if (last < first) return 0.;
if (first == last) return array[first];
double sum = 0.;
for (long i=first; i<=last; i++)
sum += array[i];
return sum;
};
double mean(const double* array, long first, long last)
{
if (last < first) return 0.;
if (first == last) return array[first];
return total(array,first,last)/double(last-first+1);
}
double mean(const double* array, const long length)
{
return mean(array,0,length-1);
};
double variance(const double* array, long first, long last)
{
if (last <= first) return 0.0;
double mu = mean(array, first, last);
double sum_of_squares = 0.0;
for(long i=first; i<=last; i++) {
sum_of_squares += (array[i] - mu) * (array[i] - mu);
}
return sum_of_squares/double(last-first+1);
}
double variance(const double* array, long length) {
return variance(array,0,length-1);
}
double standard_deviation(const double* array, long first, long last)
{
return sqrt( variance(array, first, last) );
}
double standard_deviation(const double* array, long length)
{
return standard_deviation(array,0,length-1);
}
double* generate_mean_time_series(double** const data, unsigned int size, long samples)
{
double* xglobaltemp = new double[samples];
memset(xglobaltemp, 0, samples*sizeof(double));
for (long t=0; t<samples; t++)
{
for (unsigned int ii=0; ii<size; ii++)
xglobaltemp[t] += data[ii][t];
xglobaltemp[t] /= size;
}
return xglobaltemp;
}
void free_time_series_memory(double** xresult, unsigned int size)
{
for(unsigned int ii=0; ii<size; ii++)
free_time_series_memory(xresult[ii]);
delete[] xresult;
};
void free_time_series_memory(double* xresult)
{
delete[] xresult;
};
void free_time_series_memory(rawdata** xresult, unsigned int size)
{
for(unsigned int ii=0; ii<size; ii++)
free_time_series_memory(xresult[ii]);
delete[] xresult;
};
void free_time_series_memory(rawdata* xresult)
{
delete[] xresult;
};
void display_subset(const double* data, const int length, IOSTREAMH)
{
// IOSTREAMC <<"displaying some subset of data points:"<<IOSTREAMENDL;
IOSTREAMC <<"{";
for (long t=0; t<length; t++)
{
if (t>0) IOSTREAMC <<",";
IOSTREAMC <<data[t];
}
IOSTREAMC <<"} (range "<<smallest(data,length)<<" – "<<largest(data,length)<<")"<<IOSTREAMENDL;
};
void display_subset(const rawdata* data, const int length, IOSTREAMH)
{
// IOSTREAMC <<"displaying some subset of data points:"<<IOSTREAMENDL;
IOSTREAMC <<"{";
for (long t=0; t<length; t++)
{
if (t>0) IOSTREAMC <<",";
IOSTREAMC <<int(data[t]);
}
IOSTREAMC <<"} (range "<<int(smallest(data,length))<<" – "<<int(largest(data,length))<<")"<<IOSTREAMENDL;
};
int Magic_GuessBinNumber(double** const data, const unsigned int size, const long samples)
{
double range, std;
double meanbins = 0.;
for(unsigned int i=0; i<size; i++)
{
range = largest(data[i],samples)-smallest(data[i],samples);
assert(range > 0.);
std = sqrt(gsl_stats_variance(data[i],1,samples));
meanbins += 1*range/std; // old code: 2*std/range
}
meanbins /= size;
cout <<"debug: meanbins = "<<meanbins<<endl;
return std::max(2,int(round(meanbins)));
// return std::max(2,int(meanbins));
};
double Magic_GuessConditioningLevel(double** const data, const unsigned int size, const long samples, IOSTREAMH)
{
int histo_bins = int(std::max(4.,std::min(200.,sqrt(samples))));
IOSTREAMC <<" -> number of bins for histogram: "<<histo_bins<<IOSTREAMENDL;
double xmeanmin, xmeanmax;
double xresultlevel = -1.;
double* xmean = generate_mean_time_series(data,size,samples);
xmeanmin = smallest(xmean,samples);
xmeanmax = largest(xmean,samples);
// IOSTREAMC <<"-> xmeanmin = "<<xmeanmin<<", xmeanmax = "<<xmeanmax<<IOSTREAMENDL;
// IOSTREAMC <<" -> beginning of <f>: "<<IOSTREAMENDL;
// display_subset(xmean,5,IOSTREAMV);
// find maximum, which we assume comes from the noise peak
double x_ymax = Util_FindPeakInHistogram(xmean,samples,xmeanmin,xmeanmax,histo_bins);
IOSTREAMC <<" -> identified peak at <f> = "<<x_ymax<<IOSTREAMENDL;
// for(int i=0; i<histo_bins; i++)
// IOSTREAMC <<"histo <f> = "<<xmeanmin+(double(i)+0.5)*(xmeanmax-xmeanmin)/double(histo_bins)<<": count = "<<histo[i]<<IOSTREAMENDL;
// PlotHistogramInASCII(xmean,samples,xmeanmin,x_ymax+0.1,"<f>","#(<f>)",IOSTREAMV);
IOSTREAMC <<IOSTREAMENDL<<" -> log histogram of complete range of <f>:"<<IOSTREAMENDL;
PlotLogHistogramInASCII(xmean,samples,xmeanmin,xmeanmax,"<f>","log #(<f>)",IOSTREAMV);
// IOSTREAMC <<IOSTREAMENDL<<" -> log histogram of the right tail of <f>:"<<IOSTREAMENDL;
// PlotLogHistogramInASCII(xmean,samples,x_ymax,xmeanmax,"log <f>","log #(<f>)",IOSTREAMV);
IOSTREAMC <<IOSTREAMENDL<<" -> log-log histogram of the right tail of <f>:"<<IOSTREAMENDL;
PlotLogLogHistogramInASCII(xmean,samples,x_ymax,xmeanmax,"log <f>","log #(<f>)",IOSTREAMV);
// re-sample right tail of histogram (new method)
double *x = NULL;
double *y = NULL;
double *w = NULL;
double c0,c1,cov00,cov01,cov11,chisq;
const long nr_observations = long(0.2*round(sqrt(samples)));
Util_CreateFakeLogLogHistogram(&x,&y,&w,xmean,samples,x_ymax,xmeanmax,nr_observations);
// make linear weighted fit using GSL
gsl_fit_wlinear(x,1,w,1,y,1,nr_observations,&c0,&c1,&cov00,&cov01,&cov11,&chisq);
IOSTREAMC <<" -> best fit: y(x) = "<<c0<<" + ("<<c1<<")*x; (chisq = "<<chisq<<")"<<IOSTREAMENDL;
// IOSTREAMC <<"vectorxy = ";
// Util_CoordinatedForMathematica(x,y,nr_observations,IOSTREAMV);
// IOSTREAMC <<"vectorxw = ";
// Util_CoordinatedForMathematica(x,w,nr_observations,IOSTREAMV);
// IOSTREAMC <<"c0 = "<<c0<<";"<<IOSTREAMENDL;
// IOSTREAMC <<"c1 = "<<c1<<";"<<IOSTREAMENDL<<IOSTREAMENDL;
// tranforming everything back to linear space (where the line in log-log corresponds
// to the power-law fit we wanted)
IOSTREAMC <<" -> transforming back to linear space:"<<IOSTREAMENDL;
for(int i=0; i<nr_observations; i++)
{