-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathacquire.cpp
1568 lines (1284 loc) · 59 KB
/
acquire.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 (c) 2017 XIA LLC
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
* * Neither the name of XIA LLC
* nor the names of its contributors may be used to endorse
* or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*----------------------------------------------------------------------*/
#define __STDC_FORMAT_MACROS
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <inttypes.h>
#include <sys/mman.h>
#include <sys/file.h>
#include <math.h>
#include <stdint.h>
// need to compile with -lm option
#include <fstream>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/atomic.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/lockfree/queue.hpp>
#include <boost/program_options.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include "PixieNetDefs.h"
#include "PixieNetConfig.h"
extern "C" {
#include "PixieNetCommon.h"
}
using namespace std;
//compile options to speed up processing
#define PixieNetHit_HAS_WAVEFORM 1 // optionally suppress waveforms
#define PixieNetHit_RECORD_HIT_PSA 1 // optionally ignore PSA results
#define MAX_ACQ_TL 512 // set limit for waveforms length (abs max: 4092)
#define SUMMCA 1 //
#define MAX_QUEUED 100000
/* ********************************************************************************
********************************************************************************
********************************************************************************
* DECLARATIONS
********************************************************************************
******************************************************************************** */
/* typedef struct PixieNetHit400 {
uint8_t channel;
uint32_t hit;
uint32_t timeH;
uint32_t timeL;
uint16_t energy;
#if( PixieNetHit_RECORD_HIT_PSA )
uint32_t psa0;
uint32_t psa1;
uint32_t cfd0;
uint32_t cfd1;
#endif
#if( PixieNetHit_HAS_WAVEFORM )
uint16_t num_waveform; //Lockless queue can not be used with non-trivial constructor, so can't use a vector.
uint16_t waveform[MAX_TL]; //max size of MAX_TL (4092)
uint16_t NumCurrTraceBlks; // number of trace blocks
uint16_t NumPrevTraceBlks; // number of trace blocks
#endif
} PixieNetHit400;//struct PixieNetHit400
*/
typedef struct PixieNetHit402 {
uint8_t channel;
uint32_t hit;
uint32_t evtimeH;
uint32_t evtimeL;
uint32_t PPStime;
uint32_t time0;
uint32_t time1;
uint32_t time2;
uint32_t time3;
uint16_t energy0;
uint16_t energy1;
uint16_t energy2;
uint16_t energy3;
uint16_t NumUserDataBlks;
uint16_t Esum;
#if( PixieNetHit_RECORD_HIT_PSA ) // really would need NCHANNELS of these, but currently no group PSA supported
uint32_t psa0;
uint32_t psa1;
uint32_t cfd0;
uint32_t cfd1;
#endif
#if( PixieNetHit_HAS_WAVEFORM )
uint16_t NumCurrTraceBlks; // number of trace blocks
uint16_t NumPrevTraceBlks; // number of trace blocks
uint16_t num_waveform0; //Lockless queue can not be used with non-trivial constructor, so can't use a vector.
uint16_t waveform0[MAX_ACQ_TL]; //max size of MAX_TL (4092), but typically less as defined above
uint16_t NumTraceBlks0; // number of trace blocks
uint16_t num_waveform1; //Lockless queue can not be used with non-trivial constructor, so can't use a vector.
uint16_t waveform1[MAX_ACQ_TL]; //max size of MAX_TL (4092)
uint16_t NumTraceBlks1; // number of trace blocks
uint16_t num_waveform2; //Lockless queue can not be used with non-trivial constructor, so can't use a vector.
uint16_t waveform2[MAX_ACQ_TL]; //max size of MAX_TL (4092)
uint16_t NumTraceBlks2; // number of trace blocks
uint16_t num_waveform3; //Lockless queue can not be used with non-trivial constructor, so can't use a vector.
uint16_t waveform3[MAX_ACQ_TL]; //max size of MAX_TL (4092)
uint16_t NumTraceBlks3; // number of trace blocks
#endif
} PixieNetHit402;//struct PixieNetHit402
/** A global variable that gets set to N>1 if the ctrl-c interupt is detected.
If this happens, the data collection loop is terminated, and everything else
exits as normal. */
boost::atomic<size_t> g_datataking_stop_requested;
/** Writes listmode data in the queue to disk
Uses a lockfree queue to minimize delays of locking a conventional queue,
however, when the queue becomes empty, the function then waits on the
condition_variable to recieve a notifiaction more data is available; this
is to reduce CPU usage.
Once taking_data is false, and the queue is empty, this function returns.
Use this function for RUN_TYPE 0x400, 0x500 or 0x501 */
void write_lm_data400( FILE *outfile,
uint32_t histogram[NCHANNELS+1][MAX_MCA_BINS],
uint32_t wmca[NCHANNELS+1][WEB_MCA_BINS],
boost::atomic<bool> &taking_data,
boost::lockfree::queue<PixieNetHit402> &hit_queue,
boost::condition_variable &cv,
boost::atomic<size_t> &num_wrote,
unsigned int BINFACTOR[NCHANNELS] );
/** equivalent for RUN_TYPE 0x402 */
void write_lm_data402( FILE *outfile,
uint32_t histogram[NCHANNELS+1][MAX_MCA_BINS],
uint32_t wmca[NCHANNELS+1][WEB_MCA_BINS],
// #if(SUMMCA)
// uint32_t sumhistogram[MAX_MCA_BINS],
// uint32_t swmca[WEB_MCA_BINS],
// #endif
boost::atomic<bool> &taking_data,
boost::lockfree::queue<PixieNetHit402> &hit_queue,
boost::condition_variable &cv,
boost::atomic<size_t> &num_wrote,
unsigned int BINFACTOR[NCHANNELS] );
/** Accumulates data into histogram, and does not save list mode data.
Otherwise functions similar to write_lm_data.
Use this function for RUN_TYPE 0x301 */
void histogram_lm_data( uint32_t histogram[NCHANNELS+1][MAX_MCA_BINS],
uint32_t wmca[NCHANNELS+1][WEB_MCA_BINS],
boost::atomic<bool> &taking_data,
boost::lockfree::queue<PixieNetHit402> &hit_queue,
boost::condition_variable &cv,
boost::atomic<size_t> &num_wrote,
unsigned int BINFACTOR[NCHANNELS] );
/** Sets g_datataking_stop_requested to N>0, which stops data taking so program
can exit. */
void handle_interupt( int s );
struct RunOptions
{
string listmode_output_name, mca_output_name;
};//struct RunOptions
typedef struct PixieNetRunningStats {
/** Number of times that it has been checked wether or not there are any
events waiting in the FPGAs buffer to copy over to the linux side of
things. */
uint64_t numchecks;
/** Number of times there have been any events waiting in the FPGAs buffer,
wether there was one or four, or they were rejected or kept.
Note that at each checking, a maximum of one event from each channel is
copied over. */
uint64_t collectionnum;
/** Number of events accepted so far, for all channels. */
uint64_t eventcount;
/** Number of accepted events for each channel, so far*/
uint64_t numaccepted[NCHANNELS];
/** Number of rejected events for each channel, so far */
uint64_t numrejected[NCHANNELS];
/** Number of trace blocks to follow */
uint64_t numtraceblocks;
/** Some (I believe) temporary variables that I think will be moved to the
FPGA, but we'll put them here for now */
double baseline[NCHANNELS];
double C0[NCHANNELS], C1[NCHANNELS], Cg[NCHANNELS];
} PixieNetRunningStats;
/** Zeros out PixieNetRunningStats */
void init_PixieNetRunningStats( PixieNetRunningStats *stats );
/** writes the data to file all RUN_TYPEs except 0x402 */
int PixieNetHit_write_400( FILE *instrm, const PixieNetHit402 * const hit );
/** writes the data to file (mode 0x402) */
int PixieNetHit_write_402( FILE *instrm, const PixieNetHit402 * const hit );
/** reads the data from FPGA and puts into "hits" record */
unsigned int collect_PixieNet_lm_data400( volatile unsigned int *mapped,
PixieNetHit402 hits[NCHANNELS],
PixieNetRunningStats *runstats,
const PixieNetFippiConfig *fippiconfig );
/** reads the data from FPGA and puts into "hits" record, special for RUN_TYPE 0x402 */
unsigned int collect_PixieNet_lm_data402( volatile unsigned int *mapped,
PixieNetHit402 hits[NCHANNELS],
PixieNetRunningStats *runstats,
const PixieNetFippiConfig *fippiconfig );
/** Returns a zero or positive value on success */
int init_configurations( int argc, char **argv,
RunOptions &options,
PixieNetFippiConfig &fippiconfig );
/* ********************************************************************************
********************************************************************************
********************************************************************************
* MAIN
********************************************************************************
******************************************************************************** */
int main( int argc, char **argv )
{
int TL;
unsigned int BLbad[NCHANNELS];
unsigned int BLcut[NCHANNELS], BLavg[NCHANNELS];
long queued;
int pause_queue = 0;
int rev, scale14B;
//Set the handler for if the user hits ctrl-c
g_datataking_stop_requested = 0;
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = handle_interupt;
sigemptyset( &sigIntHandler.sa_mask );
sigIntHandler.sa_flags = 0;
sigaction( SIGINT, &sigIntHandler, NULL );
// --------------------------------------------------------
// ------ Start setting up the PIXIE-NET -------
// --------------------------------------------------------
const string settings_file = "settings.ini";
RunOptions options;
PixieNetFippiConfig fippiconfig;
if( init_configurations( argc, argv, options, fippiconfig ) < 0 )
{
return EXIT_FAILURE;
}
cout << "Succeded in parsing config/settings files" << endl;
// *************** PS/PL IO initialization *********************
// open the device for PD register I/O
const int device_fd_PL = open("/dev/uio0", O_RDWR);
if( device_fd_PL < 0 ) {
perror("Failed to open PL devfile");
return -1;
}
void *map_addr = mmap( NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, device_fd_PL, 0);
if( map_addr == MAP_FAILED ) {
perror("Failed to mmap");
return -2;
}
//Lock the fipi device so multiple programs cant step on eachother.
if( flock( device_fd_PL, LOCK_EX | LOCK_NB ) )
{
cerr << "Failed to get file lock on /dev/uio0" << endl;
munmap( map_addr, 4096 );
close( device_fd_PL );
return -3;
}
volatile unsigned int *mapped = (unsigned int *) map_addr;
// ********** Compute Coefficients for E Computation and other initialization ************
PixieNetRunningStats runstats;
init_PixieNetRunningStats( &runstats );
rev = hwinfo(mapped);
// energy filters for 14bit version derive from 4x larger ADC samples, but should map to same E in MCA, so divide result by 4
if ( (((rev>>16) & 0xFFFF) == PN_BOARD_VERSION_12_250_A) ||
(((rev>>16) & 0xFFFF) == PN_BOARD_VERSION_12_250_B) ||
(((rev>>16) & 0xFFFF) == PN_BOARD_VERSION_12_250_B_PTP) )
{
//printf("Using E scale for 12 bit version");
scale14B = 1;
}
else
{
//printf("Using E scale for 14 bit version");
scale14B = 4;
}
for( int k = 0; k < NCHANNELS; k ++ )
{
const double dt = 1.0 / FILTER_CLOCK_MHZ;
// multiply time in us * # ticks per us = time in ticks
const int SL = (int)floor( fippiconfig.ENERGY_RISETIME[k]*FILTER_CLOCK_MHZ );
//const int SG = (int)floor( fippiconfig.ENERGY_FLATTOP[k]*FILTER_CLOCK_MHZ );
const double q = exp( -1.0 * dt / fippiconfig.TAU[k] );
const double elm = exp( -1.0 * dt * SL / fippiconfig.TAU[k] );
runstats.C0[k] = (q - 1.0) * elm / (1.0 - elm);
runstats.Cg[k] = 1.0 - q;
runstats.C1[k] = (1.0 - q) / (1.0 - elm);
runstats.C0[k] = runstats.C0[k] * fippiconfig.DIG_GAIN[k] / scale14B;
runstats.Cg[k] = runstats.Cg[k] * fippiconfig.DIG_GAIN[k] / scale14B;
runstats.C1[k] = runstats.C1[k] * fippiconfig.DIG_GAIN[k] / scale14B;
BLcut[k] = fippiconfig.BLCUT[k];
BLavg[k] = 65536 - fippiconfig.BLAVG[k];
if(BLavg[k]<0) BLavg[k] = 0;
if(BLavg[k]==65536) BLavg[k] = 0;
if(BLavg[k]>MAX_BLAVG) BLavg[k] = MAX_BLAVG;
BLbad[k] = MAX_BADBL; // initialize to indicate no good BL found yet
TL = (int)floor(fippiconfig.TRACE_LENGTH[k]*ADC_CLK_MHZ);
if( (fippiconfig.RUN_TYPE != 0x301 ) && (TL > MAX_ACQ_TL) )
{
cerr << "Compile option limits TRACE_LENGTH to " << MAX_ACQ_TL << " samples, exiting." << endl;
cerr << "(Shorten TRACE_LENGTHs or modify #defines in acquire.cpp and recompile.)" << endl;
flock( device_fd_PL, LOCK_UN );
munmap( map_addr, 4096 );
close( device_fd_PL );
return -6;
}
}
// ***** check HW info *********
int revsn = hwinfo(mapped);
cout << "Initialized filters" << endl;
// ********************** Run Start **********************
// run type check
if( fippiconfig.RUN_TYPE == 0x301 ||
fippiconfig.RUN_TYPE == 0x400 ||
fippiconfig.RUN_TYPE == 0x402 )
{
//ok, do nothing
} else {
cerr << "This function only supports runtypes 0x301, 0x400, 0x402 for now, exiting" << endl;
flock( device_fd_PL, LOCK_UN );
munmap( map_addr, 4096 );
close( device_fd_PL );
return -5;
}
// though we checked runtypes above, here for completeness treat all LM runtypes
string listmodeoutname = options.listmode_output_name;
if ( fippiconfig.RUN_TYPE == 0x400) listmodeoutname += ".b00"; // depends on runtype
if ( fippiconfig.RUN_TYPE == 0x402) listmodeoutname += ".b00"; // depends on runtype
if ( fippiconfig.RUN_TYPE == 0x500) listmodeoutname += ".txt"; // depends on runtype
if ( fippiconfig.RUN_TYPE == 0x501) listmodeoutname += ".dat"; // depends on runtype
if ( fippiconfig.RUN_TYPE == 0x502) listmodeoutname += ".dt2"; // depends on runtype
if ( fippiconfig.RUN_TYPE == 0x503) listmodeoutname += ".dt4"; // depends on runtype
FILE *lmout = NULL;
FILE *filmca = NULL;
if( fippiconfig.RUN_TYPE == 0x400 ||
fippiconfig.RUN_TYPE == 0x402 ||
fippiconfig.RUN_TYPE == 0x500 ||
fippiconfig.RUN_TYPE == 0x501 ||
fippiconfig.RUN_TYPE == 0x502 ||
fippiconfig.RUN_TYPE == 0x503 )
{
lmout = fopen( listmodeoutname.c_str(), "wb");
if( lmout == NULL )
{
cerr << "Failed to open '" << listmodeoutname << "', exiting" << endl;
flock( device_fd_PL, LOCK_UN );
munmap( map_addr, 4096 );
close( device_fd_PL );
return -4;
}
if( fippiconfig.RUN_TYPE == 0x400 ||
fippiconfig.RUN_TYPE == 0x402 )
{
// write a 0x400, 0x402 header
// fwrite is really slow (like very significant impact on thoroughput of events
// slow), so we will write to a buffer, and then to the file.
uint16_t buffer[FILE_HEAD_LENGTH_400] = {0};
buffer[0] = BLOCKSIZE_400;
buffer[1] = 0; // module number (get from settings file?)
buffer[2] = fippiconfig.RUN_TYPE;
buffer[3] = CHAN_HEAD_LENGTH_400;
buffer[4] = fippiconfig.COINCIDENCE_PATTERN;
buffer[5] = fippiconfig.COINCIDENCE_WINDOW;
buffer[7] = revsn>>16; // HW revision from EEPROM
buffer[12] = revsn & 0xFFFF; // serial number from EEPROM
for( unsigned int ch = 0; ch < NCHANNELS; ch++) {
TL = (int)floor(fippiconfig.TRACE_LENGTH[ch]*ADC_CLK_MHZ);
buffer[6] +=(int)floor((TL + CHAN_HEAD_LENGTH_400) / BLOCKSIZE_400); // combined event length, in blocks
buffer[8+ch] =(int)floor((TL + CHAN_HEAD_LENGTH_400) / BLOCKSIZE_400); // each channel's event length, in blocks
}
if( fippiconfig.RUN_TYPE == 0x402) {
buffer[6] -=(NCHANNELS-1); // only one event header for all 4 channels in 0x402
}
fwrite( buffer, 2, FILE_HEAD_LENGTH_400, lmout ); // write to file
} else {
cerr << "This function only supports runtypes 0x301, 0x400, 0x402 for now, exiting" << endl; // MCA run 0x301 also ok
flock( device_fd_PL, LOCK_UN );
munmap( map_addr, 4096 );
close( device_fd_PL );
fclose( lmout );
return -5;
}
}//if( saving LM data header )
const boost::posix_time::ptime starttime = boost::posix_time::second_clock::local_time();
//cout << "Start time: " << starttime << endl;
if( fippiconfig.SYNC_AT_START )
mapped[ARTC_CLR] = 1; // write to reset time counter
mapped[AOUTBLOCK] = 2;
// unsigned int startTS = mapped[AREALTIME];
const std::string starttimestr = boost::posix_time::to_iso_extended_string( starttime );
//#if(SUMMCA)
unsigned int histogram[NCHANNELS+1][MAX_MCA_BINS] = { {0} }; // full 32K spectrum for final output, 1 extra for sum
unsigned int wmca[NCHANNELS+1][WEB_MCA_BINS] = { {0} }; // 4K spectrum for faster web update
//#else
// unsigned int histogram[NCHANNELS][MAX_MCA_BINS] = { {0} }; // full 32K spectrum for final output
// unsigned int wmca[NCHANNELS][WEB_MCA_BINS] = { {0} }; // 4K spectrum for faster web update
//#endif
//#if(SUMMCA) declare always and print to MCA always, even if unused and all zero
// unsigned int sumhistogram[MAX_MCA_BINS] = {0} ; // full 32K spectrum for final output
// unsigned int swmca[WEB_MCA_BINS] = {0} ; // 4K spectrum for faster web update
//#endif
boost::atomic<bool> taking_data( true );
boost::lockfree::queue<PixieNetHit402> hit_queue(32*1024);
boost::atomic<size_t> num_wrote( 0 );
boost::condition_variable notifier;
boost::scoped_ptr<boost::thread> writing_thread;
if( fippiconfig.RUN_TYPE == 0x400 || fippiconfig.RUN_TYPE == 0x500 || fippiconfig.RUN_TYPE == 0x501 )
{
writing_thread.reset( new boost::thread( boost::bind(write_lm_data400,lmout,histogram,wmca,
boost::ref(taking_data),
boost::ref(hit_queue),
boost::ref(notifier),
boost::ref(num_wrote),
fippiconfig.BINFACTOR) ) );
}
if( fippiconfig.RUN_TYPE == 0x402 )
{
writing_thread.reset( new boost::thread( boost::bind(write_lm_data402,lmout,histogram,wmca,
// #if(SUMMCA)
// sumhistogram,swmca,
// #endif
boost::ref(taking_data),
boost::ref(hit_queue),
boost::ref(notifier),
boost::ref(num_wrote),
fippiconfig.BINFACTOR) ) );
}
if( fippiconfig.RUN_TYPE == 0x301 )
{
writing_thread.reset( new boost::thread( boost::bind(histogram_lm_data,histogram,wmca,
boost::ref(taking_data),
boost::ref(hit_queue),
boost::ref(notifier),
boost::ref(num_wrote),
fippiconfig.BINFACTOR) ) );
}//
const boost::posix_time::time_duration runtimelimit = boost::posix_time::millisec( static_cast<int>(1000*fippiconfig.REQ_RUNTIME) );
cout << "Will run for " << runtimelimit << endl;
mapped[ADSP_CLR] = 1; // write to reset DAQ buffers
mapped[ACOUNTER_CLR] = 1; // write to reset RS counters
mapped[ACSRIN] = 1; // set RunEnable bit to start run
mapped[AOUTBLOCK] = OB_EVREG; // read from event registers
// ********************** Run Loop **********************
PixieNetHit402 hits[NCHANNELS];
// PixieNetHit400 hits[NCHANNELS];
do
{
//----------- Periodically read BL and update average -----------
// this will be moved into the FPGA soon
if( (runstats.numchecks % BLREADPERIOD) == 0 )
{
for( unsigned int ch = 0; ch < NCHANNELS; ch++)
{
// read raw BL sums
const unsigned int chaddr = ch*16+16;
const unsigned int lsum = mapped[chaddr+CA_LSUMB];
const unsigned int tsum = mapped[chaddr+CA_TSUMB];
const unsigned int gsum = mapped[chaddr+CA_GSUMB];
if( tsum > 0 ) // tum=0 indicates bad baseline
{
const double ph = runstats.C1[ch]*lsum + runstats.Cg[ch]*gsum + runstats.C0[ch]*tsum;
if( (BLcut[ch]==0) ||
(abs(ph-runstats.baseline[ch])<BLcut[ch]) || // only accept "good" baselines < BLcut,
(BLbad[ch] >=MAX_BADBL) ) // or if too many bad in a row (to start over)
{
if( (BLavg[ch]==0) || (BLbad[ch] >=MAX_BADBL) )
{
runstats.baseline[ch] = ph;
BLbad[ch] = 0;
} else {
// BL average: // avg = old avg + (new meas - old avg)/2^BLavg
runstats.baseline[ch] = runstats.baseline[ch] + (ph-runstats.baseline[ch])/(1<<BLavg[ch]);
BLbad[ch] = 0;
} // end BL avg
} else {
BLbad[ch] = BLbad[ch]+1;
} // end BLcut check
} // if( tsum > 0 )
} // for( loop over channels )
} // if( should update baseline )
// -----------poll for events -----------
// if data ready. read out, compute E, increment MCA *********
unsigned int nhits;
// ensure we don't have too much of a backlog
size_t ntotalwrittennow = num_wrote;
queued = ((long)runstats.eventcount - (long)ntotalwrittennow);
if (pause_queue==0 && queued > MAX_QUEUED )
{
cout << "queue paused " << queued << endl;
pause_queue = 1;
}
if (pause_queue==1 && queued < MAX_QUEUED*0.8 )
{
cout << "queue un-paused " << queued << endl;
pause_queue = 0;
}
if(pause_queue==0)
{
if( fippiconfig.RUN_TYPE == 0x402)
{
nhits = collect_PixieNet_lm_data402( mapped, hits, &runstats, &fippiconfig );
for( size_t i = 0; i < nhits; ++i ) // nhits = 0 to 4
if( !hit_queue.push( hits[i] ) )
cerr << "Failed to push onto queue" << endl;
} else {
nhits = collect_PixieNet_lm_data400( mapped, hits, &runstats, &fippiconfig );
for( size_t i = 0; i < nhits; ++i ) // nhits = 0 to 4
if( !hit_queue.push( hits[i] ) )
cerr << "Failed to push onto queue" << endl;
}
if( nhits )
notifier.notify_one();
}
// ----------- Periodically save MCA and RS -----------
if( (runstats.numchecks % fippiconfig.POLL_TIME) == 0 )
{
// 1) Run Statistics
mapped[AOUTBLOCK] = OB_RSREG; // read from RS registers
read_print_runstats(1, 0, mapped); // print (small) set of RS to file, visible to web
mapped[AOUTBLOCK] = OB_EVREG; // read from event registers
// 2) MCA
filmca = fopen("MCA.csv","w");
if( fippiconfig.RUN_TYPE == 0x402) {
fprintf(filmca,"bin,MCAch0,MCAch1,MCAch2,MCAch3,MCAsum\n");
} else {
fprintf(filmca,"bin,MCAch0,MCAch1,MCAch2,MCAch3\n");
}
int onlinebin = (int)floor(MAX_MCA_BINS/WEB_MCA_BINS);
for( int k=0; k <WEB_MCA_BINS; k++) // report the 4K spectra during the run (faster web update)
{
if( fippiconfig.RUN_TYPE == 0x402) {
fprintf(filmca,"%d,%u,%u,%u,%u,%u\n ", k*onlinebin,wmca[0][k],wmca[1][k],wmca[2][k],wmca[3][k],wmca[4][k]);
} else {
fprintf(filmca,"%d,%u,%u,%u,%u\n ", k*onlinebin,wmca[0][k],wmca[1][k],wmca[2][k],wmca[3][k]);
}
}
fclose(filmca);
// 3) update console
const boost::posix_time::ptime currenttime1 = boost::posix_time::second_clock::local_time();
const boost::posix_time::time_duration dur1 = currenttime1 - starttime;
//cout << "Time: " << dur1 << " Events total " << runstats.eventcount << " written " << ntotalwrittennow << " queued " << ((long)runstats.eventcount - (long)ntotalwrittennow) << endl;
cout << "Time: " << dur1 << " Events total " << runstats.eventcount << " queued " << queued << endl;
}
// ----------- check if we've run long enough -------------------
const boost::posix_time::ptime currenttime = boost::posix_time::second_clock::local_time();
const boost::posix_time::time_duration dur = currenttime - starttime;
if( dur >= runtimelimit )
break;
if(g_datataking_stop_requested >1)
exit(-1); // multiple ctrl-c: exit altogether
} while ( g_datataking_stop_requested==0 );
// ********************** Run Stop **********************
// const boost::posix_time::ptime endtime = boost::posix_time::second_clock::local_time();
// clear RunEnable bit to stop run
mapped[ACSRIN] = 0;
size_t nwritensofar = num_wrote;
cout << "Done taking data" << endl;
// Grab any remaining events
unsigned int nhitsnow;
if( fippiconfig.RUN_TYPE == 0x402)
{
do
{
nhitsnow = collect_PixieNet_lm_data402( mapped, hits, &runstats, &fippiconfig );
for( size_t i = 0; i < nhitsnow; ++i )
{
hit_queue.push( hits[i] );
if(g_datataking_stop_requested >1)
exit(-1); // multiple ctrl-c: exit altogether
}
notifier.notify_one();
}while( nhitsnow );
while( !hit_queue.empty() )
{
notifier.notify_one(); //just to make sure...
}
} else {
do
{
nhitsnow = collect_PixieNet_lm_data400( mapped, hits, &runstats, &fippiconfig );
for( size_t i = 0; i < nhitsnow; ++i )
{
hit_queue.push( hits[i] );
if(g_datataking_stop_requested >1)
exit(-1); // multiple ctrl-c: exit altogether
}
notifier.notify_one();
}while( nhitsnow );
while( !hit_queue.empty() )
{
notifier.notify_one(); //just to make sure...
}
} // end if RUN_TYPE
taking_data = false;
notifier.notify_one(); //make sure and wake that thread up
writing_thread->join();
size_t ntotalwritten = num_wrote;
cout << "Done writing data, there were " << (ntotalwritten-nwritensofar) << " in queue by end" << endl;
if( fippiconfig.RUN_TYPE != 0x301 )
{
// write EOR: special hit pattern, all zero except EORMARK and WM indicates end of run data
uint8_t buffer[CHAN_HEAD_LENGTH_400*2] = {0};
uint32_t wm = EORMARK;
memcpy( buffer + 0, &(wm), 4 );
#if( PixieNetHit_HAS_WAVEFORM )
// TODO: write PrevNumTraceBlks
#endif
wm = WATERMARK;
memcpy( buffer + 60, &(wm), 4 );
fwrite( buffer, 1, CHAN_HEAD_LENGTH_400*2, lmout );
if( lmout != NULL )
fclose( lmout );
}
// ----------- Final save MCA and RS -----------
// 1) Run Statistics
mapped[AOUTBLOCK] = OB_RSREG; // read from RS registers
read_print_runstats(0, 0, mapped); // print (small) set of RS to file, visible to web
mapped[AOUTBLOCK] = OB_EVREG; // read from event registers
// 2) MCA
// once for the default filename
filmca = fopen("MCA.csv","w");
if( fippiconfig.RUN_TYPE == 0x402) {
fprintf(filmca,"bin,MCAch0,MCAch1,MCAch2,MCAch3,MCAsum\n");
} else {
fprintf(filmca,"bin,MCAch0,MCAch1,MCAch2,MCAch3\n");
}
unsigned int k;
for( k=0; k <MAX_MCA_BINS; k++)
{
if( fippiconfig.RUN_TYPE == 0x402) {
fprintf(filmca,"%d,%u,%u,%u,%u,%u\n ", k,histogram[0][k],histogram[1][k],histogram[2][k],histogram[3][k],histogram[4][k] );
} else {
fprintf(filmca,"%d,%u,%u,%u,%u\n ", k,histogram[0][k],histogram[1][k],histogram[2][k],histogram[3][k] );
}
}
fclose(filmca);
/*
// once for the named file name
// if <different names>
string mcaoutname = options.listmode_output_name;
mcaoutname += ".csv";
FILE *filmca = NULL;
filmca = fopen( mcaoutname.c_str(), "w");
fprintf(filmca,"bin,MCAch0,MCAch1,MCAch2,MCAch3\n");
unsigned int k;
for( k=0; k <MAX_MCA_BINS; k++)
{
fprintf(filmca,"%d,%u,%u,%u,%u\n ", k,histogram[0][k],histogram[1][k],histogram[2][k],histogram[3][k] );
}
fclose(filmca);
*/
cout << "Done writing MCA and run statistics." << endl;
// clean up
flock( device_fd_PL, LOCK_UN );
munmap( map_addr, 4096 );
close( device_fd_PL );
return 0;
}
/* ********************************************************************************
********************************************************************************
********************************************************************************
* SUBROUTINES
********************************************************************************
******************************************************************************** */
/* ********************************************************************************
* interrupt handler
******************************************************************************** */
void handle_interupt( int s )
{
if(g_datataking_stop_requested==0)
{
printf( "Caught signal %d. Will stop taking data.\n", s ); // first time around, try safe exit
g_datataking_stop_requested = 1;
}
else
{
printf( "Caught signal %d again. Will exit DAQ.\n", s ); // 2nd time, give up
g_datataking_stop_requested ++;
}
}//void handle_interupt( int s );
/* ********************************************************************************
* subroutine to histogram and write LM data to file (0x400)
******************************************************************************** */
void write_lm_data400( FILE *outfile,
uint32_t histogram[NCHANNELS+1][MAX_MCA_BINS],
uint32_t wmca[NCHANNELS+1][WEB_MCA_BINS],
boost::atomic<bool> &taking_data,
boost::lockfree::queue<PixieNetHit402> &hit_queue,
boost::condition_variable &cv,
boost::atomic<size_t> &num_wrote,
unsigned int BINFACTOR[NCHANNELS] )
{
PixieNetHit402 hit;
boost::mutex local_mutex;
while( taking_data )
{
boost::unique_lock<boost::mutex> lock( local_mutex );
cv.wait( lock );
while( hit_queue.pop(hit) )
{
// histogram
const uint32_t energy_bin = (hit.energy0 >> BINFACTOR[hit.channel]);
const unsigned int bin = std::max(std::min(energy_bin,static_cast<unsigned int>(MAX_MCA_BINS-1)),0u);
histogram[hit.channel][bin] += 1;
const unsigned int binw = bin >> WEB_LOGEBIN;
wmca[hit.channel][binw] += 1;
// write LM file
PixieNetHit_write_400( outfile, &hit );
num_wrote += 1;
}
}//
}//write_lm_data(...)
/* ********************************************************************************
* subroutine to histogram and write LM data to file (0x402)
******************************************************************************** */
void write_lm_data402( FILE *outfile,
uint32_t histogram[NCHANNELS+1][MAX_MCA_BINS],
uint32_t wmca[NCHANNELS+1][WEB_MCA_BINS],
// #if(SUMMCA)
// uint32_t sumhistogram[MAX_MCA_BINS],
// uint32_t swmca[WEB_MCA_BINS],
// #endif
boost::atomic<bool> &taking_data,
boost::lockfree::queue<PixieNetHit402> &hit_queue,
boost::condition_variable &cv,
boost::atomic<size_t> &num_wrote,
unsigned int BINFACTOR[NCHANNELS] )
{
PixieNetHit402 hit;
boost::mutex local_mutex;
uint32_t energy_bin[NCHANNELS];
unsigned int bin, binw;
while( taking_data )
{
boost::unique_lock<boost::mutex> lock( local_mutex );
cv.wait( lock );
while( hit_queue.pop(hit) )
{
// histogram singles
energy_bin[0] = (hit.energy0 >> BINFACTOR[0]); // get energies from record
energy_bin[1] = (hit.energy1 >> BINFACTOR[1]);
energy_bin[2] = (hit.energy2 >> BINFACTOR[2]);
energy_bin[3] = (hit.energy3 >> BINFACTOR[3]);
for( int k = 0; k < NCHANNELS; k ++ ) // increment MCAs in a loop
{
bin = std::max(std::min(energy_bin[k],static_cast<unsigned int>(MAX_MCA_BINS-1)),0u);
histogram[k][bin] += 1;
binw = bin >> WEB_LOGEBIN;
wmca[k][binw] += 1;
}
//#if(SUMMCA)
// histogram sum
energy_bin[0] = energy_bin[0] + energy_bin[1] + energy_bin[2] + energy_bin[3];
bin = std::max(std::min(energy_bin[0],static_cast<unsigned int>(MAX_MCA_BINS-1)),0u);
histogram[4][bin] += 1;
binw = bin >> WEB_LOGEBIN;
wmca[4][binw] += 1;
//#endif
// write LM file
PixieNetHit_write_402( outfile, &hit );
num_wrote += 1;
}
}//
}//write_lm_data(...)
/* ********************************************************************************
* subroutine to histogram only
******************************************************************************** */
void histogram_lm_data(uint32_t histogram[NCHANNELS+1][MAX_MCA_BINS],
uint32_t wmca[NCHANNELS+1][WEB_MCA_BINS],
boost::atomic<bool> &taking_data,
boost::lockfree::queue<PixieNetHit402> &hit_queue,
boost::condition_variable &cv,
boost::atomic<size_t> &num_wrote,
unsigned int BINFACTOR[NCHANNELS] )
{
PixieNetHit402 hit;
boost::mutex local_mutex;
while( taking_data )
{
boost::unique_lock<boost::mutex> lock( local_mutex );
cv.wait( lock );
while( hit_queue.pop(hit) )
{
const uint32_t energy_bin = (hit.energy0 >> BINFACTOR[hit.channel]);
const unsigned int bin = std::max(std::min(energy_bin,static_cast<unsigned int>(MAX_MCA_BINS-1)),0u);
histogram[hit.channel][bin] += 1;
const unsigned int binw = bin >> WEB_LOGEBIN;
wmca[hit.channel][binw] += 1;
num_wrote += 1;
}