-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathImage.cpp
More file actions
2275 lines (2061 loc) · 65.3 KB
/
Image.cpp
File metadata and controls
2275 lines (2061 loc) · 65.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <unistd.h> // for sysconf ()
#include <memory>
#include <limits.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/time.h> // for debug time interval
#include <fcntl.h>
#include <libgen.h>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <limits>
#include "MathOptim.h"
#include "IonErr.h"
#include "Image.h"
#include "SampleStats.h"
#include "sgfilter/SGFilter.h"
#include "Histogram.h"
#include "Utils.h"
#include "deInterlace.h"
#include "LinuxCompat.h"
#include "ChipIdDecoder.h"
#include "LSRowImageProcessor.h"
#include "dbgmem.h"
#include "PinnedWellReporter.h"
using namespace std;
//Initialize chipSubRegion in Image class
Region Image::chipSubRegion = {0,0,0,0};
// this is perhaps a prime candidate for something that is a json set of parameters to read in
// inversion vector + coordinates of the offsets
// we do only a single pass because the second-order correction is too small to notice
#define DEFAULT_VECT_LEN 7
static float chan_xt_vect_316[DEFAULT_VECT_LEN] = {0.0029,-0.0632,-0.0511,1.1114,0.0000,0.0000,0.0000};
static float *default_316_xt_vectors[] = {chan_xt_vect_316};
static float chan_xt_vect_318_even[DEFAULT_VECT_LEN] = {0.0132,-0.1511,-0.0131,1.1076,0.0404,0.0013,0.0018};
static float chan_xt_vect_318_odd[DEFAULT_VECT_LEN] = {0.0356,-0.1787,-0.1732,1.3311,-0.0085,-0.0066,0.0001};
static float *default_318_xt_vectors[] = {chan_xt_vect_318_even, chan_xt_vect_318_even,chan_xt_vect_318_even, chan_xt_vect_318_even,
chan_xt_vect_318_odd, chan_xt_vect_318_odd,chan_xt_vect_318_odd, chan_xt_vect_318_odd
};
int Image::chan_xt_column_offset[DEFAULT_VECT_LEN] = {-12,-8,-4,0,4,8,12};
ChipXtVectArrayType Image::default_chip_xt_vect_array[] =
{
{ChipId316, {default_316_xt_vectors, 1, DEFAULT_VECT_LEN, chan_xt_column_offset} },
{ChipId318, {default_318_xt_vectors, 8, DEFAULT_VECT_LEN, chan_xt_column_offset} },
{ChipIdUnknown, {NULL, 0,0,NULL} },
};
ChannelXTCorrectionDescriptor Image::selected_chip_xt_vectors = {NULL, 0,0,NULL};
// default constructor
Image::Image()
{
results = NULL;
raw = new RawImage;
memset (raw,0,sizeof (*raw));
maxFrames = 0;
// set up the default SG-Filter class
// MGD note - may want to ensure this becomes thread-safe or create one per region/thread
sgSpread = 2;
sgCoeff = 1;
sgFilter = new SGFilter();
sgFilter->SetFilterParameters (sgSpread, sgCoeff);
experimentName = NULL;
flowOffset = 1000;
bkg = NULL;
retry_interval = 15; // 15 seconds wait time.
total_timeout = 36000; // 10 hours before giving up.
numAcqFiles = 0; // total number of acq files in the dataset
recklessAbandon = true; // false: use file availability testing during loading
ignoreChecksumErrors = 0;
dump_XTvects_to_file = 1;
}
Image::~Image()
{
cleanupRaw();
delete raw;
delete sgFilter;
if (results)
delete [] results;
if (experimentName)
free (experimentName);
if (bkg)
free (bkg);
}
void Image::Close()
{
cleanupRaw();
if (results)
delete [] results;
results = NULL;
if (bkg)
free (bkg);
bkg = NULL;
maxFrames = 0;
}
void Image::cleanupRaw()
{
if (raw->image)
{
free (raw->image);
raw->image = NULL;
}
if (raw->timestamps)
{
free (raw->timestamps);
raw->timestamps = NULL;
}
if (raw->interpolatedFrames)
{
free (raw->interpolatedFrames);
raw->interpolatedFrames = NULL;
}
if (raw->interpolatedMult)
{
free (raw->interpolatedMult);
raw->interpolatedMult = NULL;
}
memset (raw,0,sizeof (*raw));
}
//@TODO: this function has become unwieldy and needs refactoring.
bool Image::LoadSlice (
vector<string> rawFileName,
vector<unsigned int> col,
vector<unsigned int> row,
int minCol,
int maxCol,
int minRow,
int maxRow,
bool returnSignal,
bool returnMean,
bool returnSD,
bool returnLag,
bool uncompress,
bool doNormalize,
int normStart,
int normEnd,
bool XTCorrect,
double baselineMinTime,
double baselineMaxTime,
double loadMinTime,
double loadMaxTime,
unsigned int &nColFull,
unsigned int &nRowFull,
vector<unsigned int> &colOut,
vector<unsigned int> &rowOut,
unsigned int &nFrame,
vector< vector<double> > &frameStart,
vector< vector<double> > &frameEnd,
vector< vector< vector<short> > > &signal,
vector< vector<short> > &mean,
vector< vector<short> > &sd,
vector< vector<short> > &lag
)
{
// Determine how many wells are sought
unsigned int nSavedWells=0;
bool cherryPickWells=false;
if (col.size() > 0 || row.size() > 0)
{
if (row.size() != col.size())
{
cerr << "number of requested rows and columns should be the same" << endl;
return (false);
}
nSavedWells = col.size();
cherryPickWells=true;
// Figure out min & max cols to load less data
minCol = col[0];
maxCol = minCol+1;
minRow = row[0];
maxRow = minRow+1;
for (unsigned int iWell=1; iWell < col.size(); iWell++)
{
if (col[iWell] < (unsigned int) minCol)
minCol = col[iWell];
if (col[iWell] >= (unsigned int) maxCol)
maxCol = 1+col[iWell];
if (row[iWell] < (unsigned int) minRow)
minRow = row[iWell];
if (row[iWell] >= (unsigned int) maxRow)
maxRow = 1+row[iWell];
}
}
// Read header to determine full-chip rows & cols
if (!LoadRaw (rawFileName[0].c_str(), 0, true, true))
{
cerr << "Problem loading dat file " << rawFileName[0] << endl;
return (false);
}
nColFull = raw->cols;
nRowFull = raw->rows;
// This next block of ugliness will not be needed when we encode the chip type in the dat file
char *chipID = NULL;
if (nColFull == 1280 && nRowFull == 1152)
{
chipID = strdup ("314");
}
else if (nColFull == 2736 && nRowFull == 2640)
{
chipID = strdup ("316");
}
else if (nColFull == 3392 && nRowFull == 3792)
{
chipID = strdup ("318");
}
else
{
ION_WARN ("Unable to determine chip type from dimensions");
}
// Only allow for XTCorrection on 316 and 318 chips
if (XTCorrect)
{
if ( (chipID == NULL) || (strcmp (chipID,"318") && strcmp (chipID,"316")))
{
XTCorrect = false;
}
}
// Variables to handle cases where we need to expand for proper
// XTCorrection at boundaries
int minColOuter;
int maxColOuter;
int minRowOuter;
int maxRowOuter;
if (minCol > -1 || minRow > -1 || maxCol > -1 || maxRow > -1)
{
// First do a few boundary checks
bool badBoundary=false;
if (minCol >= (int) nColFull)
{
cerr << "Error in Image::LoadSlice() - minCol is " << minCol << " which should be less than nColFull which is " << nColFull << endl;
badBoundary=true;
}
if (maxCol <= 0)
{
cerr << "Error in Image::LoadSlice() - maxCol is " << maxCol << " which is less than 1" << endl;
badBoundary=true;
}
if (minCol >= maxCol)
{
cerr << "Error in Image::LoadSlice() - maxCol is " << maxCol << " which is not greater than minCol which is " << minCol << endl;
badBoundary=true;
}
if (minRow >= (int) nRowFull)
{
cerr << "Error in Image::LoadSlice() - minRow is " << minRow << " which should be less than nRowFull which is " << nRowFull << endl;
badBoundary=true;
}
if (maxRow <= 0)
{
cerr << "Error in Image::LoadSlice() - maxRow is " << maxRow << " which is less than 1" << endl;
badBoundary=true;
}
if (minRow >= maxRow)
{
cerr << "Error in Image::LoadSlice() - maxRow is " << maxRow << " which is not greater than minRow which is " << minRow << endl;
badBoundary=true;
}
if (badBoundary)
return (false);
// Expand boundaries as necessary for XTCorrection
minColOuter = minCol;
maxColOuter = maxCol;
minRowOuter = minRow;
maxRowOuter = maxRow;
if (XTCorrect)
{
minColOuter = std::max (0, minCol + chan_xt_column_offset[0]);
maxColOuter = std::min ( (int) nColFull, maxCol + chan_xt_column_offset[DEFAULT_VECT_LEN-1]);
}
}
else
{
if (minCol < 0)
minCol = 0;
if (minRow < 0)
minRow = 0;
if (maxCol < 0)
maxCol = nColFull;
if (maxRow < 0)
maxRow = nRowFull;
minColOuter = minCol;
maxColOuter = maxCol;
minRowOuter = minRow;
maxRowOuter = maxRow;
}
// Set up Image class to read only the sub-range
chipSubRegion.col = minColOuter;
chipSubRegion.row = minRowOuter;
chipSubRegion.w = maxColOuter-minColOuter;
chipSubRegion.h = maxRowOuter-minRowOuter;
// Set region origin for proper XTCorrection
SetCroppedRegionOrigin (minColOuter,minRowOuter);
unsigned int nPrevCol=0;
unsigned int nPrevRow=0;
unsigned int nPrevFramesCompressed=0;
unsigned int nPrevFramesUncompressed=0;
unsigned int nDat = rawFileName.size();
bool problem = false;
int *uncompressedTimestamps = NULL;
vector<unsigned int> wellIndex;
vector< vector<SampleStats<float> > > signalStats;
vector< vector<SampleStats<float> > > lagStats;
for (unsigned int iDat=0; iDat < nDat; iDat++)
{
if (!LoadRaw (rawFileName[iDat].c_str(), 0, true, false))
{
cerr << "Problem loading dat file " << rawFileName[iDat] << endl;
return (false);
}
unsigned int nCol = raw->cols;
unsigned int nRow = raw->rows;
// We normalize if asked
if (doNormalize)
{
Normalize (normStart,normEnd);
}
// cross-channel correction
if (XTCorrect)
{
Mask tempMask (raw->cols, raw->rows);
if (chipID != NULL)
{
ChipIdDecoder::SetGlobalChipId (chipID);
CalibrateChannelXTCorrection (rawFileName[iDat].c_str(),"lsrowimage.dat");
XTChannelCorrect (&tempMask);
}
}
unsigned int nLoadedWells = nRow * nCol;
unsigned int nFramesCompressed = raw->frames;
unsigned int nFramesUncompressed = raw->uncompFrames;
if (iDat==0)
{
nPrevCol=nCol;
nPrevRow=nRow;
nPrevFramesCompressed=nFramesCompressed;
nPrevFramesUncompressed=nFramesUncompressed;
// Size the return objects depending on whether or not we're returning compressed data
if (uncompress)
{
nFrame = nFramesUncompressed;
}
else
{
nFrame = nFramesCompressed;
}
frameStart.resize (nDat);
frameEnd.resize (nDat);
for (unsigned int jDat=0; jDat<nDat; jDat++)
{
frameStart[jDat].resize (nFrame);
frameEnd[jDat].resize (nFrame);
}
if (!cherryPickWells)
{
// If not using a specified set of row,col coordinates then return a rectangular region
nSavedWells = (maxCol-minCol) * (maxRow-minRow);
}
if (returnSignal)
{
signal.resize (nDat);
for (unsigned int jDat=0; jDat<nDat; jDat++)
{
signal[jDat].resize (nSavedWells);
// Will resize for number of frames to return later, when that has been determined
}
}
if (returnMean)
{
mean.resize (nDat);
for (unsigned int jDat=0; jDat<nDat; jDat++)
{
mean[jDat].resize (nSavedWells);
}
}
if (returnSD)
{
sd.resize (nDat);
for (unsigned int jDat=0; jDat<nDat; jDat++)
{
sd[jDat].resize (nSavedWells);
}
}
if (returnLag)
{
lag.resize (nDat);
for (unsigned int jDat=0; jDat<nDat; jDat++)
{
lag[jDat].resize (nSavedWells);
}
}
if (returnMean || returnSD)
{
signalStats.resize (nDat);
for (unsigned int jDat=0; jDat<nDat; jDat++)
{
signalStats[jDat].resize (nSavedWells);
}
}
if (returnLag)
{
lagStats.resize (nDat);
for (unsigned int jDat=0; jDat<nDat; jDat++)
{
lagStats[jDat].resize (nSavedWells);
}
}
}
else
{
if (nCol != nPrevCol)
{
cerr << "Dat file " << rawFileName[iDat] << " has different number of cols to first dat file " << rawFileName[0] << endl;
return (false);
}
if (nRow != nPrevRow)
{
cerr << "Dat file " << rawFileName[iDat] << " has different number of rows to first dat file " << rawFileName[0] << endl;
return (false);
}
if (nFramesCompressed != nPrevFramesCompressed)
{
cerr << "Dat file " << rawFileName[iDat] << " has different number of compressed frames to first dat file " << rawFileName[0] << endl;
return (false);
}
if (nFramesUncompressed != nPrevFramesUncompressed)
{
cerr << "Dat file " << rawFileName[iDat] << " has different number of uncompressed frames to first dat file " << rawFileName[0] << endl;
return (false);
}
}
// Determine well offsets to collect
if (iDat==0)
{
wellIndex.resize (nSavedWells);
colOut.resize (nSavedWells);
rowOut.resize (nSavedWells);
if (cherryPickWells)
{
for (unsigned int iWell=0; iWell < nSavedWells; iWell++)
{
wellIndex[iWell] = (row[iWell]-minRowOuter) *nCol + (col[iWell]-minColOuter);
colOut[iWell] = col[iWell];
rowOut[iWell] = row[iWell];
}
}
else
{
for (unsigned int iWell=0, iRow=minRow; iRow < (unsigned int) maxRow; iRow++)
{
for (unsigned int iCol=minCol; iCol < (unsigned int) maxCol; iCol++, iWell++)
{
wellIndex[iWell] = (iRow-minRowOuter) *nCol + (iCol-minColOuter);
colOut[iWell] = iCol;
rowOut[iWell] = iRow;
}
}
}
}
// Check if we need to uncompress
// Make rawTimestamps point to the timestamps we need to report
int *rawTimestamps = NULL;
if (iDat==0 && uncompress && (nFramesUncompressed != nFramesCompressed))
{
int baseTime = raw->timestamps[0];
uncompressedTimestamps = new int[sizeof (int) * nFramesUncompressed];
uncompressedTimestamps[0] = 0;
for (int iFrame=1; iFrame < raw->uncompFrames; iFrame++)
uncompressedTimestamps[iFrame] = baseTime+uncompressedTimestamps[iFrame-1];
rawTimestamps = uncompressedTimestamps;
}
else
{
rawTimestamps = raw->timestamps;
}
// Determine timeframe starts & stops
bool oldMode = (rawTimestamps[0]==0);
for (unsigned int iFrame=0; iFrame<nFrame; iFrame++)
{
if (oldMode)
{
frameStart[iDat][iFrame] = rawTimestamps[iFrame] / FRAME_SCALE;
if (iFrame < nFrame-1)
frameEnd[iDat][iFrame] = ( (double) rawTimestamps[iFrame+1]) / FRAME_SCALE;
else if (iFrame > 0)
frameEnd[iDat][iFrame] = (2.0 * (double) rawTimestamps[iFrame] - (double) rawTimestamps[iFrame-1]) / FRAME_SCALE;
else
frameEnd[iDat][iFrame] = 0;
}
else
{
frameEnd[iDat][iFrame] = ( (double) rawTimestamps[iFrame]) / FRAME_SCALE;
frameStart[iDat][iFrame] = ( (double) ( (iFrame > 0) ? rawTimestamps[iFrame-1] : 0)) / FRAME_SCALE;
}
}
// Determing per-well baseline values to subtract
bool doBaseline=false;
int baselineMinFrame = -1;
int baselineMaxFrame = -1;
std::vector<double> baselineWeight;
if (baselineMinTime < baselineMaxTime)
{
double baselineWeightSum = 0;
for (unsigned int iFrame=0; iFrame < nFrame; iFrame++)
{
if ( (frameStart[iDat][iFrame] > (baselineMinTime-numeric_limits<double>::epsilon())) && frameEnd[iDat][iFrame] < (baselineMaxTime+numeric_limits<double>::epsilon()))
{
// frame is in our baseline timeframe
if (baselineMinFrame < 0)
baselineMinFrame = iFrame;
baselineMaxFrame = iFrame;
baselineWeight.push_back (frameEnd[iDat][iFrame]-frameStart[iDat][iFrame]);
baselineWeightSum += frameEnd[iDat][iFrame]-frameStart[iDat][iFrame];
}
}
if (baselineWeightSum > 0)
{
unsigned int nBaselineFrame = baselineWeight.size();
for (unsigned int iFrame=0; iFrame < nBaselineFrame; iFrame++)
baselineWeight[iFrame] /= baselineWeightSum;
doBaseline=true;
}
}
vector<double> baselineVal;
short bVal=0;
if (doBaseline)
{
baselineVal.resize (nSavedWells,0);
for (unsigned int iWell=0; iWell < nSavedWells; iWell++)
{
for (int iFrame=baselineMinFrame; iFrame <= baselineMaxFrame; iFrame++)
{
if (uncompress)
bVal = GetInterpolatedValue (iFrame, colOut[iWell]-minColOuter, rowOut[iWell]-minRowOuter);
else
bVal = raw->image[iFrame * nLoadedWells + wellIndex[iWell]];
baselineVal[iWell] += baselineWeight[iFrame-baselineMinFrame] * bVal;
}
}
}
// Determine which frames to return
int loadMinFrame = 0;
int loadMaxFrame = nFrame;
unsigned int nLoadFrame = nFrame;
bool loadFrameSubset=false;
if (loadMinTime < loadMaxTime)
{
loadMinFrame = -1;
for (unsigned int iFrame=0; iFrame < nFrame; iFrame++)
{
if ( (frameStart[iDat][iFrame] > (loadMinTime-numeric_limits<double>::epsilon())) && frameEnd[iDat][iFrame] < (loadMaxTime+numeric_limits<double>::epsilon()))
{
if (loadMinFrame < 0)
loadMinFrame = iFrame;
loadMaxFrame = iFrame+1;
}
}
if (loadMinFrame == -1)
{
cerr << "Image::LoadSlice - no frames found in requested timeframe\n";
problem=true;
break;
}
else
{
nLoadFrame = loadMaxFrame-loadMinFrame;
loadFrameSubset=true;
}
}
// resize return signal object
if (returnSignal)
{
for (unsigned int iWell=0; iWell < nSavedWells; iWell++)
signal[iDat][iWell].resize (nLoadFrame);
}
// subset frameStart/frameEnd for frame range requested
if (loadFrameSubset)
{
if (loadMaxFrame < (int) nFrame)
{
unsigned int nToDrop = nFrame - loadMaxFrame;
frameStart[iDat].erase (frameStart[iDat].end()-nToDrop,frameStart[iDat].end());
frameEnd[iDat].erase (frameEnd[iDat].end()-nToDrop,frameEnd[iDat].end());
}
if (loadMinFrame > 0)
{
unsigned int nToDrop = loadMinFrame+1;
frameStart[iDat].erase (frameStart[iDat].begin(),frameStart[iDat].begin() +nToDrop);
frameEnd[iDat].erase (frameEnd[iDat].begin(),frameEnd[iDat].begin() +nToDrop);
}
}
short val=0;
for (unsigned int iWell=0; iWell < nSavedWells; iWell++)
{
// do frames
short oldval =0;
for (int iFrame=loadMinFrame; iFrame < loadMaxFrame; iFrame++)
{
if (uncompress)
val = GetInterpolatedValue (iFrame, colOut[iWell]-minColOuter, rowOut[iWell]-minRowOuter);
else
val = raw->image[iFrame * nLoadedWells + wellIndex[iWell]];
if (doBaseline)
{
val = (short) ( (double) val - baselineVal[iWell]);
}
if (returnSignal)
signal[iDat][iWell][iFrame-loadMinFrame] = val;
if (returnMean || returnSD)
signalStats[iDat][iWell].AddValue ( (float) val);
if (returnLag & (iFrame>loadMinFrame))
lagStats[iDat][iWell].AddValue ( (float) (val-oldval));
oldval = val;
}
}
for (unsigned int iWell=0; iWell < nSavedWells; iWell++)
{
if (returnMean)
{
mean[iDat][iWell] = (short) (signalStats[iDat][iWell].GetMean());
}
if (returnSD)
{
sd[iDat][iWell] = (short) (signalStats[iDat][iWell].GetSD());
}
if (returnLag)
{
lag[iDat][iWell] = (short) (lagStats[iDat][iWell].GetSD()); // sd on lagged signal
}
}
cleanupRaw();
}
if (chipID != NULL)
free (chipID);
if (uncompressedTimestamps != NULL)
delete [] uncompressedTimestamps;
if (problem)
return (false);
else
return (true);
};
//
// LoadRaw
// loads raw image data for one experiment, and byte-swaps as appropriate
// returns a structure with header data and a pointer to the allocated image data with timesteps removed
//
bool Image::LoadRaw (const char *rawFileName, int frames, bool allocate, bool headerOnly)
{
// _file_hdr hdr;
// int offset=0;
int rc;
(void) allocate;
cleanupRaw();
//set default name only if not already set
if (!experimentName)
{
experimentName = (char *) malloc (3);
strncpy (experimentName, "./", 3);
}
//DEBUG: monitor file access time
struct timeval tv;
double startT;
double stopT;
gettimeofday (&tv, NULL);
startT = (double) tv.tv_sec + ( (double) tv.tv_usec/1000000);
FILE *fp = NULL;
if (recklessAbandon)
{
fopen_s (&fp, rawFileName, "rb");
}
else // Try open and wait until open or timeout
{
uint32_t waitTime = retry_interval;
int32_t timeOut = total_timeout;
//--- Wait up to 3600 seconds for a file to be available
while (timeOut > 0)
{
//--- Is the file we want available?
if (ReadyToLoad (rawFileName))
{
//--- Open the file we want
fopen_s (&fp, rawFileName, "rb");
break; // any error will be reported below
}
//DEBUG
fprintf (stdout, "Waiting to load %s\n", rawFileName);
sleep (waitTime);
timeOut -= waitTime;
}
}
if (fp == NULL)
{
perror (rawFileName);
return false;
}
printf ("Loading raw file: %s...\n", rawFileName);
fflush (stdout);
// size_t rdSize;
fclose (fp);
raw->channels = 4;
raw->interlaceType = 0;
raw->image = NULL;
if (frames)
raw->frames = frames;
if (headerOnly)
{
rc = deInterlace_c ( (char *) rawFileName,NULL,NULL,
&raw->rows,&raw->cols,&raw->frames,&raw->uncompFrames,
0,0,chipSubRegion.col,chipSubRegion.row,chipSubRegion.col+chipSubRegion.w,chipSubRegion.row+chipSubRegion.h,ignoreChecksumErrors);
}
else
{
rc = deInterlace_c ( (char *) rawFileName,&raw->image,&raw->timestamps,
&raw->rows,&raw->cols,&raw->frames,&raw->uncompFrames,
0,0,chipSubRegion.col,chipSubRegion.row,chipSubRegion.col+chipSubRegion.w,chipSubRegion.row+chipSubRegion.h,ignoreChecksumErrors);
if (chipSubRegion.h != 0)
raw->rows = chipSubRegion.h;
if (chipSubRegion.w != 0)
raw->cols = chipSubRegion.w;
raw->baseFrameRate=raw->timestamps[0];
if (raw->baseFrameRate == 0)
raw->baseFrameRate=raw->timestamps[1];
if (raw->uncompFrames != raw->frames)
{
// create a temporary set of timestamps that indicate the centroid of each averaged data point
// from the ones in the file (which indicate the end of each data point)
float *centr_timestamps = (float *) malloc (sizeof (float) *raw->frames);
float last_timestamp = 0.0;
for (int j=0;j<raw->frames;j++)
{
centr_timestamps[j] = (raw->timestamps[j] + last_timestamp) /2.0;
last_timestamp = raw->timestamps[j];
}
raw->interpolatedFrames = (int *) malloc (sizeof (int) *raw->uncompFrames);
raw->interpolatedMult = (float *) malloc (sizeof (float) *raw->uncompFrames);
for (int i=0;i<raw->uncompFrames;i++)
{
int curTime=raw->baseFrameRate*i;
int prevTime,nextTime;
if (curTime > centr_timestamps[raw->frames-1])
{
// the last several points must actually be extrapolated
nextTime = centr_timestamps[raw->frames-1];
prevTime = centr_timestamps[raw->frames-2];
raw->interpolatedFrames[i] = raw->frames-1;
raw->interpolatedMult[i] = (float) (nextTime-curTime) / (float) (nextTime-prevTime);
}
else
for (int j=0;j<raw->frames;j++)
{
if (centr_timestamps[j] >= curTime)
{
nextTime = centr_timestamps[j];
if (j)
prevTime = centr_timestamps[j-1];
else
prevTime = 0;
raw->interpolatedFrames[i] = j;
raw->interpolatedMult[i] = (float) (nextTime-curTime) / (float) (nextTime-prevTime);
break;
}
}
}
free (centr_timestamps);
}
}
raw->frameStride = raw->rows * raw->cols;
printf ("Loading raw file: %s...done\n", rawFileName);
if (rc && raw->timestamps)
{
uint32_t prev = 0;
float avgTimestamp = 0;
double fps;
// read the raw data, and convert it into image data
int i;
for (i=0;i<raw->frames;i++)
{
avgTimestamp += (raw->timestamps[i] - prev);
prev = raw->timestamps[i];
}
avgTimestamp = avgTimestamp / (raw->frames - 1); // milliseconds
fps = (1000.0/avgTimestamp); // convert to frames per second
// Subtle hint to users of "old" cropped datasets that did not have real timestamps written
/*if (rint(fps) == 10) {
fprintf (stdout, "\n\nWARNING: if this is a cropped dataset, it may have incorrect frame timestamp!\n");
fprintf (stdout, "Your results will not be valid\n\n");
}*/
//DEBUG
fprintf (stdout, "Avg Image Time = %f ", avgTimestamp);
fprintf (stdout, "Frames = %d ", raw->frames);
fprintf (stdout, "FPS = %f\n", fps);
gettimeofday (&tv, NULL);
stopT = (double) tv.tv_sec + ( (double) tv.tv_usec/1000000);
fprintf (stdout, "File access = %0.2lf sec.\n", stopT - startT);
fflush (stdout);
}
ReportPinnedWells (std::string (rawFileName));
return true;
}
void Image::ReportPinnedWells (const std::string& strDatFileName)
{
// Create a PinnedWellReporter object instance.
// To disable the reporter, pass false into Instance()
// by calling PinnedWellReporter::Instance( false ).
//
// Note: If PinnedWellReporter::Instance() is called before this
// call, below, then the state, either enabled or disabled, is already
// set and cannot be changed for the life of the application.
//
// For example, this call to Instance() passes false to disable
// this instance. However, if a previous call to Instance was
// made before this call to Instance(), then the enable/disable state
// of the previous call is used. This is because the enable/disable
// state is stored in a private static flag that is set on the first call to
// PinnedWellReporter::Instance(). Any subsequent calls to Instance()
// will not change the enable/disable state.
//
// Therefore, to enable PinnedWellReporter::Instance(), be sure
// to call Instance() early on, preferrably in main() so that there
// will be no mysteries as to why the PinnedWellReporter is or is not
// working.
PWR::PinnedWellReporter& pwr = *PWR::PinnedWellReporter::Instance (false);
// Do only if the well is pinned and the reporter object is enabled.
if (PWR::PinnedWellReporter::IsEnabled())
{
// Pinned value constants.
const int PIN_LOW_VALUE = 0;
const int PIN_HIGH_VALUE = 0x3fff;
// Linear position index into the raw->image array.
int i = 0;
// Do for each row in the well matrix.
for (int y = 0; y < raw->rows; y++)
{
// Do for each column in the well matrix.
for (int x = 0; x < raw->cols; x++)
{
// Accumulate data for well x,y here...
PWR::PinnedWell pinnedWell;
// Count of pinned frames in this well.
int numPinnedFramesInWell = 0;
// Is this frame pinned?
bool bIsPinned = false;
// Assume a pinned low state
PWR::PinnedWellReporter::PinnedStateEnum pinnedState
= PWR::PinnedWellReporter::LOW;
// Do for each frame in this well.
for (int frame = 0; frame < raw->frames; frame++)
{
// Pre-calculate the index into the image.
const int iImgIndex = frame * raw->frameStride + i;
// Do if the value is pinned.
if (PIN_LOW_VALUE == raw->image[iImgIndex]
|| PIN_HIGH_VALUE == raw->image[iImgIndex])
{
// This pixel value is pinned either high or low.
bIsPinned = true;
// Accumulate the number of pinned frames in this well.
numPinnedFramesInWell++;
// If pinned high, then set the state accordingly.
if (PIN_HIGH_VALUE == raw->image[iImgIndex])
pinnedState = PWR::PinnedWellReporter::HIGH;
}
} // END for( int frame = 0; frame < raw->frames; frame++ )
// Do only if this frame is pinned.
if (bIsPinned)
{
// Calculate the value in this frame.
unsigned int valueInFrame = raw->image[i];
// Accumulate information at this well.
pinnedWell.Add (x, y, valueInFrame, pinnedState);
} // END if( bIsPinned )
// Add the pinned well data into the reporter instance.
pwr.Write (strDatFileName, pinnedWell, numPinnedFramesInWell);
// Increment the linear position index
i++;
} // END for( int x = 0; x < raw->cols; x++ )
} // END for( int y = 0; y < raw->rows; y++ )
} // END if( PWR::PinnedWellReporter::IsEnabled() )
} // END Image::ReportedFilterForPinned()
void Image::SetDir (char *directory)
{
if (experimentName)
free (experimentName);
experimentName = (char *) malloc (strlen (directory) + 1);
strncpy (experimentName, directory, strlen (directory) + 1);
return;
}
int Image::FilterForPinned (Mask *mask, MaskType these, int markBead)
{
printf ("Filtering for pinned pixels.\n");
int x, y, frame;
int pinnedCount = 0;
int i = 0;
for (y=0;y<raw->rows;y++)
{
for (x=0;x<raw->cols;x++)
{
if ( (*mask) [i] & these)
{
for (frame=0;frame<raw->frames;frame++)
{
if (raw->image[frame*raw->frameStride + i] == 0 ||
raw->image[frame*raw->frameStride + i] == 0x3fff)