forked from VolunteerComputingHelp/boinc-app-eah-brp
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdemod_binary.c
1794 lines (1527 loc) · 65.8 KB
/
demod_binary.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
* Copyright (C) 2008 by Benjamin Knispel, Holger Pletsch *
* benjamin.knispel[AT]aei.mpg.de *
* Copyright (C) 2009, 2010 by Oliver Bock *
* oliver.bock[AT]aei.mpg.de *
* Copyright (C) 2009, 2010 by Heinz-Bernd Eggenstein *
* *
* This file is part of Einstein@Home (Radio Pulsar Edition). *
* *
* Description: *
* Demodulates dedispersed time series using a bank of orbital *
* parameters. After this step, an FFT of the resampled time series is *
* searched for pulsed, periodic signals by harmonic summing. *
* *
* Einstein@Home 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, version 2 of the License. *
* *
* Einstein@Home 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 Einstein@Home. If not, see <http://www.gnu.org/licenses/>. *
* *
***************************************************************************/
// includes
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <fftw3.h>
#include <zlib.h>
#include "rngmed.h"
#include "structs.h"
#include "erp_utilities.h"
#include "erp_git_version.h"
#ifdef BOINCIFIED
// BOINC-specific includes
#include <time.h>
#include "demod_binary.h"
#include "erp_boinc_ipc.h"
#include "erp_boinc_wrapper.h"
#include "svn_version.h"
#include "filesys.h"
// BOINC-specific function mapping
#define fopen boinc_fopen
#define gzopen boinc_gzopen
#define rename boinc_rename
#endif
#include "hs_common.h"
#ifdef USE_CPU_RESAMP
#include "demod_binary_resamp_cpu.h"
#endif
#ifdef USE_FFTW_FFT
#include "demod_binary_fft_fftw.h"
#endif
#if defined USE_CUDA
#include "cuda/app/cuda_utilities.h"
#include "cuda/app/demod_binary_cuda.h"
#include "cuda/app/demod_binary_hs_cuda.cuh"
#elif defined USE_OPENCL
#include "boinc_opencl.h"
#include "opencl/app/demod_binary_ocl.h"
#else
#include "demod_binary_hs_cpu.h"
#endif
#define N_CAND_5 100 // number of candidates for each harmonic = number of candidates reported back
#define N_CAND 500 // number of candidates stored = five times the number of candidates reported back
#define TIME_FORMAT "%Y-%m-%dT%H:%M:%S+00:00" // used for the result file header
#define TIME_LENGTH 30 // used for the result file header
// user input
typedef struct
{
float f0; // maximum fundamental signal frequency (Hz) to search for
float padding; // factor of frequency overresolution achieved by mean-padding
float fA; // overall false alarm probability
unsigned int window; // window width for the running median in frequency bins
unsigned short int white; // switch for power spectrum whitening
unsigned short int debug; // switch for debug mode
char *inputfile; // name of the input file
char *outputfile; // pointer to name of the output file
char *templatebank; // pointer to name of the template bank
char *checkpointfile; // pointer to name of the checkpoint file
char *zaplistfile; // pointer to name of the zaplist file
char outputfile_tmp[FN_LENGTH + 4]; // name of the temporary output file
char checkpointfile_tmp[FN_LENGTH + 4];// name of the temporary checkpoint file
} User_Variables;
// prototypes
int compare_structs_by_P(const void * const ptr1, const void * const ptr2);
int compare_structs_by_ifa(const void * const ptr1, const void * const ptr2);
int set_checkpoint(const User_Variables * const uvar,
const CP_Header * const cp_head,
const CP_cand * const candidates);
/*+++++++++++++++++++++++++++++
+ start main program +
+++++++++++++++++++++++++++++*/
int MAIN (int argc, char *argv[])
{
// structs
User_Variables uvar; // parameters specified in the command line
DD_Header data_head; // header of the dedispersed time series
CP_Header cp_head; // header of the checkpoint file
t_pulsar_search search_params_tmp; // for communication with screensaver
// candiate array
CP_cand *candidates_all = NULL; // array of structs for all candidates
// file pointers
FILE *output = NULL, *templatebank = NULL, *checkpoint = NULL;
gzFile input;
// pointers for time series variables and FFT plan.
// at top level to avoid unnecessary allocation and destruction of FFT plan
int t_series_4bit = 1; // boolean flag to indicate 4-bit data format (default)
unsigned char * t_series_dd_comp4 = NULL; // nibble time series
signed char * t_series_dd_comp8 = NULL; // single-byte time series
DIfloatPtr t_series_dd; // dedispersed time series
DIfloatPtr t_series_resamp; // resampled timeseries
float *sumspec[5]; // spectra of summed harmonics
int32_t *dirty[5]; // flags for non-zero pages (per sumpspec array)
unsigned int nr_dirty_pages; // total number of pages for sparse cand. selection
unsigned int dirty_page_count; // counts sumspec pages marked dirty (for logging only)
unsigned int fft_size; // size of the FFT
DIfloatPtr powerspectrum ; // power spectrum of the resampled time series
float *sinLUTsamples = NULL; // sin/cos LUT samples
float *cosLUTsamples = NULL; // sin/cos LUT samples
unsigned int window_2; // half the size of the running median window
unsigned int fundamental_idx_hi; // frequency bin of the highest fundamental frequency searched for
unsigned int harmonic_idx_hi; // frequency bin of the highest harmonic frequency searched for
float t_obs; // observation time in seconds
float dt;
float step_inv; // inverse of a time sample
#ifdef BOINCIFIED
BOINC_STATUS boinc_status;
#endif
#if defined USE_CUDA || defined USE_OPENCL
int coprocDeviceId = -1; // Co-processor (CUDA/OpenCL) device id
int coprocDeviceIdGiven = 0; // Did we get a device ID via command line (bool)?
#endif
// book-keeping
unsigned int template_total_amount = 0; // total amount of templates
unsigned int template_counter; // count the templates already done
unsigned int n_unpadded; // number of the time samples in the original time series
unsigned int n_unpadded_format; // modified number of samples based on input file format (4-bit/8-bit)
unsigned int i; // loop and index vars
int result; // return value storage
char line[FN_LENGTH]; // string for parsing lines from the templatebank
// vars for sky position in screensaver
float hrs; // hours in RA, degrees in DEC
float min; // minutes in RA, arcminutes in DEC
float sec; // seconds in RA, arcseconds in DEC
// thresholds
float thrA[5]; // threshold for harmonics
t_series_dd.host_ptr = NULL;
t_series_resamp.host_ptr = NULL;
powerspectrum.host_ptr = NULL;
// vars for result header
char resultTimeISO[TIME_LENGTH + 1] = {0};
time_t timeValue;
struct tm* timeUTC;
// scan format constants
static const char* c_template_scan_format = "%lg %lg %lg\n";
// determine actual "endianess"
int big_endian = check_byte_order() == ERP_BIG_ENDIAN ? 1 : 0;
// set user variables to defaults
uvar.outputfile = NULL;
uvar.templatebank = NULL;
uvar.checkpointfile = NULL;
uvar.inputfile = NULL;
uvar.zaplistfile = NULL;
sprintf(uvar.outputfile_tmp, "");
sprintf(uvar.checkpointfile_tmp, "");
uvar.white = 0;
uvar.f0 = 250.0;
uvar.window = 1000;
uvar.padding = 1.0;
uvar.fA = 0.04;
uvar.debug = 0;
// parse command line arguments
i = 1;
while (i < argc)
{
if ((strcmp(argv[i], "-W") == 0) || (strcmp(argv[i], "--whitening") == 0))
{
uvar.white = 1;
i++;
}
else if ((strcmp(argv[i], "-P") == 0) || (strcmp(argv[i], "--padding") == 0))
{
// sanity check
if(atof(argv[i+1]) < 1.0)
{
logMessage(error, true, "Nonsense value: padding factor %g < 1.0.\n", atof(argv[i+1]));
return(RADPUL_EVAL);
}
else if(atof(argv[i+1]) > 10.0)
{
logMessage(error, true, "Nonsense value: padding factor %g > 10.0.\n", atof(argv[i+1]));
return(RADPUL_EVAL);
}
else
{
uvar.padding = atof(argv[i+1]);
i += 2;
}
}
else if ((strcmp(argv[i], "-B") == 0) || (strcmp(argv[i], "--box") == 0))
{
// sanity check
if(atoi(argv[i+1]) < 0)
{
logMessage(error, true, "Nonsense value: window size for running median %d is negative.\n", atoi(argv[i+1]));
return(RADPUL_EVAL);
}
else if(atoi(argv[i+1]) > 250000)
{
logMessage(error, true, "Nonsense value: window size for running median too large: %d.\n", atoi(argv[i+1]));
return(RADPUL_EVAL);
}
else
{
uvar.window = atoi(argv[i+1]);
i += 2;
}
}
else if ((strcmp(argv[i], "-z") == 0) || (strcmp(argv[i], "--debug") == 0))
{
uvar.debug = 1;
logMessage(debug, true, "Running program in debugging mode.\n");
i++;
}
else if ((strcmp(argv[i], "-f") == 0) || (strcmp(argv[i], "--f0") == 0))
{
// sanity check
if(atof(argv[i+1]) < 0.0)
{
logMessage(error, true, "Nonsense value: upper limit for search frequency %g is negative.\n", atof(argv[i+1]));
return(RADPUL_EVAL);
}
else if(atof(argv[i+1]) > 16.0e3)
{
logMessage(error, true, "Nonsense value: upper limit for search frequency %g > 16 kHz.\n", atof(argv[i+1]));
return(RADPUL_EVAL);
}
else
{
uvar.f0 = atof(argv[i+1]);
i += 2;
}
}
else if ((strcmp(argv[i], "-A") == 0) || (strcmp(argv[i], "--false_alarm") == 0))
{
// sanity check
if(atof(argv[i+1]) < 0.0)
{
logMessage(error, true, "Nonsense value: false alarm rate %g is negative.\n", atof(argv[i+1]));
return(RADPUL_EVAL);
}
else if(atof(argv[i+1]) > 1.0)
{
logMessage(error, true, "Nonsense value: false alarm rate %g > 1.0.\n", atof(argv[i+1]));
return(RADPUL_EVAL);
}
else
{
uvar.fA = atof(argv[i+1]);
i += 2;
}
}
else if ((strcmp(argv[i], "-i") == 0) || (strcmp(argv[i], "--input_file") == 0))
{
uvar.inputfile = argv[i+1];
if(NULL == uvar.inputfile)
{
logMessage(error, true, "Couldn't prepare input file name: %s\n", argv[i+1]);
return(RADPUL_EFILE);
}
if(strstr(uvar.inputfile, ".binary")) {
t_series_4bit = 0;
logMessage(debug, true, "Using 8-bit format instead of 4-bit format for input file: %s\n", uvar.inputfile);
}
else if(!strstr(uvar.inputfile, ".bin4")) {
logMessage(error, true, "Unknown file format (extension) for input file: %s\n", uvar.inputfile);
return(RADPUL_EFILE);
}
i += 2;
}
else if ((strcmp(argv[i], "-o") == 0) || (strcmp(argv[i], "--output_file") == 0))
{
uvar.outputfile = argv[i+1];
if(NULL == uvar.outputfile)
{
logMessage(error, true, "Couldn't prepare output file name: %s\n", argv[i+1]);
return(RADPUL_EFILE);
}
if(snprintf(uvar.outputfile_tmp, sizeof(uvar.outputfile_tmp), "%s.tmp", argv[i+1]) >= sizeof(uvar.outputfile_tmp))
{
logMessage(error, true, "Couldn't prepare temporary output file name: %s\n", argv[i+1]);
return(RADPUL_EFILE);
}
i += 2;
}
else if ((strcmp(argv[i], "-c") == 0) || (strcmp(argv[i], "--checkpoint_file") == 0))
{
uvar.checkpointfile = argv[i+1];
if(NULL == uvar.checkpointfile)
{
logMessage(error, true, "Couldn't prepare checkpoint file name: %s\n", argv[i+1]);
return(RADPUL_EFILE);
}
if(snprintf(uvar.checkpointfile_tmp, sizeof(uvar.checkpointfile_tmp), "%s.tmp", argv[i+1]) >= sizeof(uvar.checkpointfile_tmp))
{
logMessage(error, true, "Couldn't prepare temporary checkpoint file name: %s\n", argv[i+1]);
return(RADPUL_EFILE);
}
i += 2;
}
else if ((strcmp(argv[i], "-t") == 0) || (strcmp(argv[i], "--template_bank") == 0))
{
uvar.templatebank = argv[i+1];
if(NULL == uvar.templatebank)
{
logMessage(error, true, "Couldn't prepare template bank file name: %s\n", argv[i+1]);
return(RADPUL_EFILE);
}
i += 2;
}
else if ((strcmp(argv[i], "-l") == 0) || (strcmp(argv[i], "--zaplist_file") == 0))
{
uvar.zaplistfile = argv[i+1];
if(NULL == uvar.zaplistfile)
{
logMessage(error, true, "Couldn't prepare zaplist file name: %s\n", argv[i+1]);
return(RADPUL_EFILE);
}
i += 2;
}
#if defined USE_CUDA || defined USE_OPENCL
else if ((strcmp(argv[i], "-D") == 0) || (strcmp(argv[i], "--device") == 0)) {
long int temp = -1;
// input conversion
if(isdigit(*(argv[i+1])))
{
errno = 0;
temp = strtol(argv[i+1], (char**)NULL, 10);
}
else
{
logMessage(error, true, "Invalid GPU device ID encountered: %s\n", argv[i+1]);
return(RADPUL_EVAL);
}
if(errno != 0)
{
logMessage(error, true, "GPU device ID couldn't be parsed: %s\n", strerror(errno));
return(RADPUL_EVAL);
}
// sanity check
if(temp < 0)
{
logMessage(error, true, "Nonsense value: GPU device ID %i is negative.\n", atoi(argv[i+1]));
return(RADPUL_EVAL);
}
else
{
coprocDeviceId = (int)temp;
coprocDeviceIdGiven = 1;
i += 2;
}
}
#endif
else if ((strcmp(argv[i], "-h") == 0) || (strcmp(argv[i], "--help") == 0))
{
printf("\nUsage: %s [options], options are:\n\n", argv[0]);
printf(" -h, --help\t\t\tboolean\tPrint this message\n");
printf(" -i, --input_file\t\tstring\tThe name of the input file.\n");
printf(" -o, --output_file\t\tstring\tThe name of the candidate output file.\n");
printf(" -t, --template_bank\t\tstring\tThe name of the random template bank.\n");
printf(" -c, --checkpoint_file\t\tstring\tThe name of the checkpoint file.\n");
printf(" -l, --zaplist_file\t\tstring\tThe name of the zaplist file.\n");
printf(" -f, --f0\t\t\tfloat\tThe maximum signal frequency (in Hz)\n");
printf(" -A, --false_alarm\t\tfloat\tFalse alarm probability.\n");
printf(" -P, --padding\t\t\tfloat\tThe frequency over-resolution factor.\n");
printf(" -W, --whitening\t\tboolean\tSwitch for power spectrum whitening and line zapping.\n");
printf(" -B, --box\t\t\tint\tWindow width for the running median in frequeny bins.\n");
#if defined USE_CUDA || defined USE_OPENCL
printf(" -D, --device\t\tinteger\tThe GPU device ID to be used.\n");
#endif
printf(" -z, --debug\t\t\tboolean\tRun program in debug mode.\n");
printf("\n");
return(RADPUL_EMISC);
}
else
{
logMessage(error, true, "\nUnknown option \"%s\". Use '%s --help'.\n\n", argv[i], argv[0]);
return(RADPUL_EMISC);
}
}// end: while (i < argc)
logMessage(info, true, "Starting data processing...\n");
#if defined(BOINCIFIED) && (defined(USE_CUDA) || defined(USE_OPENCL))
boinc_begin_critical_section();
logMessage(debug, true, "Entered critical section: CUDA/OpenCL initialization\n");
#endif
#if defined USE_CUDA
// set up CUDA device
result = initialize_cuda(coprocDeviceIdGiven, &coprocDeviceId);
if(result != 0) return result;
#elif defined USE_OPENCL
cl_platform_id boincPlatformId = NULL;
cl_device_id boincDeviceId = NULL;
// do we run under BOINC control?
if(!boinc_is_standalone()) {
result = boinc_get_opencl_ids(&boincDeviceId, &boincPlatformId);
if(CL_SUCCESS == result) {
// BOINC takes the lead, ignore values passed manually (just to make sure)
coprocDeviceIdGiven = 0;
coprocDeviceId = -1;
// acquire OpenCL device determined by BOINC
result = initialize_ocl(coprocDeviceIdGiven, &coprocDeviceId, boincPlatformId, boincDeviceId);
}
else {
logMessage(error, true, "Failed to get OpenCL platform/device info from BOINC (error: %i)!\n", result);
}
}
else {
// set up OpenCL device manually or determine "best" of first platform
logMessage(debug, true, "Running in standalone mode, so we take care of OpenCL platform/device management...\n");
result = initialize_ocl(coprocDeviceIdGiven, &coprocDeviceId, boincPlatformId, boincDeviceId);
}
if(result != 0) return result;
#endif
#if defined(BOINCIFIED) && (defined(USE_CUDA) || defined(USE_OPENCL))
boinc_end_critical_section();
logMessage(debug, true, "Left critical section: CUDA/OpenCL initialization\n");
#endif
// allocate memory for candidates array of structs
candidates_all = (CP_cand *)calloc(N_CAND, sizeof(CP_cand));
if(candidates_all == NULL)
{
logMessage(error, true, "Couldn't allocate %d bytes of memory for candidates_all.\n", N_CAND*sizeof(CP_cand));
return(RADPUL_EMEM);
}
// open template bank
logMessage(debug, true, "Opening template bank file: %s\n", uvar.templatebank);
templatebank = fopen(uvar.templatebank, "r");
if(templatebank == NULL)
{
logMessage(error, true, "Couldn't open template bank file: %s (%s).\n", uvar.templatebank, strerror(errno));
return(RADPUL_EIO);
}
// determine total number of templates
while(1)
{
double P_tmp, tau_tmp, psi_tmp;
char line[FN_LENGTH];
// check whether file is sane, fgets can read line and the EOF isn't reached by this scan
if(!ferror(templatebank) && (NULL != fgets(line, FN_LENGTH, templatebank)) && !feof(templatebank))
{
// parse line and check whether three values could be read
if(sscanf(line, c_template_scan_format, &P_tmp, &tau_tmp, &psi_tmp) == 3)
{
template_total_amount++;
}
else // if three values could not be read
{
logMessage(error, true, "Line %d in templatebank %s seems to be damaged.\n", template_total_amount + 1, uvar.templatebank);
return(RADPUL_EVAL);
}
}
else if(feof(templatebank)) // if EOF reached, break out of while loop
{
break;
}
else // if line couldn't be read and EOF is not reached -> error has happened
{
logMessage(error, true, "Couldn't determine number of templates in %s (%s).\n", uvar.templatebank, strerror(errno));
return(RADPUL_EIO);
}
}
// reset file position
if(fseek(templatebank, 0, SEEK_SET))
{
logMessage(error, true, "Couldn't reset template bank file: %s (%s).\n", uvar.templatebank, strerror(errno));
return(RADPUL_EIO);
}
logMessage(debug, true, "Total amount of templates: %i\n", template_total_amount);
// open checkpoint input stream
logMessage(debug, true, "Opening checkpoint file: %s\n", uvar.checkpointfile);
checkpoint = fopen(uvar.checkpointfile,"rb");
if(checkpoint == NULL)
{
logMessage(info, true, "Checkpoint file unavailable: %s (%s).\n", uvar.checkpointfile, strerror(errno));
logMessage(info, false, "Starting from scratch...\n");
template_counter = 0;
if(snprintf(cp_head.originalfile, sizeof(cp_head.originalfile), uvar.inputfile) >= sizeof(cp_head.originalfile))
{
logMessage(error, true, "Couldn't write input file %s name to checkpoint header.\n", uvar.inputfile);
return(RADPUL_EFILE);
}
}
else
{
// read the header information from checkpoint file
if(fread(&cp_head, sizeof(CP_Header), 1, checkpoint) != 1)
{
// if header is broken: just die
logMessage(error, true, "Premature end of data header in file: %s (%s)\n", uvar.checkpointfile, strerror(errno));
return(RADPUL_EFILE);
}
else
{
logMessage(debug, true, "Header read from checkpoint file.\n");
// determine if there's still work left
if(cp_head.n_template == template_total_amount)
{
logMessage(info, true, "Thank you but this work unit has already been processed completely...\n");
}
else if(cp_head.n_template < template_total_amount)
{
logMessage(info, true, "Continuing work on %s at template no. %d\n", cp_head.originalfile, cp_head.n_template);
}
else if(cp_head.n_template > template_total_amount)
{
logMessage(error, true, "Header checkpoint file %s contains inconsistent information about number of templates done (%d > %d).\n", uvar.checkpointfile, cp_head.n_template, template_total_amount);
return(RADPUL_EFILE);
}
// check command line information equals header information
if(strcmp(uvar.inputfile, cp_head.originalfile))
{
logMessage(error, true, "Input file on command line %s doesn't agree with input file %s from checkpoint header.\n", uvar.inputfile, cp_head.originalfile);
return(RADPUL_EFILE);
}
// read in candidates from checkpoint file
if(fread(candidates_all, sizeof(CP_cand), N_CAND, checkpoint) != N_CAND)
{
// XXX checksum for checkpoint
logMessage(error, true, "Couldn't read all candidates from checkpoint (%s)!", strerror(errno));
return(RADPUL_EIO);
}
if(ferror(checkpoint))
{
logMessage(error, true, "Couldn't read checkpoint file: %s (%s)\n", uvar.checkpointfile, strerror(errno));
return(RADPUL_EIO);
}
if(fclose(checkpoint))
{
logMessage(error, true, "Couldn't close checkpoint file: %s (%s).\n", uvar.checkpointfile, strerror(errno));
return(RADPUL_EIO);
}
if(uvar.debug)
{
logMessage(debug, true, "Candidates found so far:\n");
for(i = 0; i < N_CAND; i++)
{
logMessage(debug, false, "%d %6.12f %6.12f %6.12f %6.12f %d\n", candidates_all[i].f0, candidates_all[i].power, candidates_all[i].P_b, candidates_all[i].tau, candidates_all[i].Psi, candidates_all[i].n_harm);
}
}
// go to the next unused template in the template bank if checkpoint file exists
for( i = 0; i < cp_head.n_template; i++)
{
float P_tmp, tau_tmp, psi_tmp;
char line[FN_LENGTH];
if(NULL == fgets(line, FN_LENGTH, templatebank))
{
if(feof(templatebank))
{
logMessage(error, true, "Premature end of data in: %s\n", uvar.templatebank);
return(RADPUL_EIO);
}
else
{
logMessage(error, true, "Error while reading data from %s\n", uvar.templatebank);
return(RADPUL_EIO);
}
}
else if(sscanf(line, c_template_scan_format, &P_tmp, &tau_tmp, &psi_tmp) != 3)
{
logMessage(error, true, "Couldn't read complete line %d in %s\n", i, uvar.templatebank);
return(RADPUL_EIO);
}
}
// set template_counter to value in checkpoint header
template_counter = cp_head.n_template;
}
}
// open input stream
logMessage(debug, true, "Opening input file: %s\n", uvar.inputfile);
input = gzopen(uvar.inputfile,"rb");
if(input == NULL)
{
logMessage(error, true, "Couldn't open input file: %s (%s)\n", uvar.inputfile, strerror(errno));
return(RADPUL_EIO);
}
// read data header
logMessage(debug, true, "Reading header from time series file: %s\n", uvar.inputfile);
if(gzread(input, &data_head, sizeof(DD_Header)) != sizeof(DD_Header))
{
logMessage(error, true, "Premature end of data in file: %s (%s; %s)\n", uvar.inputfile, gzerror(input, NULL), strerror(errno));
gzclose_r(input);
return(RADPUL_EIO);
}
// convert little endian input file header if necessary
if(big_endian)
{
// double
endian_swap((uint8_t*) &data_head.tsample, sizeof(data_head.tsample), 1);
endian_swap((uint8_t*) &data_head.tobs, sizeof(data_head.tobs), 1);
endian_swap((uint8_t*) &data_head.timestamp, sizeof(data_head.timestamp), 1);
endian_swap((uint8_t*) &data_head.fcenter, sizeof(data_head.fcenter), 1);
endian_swap((uint8_t*) &data_head.fchan, sizeof(data_head.fchan), 1);
endian_swap((uint8_t*) &data_head.RA, sizeof(data_head.RA), 1);
endian_swap((uint8_t*) &data_head.DEC, sizeof(data_head.DEC), 1);
endian_swap((uint8_t*) &data_head.gal_l, sizeof(data_head.gal_l), 1);
endian_swap((uint8_t*) &data_head.gal_b, sizeof(data_head.gal_b), 1);
endian_swap((uint8_t*) &data_head.AZstart, sizeof(data_head.AZstart), 1);
endian_swap((uint8_t*) &data_head.ZAstart, sizeof(data_head.ZAstart), 1);
endian_swap((uint8_t*) &data_head.ASTstart, sizeof(data_head.ASTstart), 1);
endian_swap((uint8_t*) &data_head.LSTstart, sizeof(data_head.LSTstart), 1);
endian_swap((uint8_t*) &data_head.DM, sizeof(data_head.DM), 1);
endian_swap((uint8_t*) &data_head.scale, sizeof(data_head.scale), 1);
// uint32
endian_swap((uint8_t*) &data_head.filesize, sizeof(data_head.filesize), 1);
endian_swap((uint8_t*) &data_head.datasize, sizeof(data_head.datasize), 1);
endian_swap((uint8_t*) &data_head.nsamples, sizeof(data_head.nsamples), 1);
// uint 16
endian_swap((uint8_t*) &data_head.smprec, sizeof(data_head.smprec), 1);
endian_swap((uint8_t*) &data_head.nchan, sizeof(data_head.nchan), 1);
endian_swap((uint8_t*) &data_head.nifs, sizeof(data_head.nifs), 1);
endian_swap((uint8_t*) &data_head.lagformat, sizeof(data_head.lagformat), 1);
endian_swap((uint8_t*) &data_head.sum, sizeof(data_head.sum), 1);
endian_swap((uint8_t*) &data_head.level, sizeof(data_head.level), 1);
}
// dump header information to stdout
if(uvar.debug)
{
logMessage(info, true, "Header contents:\n");
logMessage(info, false, "Original WAPP file: %s\n", data_head.originalfile);
logMessage(info, false, "Sample time in microseconds: %g\n", data_head.tsample);
logMessage(info, false, "Observation time in seconds: %.8g\n", data_head.tobs);
logMessage(info, false, "Time stamp (MJD): %.17g\n", data_head.timestamp);
logMessage(info, false, "Number of samples/record: %d\n", data_head.smprec);
logMessage(info, false, "Center freq in MHz: %.10g\n", data_head.fcenter);
logMessage(info, false, "Channel band in MHz: %.9g\n", data_head.fchan);
logMessage(info, false, "Number of channels/record: %d\n", data_head.nchan);
logMessage(info, false, "Nifs: %d\n", data_head.nifs);
logMessage(info, false, "RA (J2000): %.12g\n", data_head.RA);
logMessage(info, false, "DEC (J2000): %.12g\n", data_head.DEC);
logMessage(info, false, "Galactic l: %.7g\n", data_head.gal_l);
logMessage(info, false, "Galactic b: %.7g\n", data_head.gal_b);
logMessage(info, false, "Name: %s\n", data_head.name);
logMessage(info, false, "Lagformat: %d\n", data_head.lagformat);
logMessage(info, false, "Sum: %d\n", data_head.sum);
logMessage(info, false, "Level: %d\n", data_head.level);
logMessage(info, false, "AZ at start: %.9g\n", data_head.AZstart);
logMessage(info, false, "ZA at start: %.9g\n", data_head.ZAstart);
logMessage(info, false, "AST at start: %.9g\n", data_head.ASTstart);
logMessage(info, false, "LST at start: %.9g\n", data_head.LSTstart);
logMessage(info, false, "Project ID: %s\n", data_head.proj_id);
logMessage(info, false, "Observers: %s\n", data_head.observers);
logMessage(info, false, "File size (bytes): %d\n", data_head.filesize);
logMessage(info, false, "Data size (bytes): %d\n", data_head.datasize);
logMessage(info, false, "Number of samples: %d\n", data_head.nsamples);
logMessage(info, false, "Trial dispersion measure: %g cm^-3 pc\n", data_head.DM);
logMessage(info, false, "Scale factor: %g\n", data_head.scale);
}
/*----------------------------------------------
NO SANITY CHECK OF HEADER DATA HERE AS LONG AS
THE FINAL HEADER FORMAT IS NOT EXACTLY DEFINED
----------------------------------------------*/
// drop header information into temporary param array
// convert RA to radian
hrs = floor(data_head.RA/10000.0);
min = floor((data_head.RA - 10000.0*hrs)/100.0);
sec = data_head.RA - 10000.0*hrs - 100.0*min;
// set sky position RA in temporary struct
search_params_tmp.skypos_rac = M_PI*(hrs/12.0 + min/720.0 + sec/43200.0);
// convert DEC to radian
if(data_head.DEC < 0.0)
{
hrs = floor(-data_head.DEC/10000.0);
min = floor(-(data_head.DEC + 10000.0*hrs)/100.0);
sec = -(data_head.DEC + 10000.0*hrs + 100.0*min);
// set sky position DEC in temporary struct
search_params_tmp.skypos_dec = -M_PI*(hrs/180.0 + min/10800.0 + sec/648000.0);
}
else
{
hrs = floor(data_head.DEC/10000.0);
min = floor((data_head.DEC - 10000.0*hrs)/100.0);
sec = data_head.DEC - 10000.0*hrs - 100.0*min;
// set sky position DEC in temporary struct
search_params_tmp.skypos_dec = M_PI*(hrs/180.0 + min/10800.0 + sec/648000.0);
}
// set DM in temporary struct
search_params_tmp.dispersion_measure = data_head.DM;
// remember number of original time samples
n_unpadded = (unsigned int)data_head.nsamples;
n_unpadded_format = t_series_4bit ? n_unpadded * 0.5 : n_unpadded;
// apply padding
data_head.nsamples = (int)(uvar.padding*data_head.nsamples + 0.5);
// allocate memory for compressed dedispersed time series
logMessage(debug, true, "Allocating memory for dedispersed compressed time series...\n");
if(t_series_4bit) {
t_series_dd_comp4 = (unsigned char *) calloc(n_unpadded_format, sizeof(unsigned char));
if(t_series_dd_comp4 == NULL)
{
logMessage(error, true, "Couldn't allocate %d bytes of memory for dedispersed 4-bit compressed time series.\n", n_unpadded_format*sizeof(unsigned char));
return(RADPUL_EMEM);
}
}
else {
t_series_dd_comp8 = (signed char *) calloc(n_unpadded_format, sizeof(signed char));
if(t_series_dd_comp8 == NULL)
{
logMessage(error, true, "Couldn't allocate %d bytes of memory for dedispersed 8-bit compressed time series.\n", n_unpadded_format*sizeof(signed char));
return(RADPUL_EMEM);
}
}
// read dedispersed timeseries
logMessage(debug, true, "Reading dedispersed time series from file: %s\n", uvar.inputfile);
if( ( t_series_4bit && gzread(input, t_series_dd_comp4, sizeof(unsigned char) * n_unpadded_format) != sizeof(unsigned char) * n_unpadded_format) ||
(!t_series_4bit && gzread(input, t_series_dd_comp8, sizeof(signed char) * n_unpadded_format) != sizeof(signed char) * n_unpadded_format) )
{
logMessage(error, true, "Premature end of data in file: %s (%s; %s)\n", uvar.inputfile, gzerror(input, NULL), strerror(errno));
gzclose_r(input);
return(RADPUL_EIO);
}
// close input stream
if(gzclose_r(input))
{
logMessage(error, true, "Couldn't close input file: %s (%s; %s)\n", uvar.inputfile, gzerror(input, NULL), strerror(errno));
return(RADPUL_EIO);
}
// allocate memory for uncompressed dedispersed time series
logMessage(debug, true, "Allocating memory for dedispersed uncompressed time series.\n");
t_series_dd.host_ptr = (float *) calloc(n_unpadded, sizeof(float));
if(t_series_dd.host_ptr == NULL)
{
logMessage(error, true, "Couldn't allocate %d bytes of memory for dedispersed uncompressed time series.\n", n_unpadded*sizeof(float));
return(RADPUL_EMEM);
}
// convert compressed single-byte data back into 4-byte floats
for(i = 0; i < n_unpadded_format; i ++)
{
if(t_series_4bit) {
// read in the two samples packed in one char and convert into floats
t_series_dd.host_ptr[2*i + 1] = (float)(t_series_dd_comp4[i]%16)/data_head.scale;
t_series_dd.host_ptr[2*i] = (float)(t_series_dd_comp4[i]>>4)/data_head.scale;
}
else {
// "unpack" single char sample
t_series_dd.host_ptr[i] = t_series_dd_comp8[i]/data_head.scale;
}
}
// free compressed time series
if(t_series_4bit) {
free(t_series_dd_comp4);
}
else {
free(t_series_dd_comp8);
}
/*---------------------------------------------------------------------------
WHITENING OF THE POWERSPECTRUM OF THE TIME SERIES AND ZAPPING OF KNOWN RFIS
-------------------------------------------------------------------------*/
logMessage(debug, true, "Starting whitening of the powerspectrum of the timeseries and zapping of known RFIs.\n");
if(uvar.white)
{
FILE *zaplist = NULL;
float norm_factor;
float *time_series;
float *powerspectrum;
float *running_median;
int32_t seed = 0;
int white_size;
int line_counter = 0;
unsigned int fft_size;
unsigned int window_2 = (int)(0.5*uvar.window + 0.5);
fftwf_complex *fft;
fftwf_plan fft_plan;
gsl_rng *r;
// if input is N real numbers, output has N/2 + 1 non-redundant entries
fft_size = (unsigned int)(0.5*data_head.nsamples + 0.5) + 1;
// sanity check for window size
if(fft_size < uvar.window)
{
logMessage(error, true, "Running median window (%d bins) is too wide for data set (%d bins)!\n", uvar.window, fft_size);
return(RADPUL_EVAL);
}
// use fftwf_malloc for allocation: this is recommended by FFTW (see manual: section 2.1, page 3)
fft = (fftwf_complex*) fftwf_malloc(sizeof(fftwf_complex)*fft_size);
if(fft == NULL)
{
logMessage(error, true, "Couldn't allocate %d bytes of memory for FFT.\n", fft_size*sizeof(fftwf_complex));
return(RADPUL_EMEM);
}
// allocate memory for time series and its FFT
#ifdef BRP_FFT_INPLACE
// note that fft array is always at least as long as input array, so no problem here
// sharing both for inplace transform
// BUT we have to take care explicitly about the zero-padding, as fft wasn't allocated with calloc.
time_series = (float *) fft;
for(i=n_unpadded; i < data_head.nsamples; i++) {
time_series[i]=0.0f;
}
#else
time_series = (float *) calloc(data_head.nsamples, sizeof(float));
if(time_series == NULL)
{
logMessage(error, true, "Couldn't allocate %d bytes of memory for time series.\n", data_head.nsamples*sizeof(float));
return(RADPUL_EMEM);
}
#endif
// create zero-padded time series
for(i = 0; i < n_unpadded; i++)
time_series[i] = t_series_dd.host_ptr[i];
// get seed for random number generator from the dedispersed time series itself
seed = *((int32_t*)t_series_dd.host_ptr);
logMessage(info, true, "Seed for random number generator is %d.\n", seed);
// to conserve max working set size, free buffer here and reallocate it later when needed.
free(t_series_dd.host_ptr);
// compute FFT of the time series
fft_plan = fftwf_plan_dft_r2c_1d(data_head.nsamples, time_series, fft, FFTW_ESTIMATE);
fftwf_execute(fft_plan);
fftwf_destroy_plan(fft_plan);
// allocate memory for the array containing the periodogramm
powerspectrum = (float *) calloc(fft_size, sizeof(float));
if(powerspectrum == NULL)
{
logMessage(error, true, "Couldn't allocate %d bytes of memory for power spectrum.\n", fft_size*sizeof(float));
return(RADPUL_EMEM);
}
// get the corresponding periodogramm, ignore DC element
for(i = 1; i < fft_size; i++)
powerspectrum[i] = gsl_pow_2(fft[i][0]) + gsl_pow_2(fft[i][1]);
// size of the running median array
white_size = fft_size - uvar.window + 1;
// allocate memory for the running median array
running_median = (float *) calloc(white_size, sizeof(float));
if(running_median == NULL)
{
logMessage(error, true, "Couldn't allocate %d bytes of memory for running median array.\n", white_size*sizeof(float));
return(RADPUL_EMEM);
}
// compute running median and store in running_median[]
rngmed(powerspectrum, fft_size, uvar.window, running_median);
// clean up
free(powerspectrum);
// periodogramm distribution of Gaussian should have
// median M_LN2 and mean of 1, scale the amplitudes
// so that the median is M_LN2
// ATTENTION: don't make window size too small, will bias
// estimation of median
// [0 ................ window_2 ................ white_size - 1 + window_2 ................ fft_size - 1]
for(i = 0; i < white_size; i++)
{
float factor = sqrt(M_LN2/running_median[i]);
fft[i + window_2][0] *= factor;
fft[i + window_2][1] *= factor;
}
// clean up
free(running_median);
/*------------------
ZAPPING KNOWN RFIS
------------------*/
logMessage(debug, true, "Start zapping known radio frequency interferences.\n");
// open zaplist file
zaplist = fopen(uvar.zaplistfile, "r");
if(NULL == zaplist)
{
logMessage(error, true, "Couldn't open zaplist file: %s (%s)\n", uvar.zaplistfile, strerror(errno));
return(RADPUL_EFILE);
}
// setup GSL random number generation
r = gsl_rng_alloc(gsl_rng_taus2);
gsl_rng_set(r, seed);
while( (NULL != fgets(line, FN_LENGTH, zaplist) && !feof(zaplist)) )
{
// var declarations
double t_obs = data_head.nsamples*data_head.tsample*MICROSEC;
unsigned int idx;
unsigned int idx_min;
unsigned int idx_max;
double fmin, fmax;