-
Notifications
You must be signed in to change notification settings - Fork 3
/
callback.c
1507 lines (1272 loc) · 58.6 KB
/
callback.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
#define _XOPEN_SOURCE
#include <inttypes.h>
#include <sys/time.h>
#include <time.h>
#include <string.h>
#include "callback.h"
#include "corrspec.h"
#include <errno.h>
#include <curl/curl.h>
#include "influx.h"
#include <Python.h>
#include <stdio.h>
#include <stdbool.h>
#include <fitsio.h>
#define PI 3.14159
#define BUFSIZE 256
#define DEBUG 0
#define DOQC 1
// Function to perform circular shift by -1 [UNUSED]
// functionally identical to the even/odd IQ[i+1] scheme
// when IQ[last] is set zero via Hann window
void circularShiftLeft(float arr[], int size) {
if (size <= 1) return; // No shift needed for arrays of size 0 or 1
float firstElement = arr[0]; // Store the first element
// Shift all elements one position to the left
for (int i = 0; i < size - 1; i++) {
arr[i] = arr[i + 1];
}
// Place the first element at the end of the array
arr[size - 1] = firstElement;
}
void get_git_commit_info(const char *filename, char *commit_info) {
char command[BUFSIZ];
FILE *fp;
char hash[BUFSIZ];
// Construct the command to get the commit hash
snprintf(command, sizeof(command), "git log -1 --format=%%cd --date=format-local:'%%Y-%%m-%%d %%H:%%M:%%S %%Z' --pretty=format:\"Last commit %%h by %%an %%ad\" -- %s", filename);
fp = popen(command, "r");
if (fp == NULL) {
perror("popen");
exit(EXIT_FAILURE);
}
fgets(hash, sizeof(hash), fp);
pclose(fp);
hash[strcspn(hash, "\n")] = 0; // Remove trailing newline
// Combine hash and date into the commit_info string
snprintf(commit_info, BUFSIZ+sizeof(filename), "%s %s", filename, hash);
}
void get_proctime(char *proctime) {
char command[BUFSIZ];
FILE *fp;
char date[BUFSIZ];
snprintf(command, sizeof(command), "date +%%Y%%m%%d_%%H%%M%%S");
fp = popen(command, "r");
if (fp == NULL) {
perror("popen");
exit(EXIT_FAILURE);
}
fgets(date, sizeof(date), fp);
pclose(fp);
date[strcspn(date, "\n")] = 0; // Remove trailing newline
snprintf(proctime, BUFSIZ, "%s", date);
}
void append_to_fits_table(const char *filename, struct s_header *fits_header, double *array, int THOTID) {
fitsfile *fptr; // FITS file pointer
//
int status = 0; // CFITSIO status value MUST be initialized to zero!
int hdutype;
int array_length;
long nrows;
char extname[] = "DATA_TABLE";
long n_elements = sizeof(array) / sizeof(array[0]);
CURL *curl;
char *query = malloc(BUFSIZ);
char *buf;
char commit_info[256];
char proctime[256];
int IF_index, LO_index;
float crpix = 0.;
float crval = 0.;
float cdelt;
char line[4];
float linefreq;
int band, npix;
int syntmult;
// Try to open the FITS file in read/write mode. If it doesn't exist, create a new one.
if (fits_open_file(&fptr, filename, READWRITE, &status)) {
if (status == FILE_NOT_OPENED) {
status = 0; // Reset the status
if (fits_create_file(&fptr, filename, &status)) {
fits_report_error(stderr, status); // Print any error message
return;
}
// Create a primary array image (needed before any extensions can be created)
if (fits_create_img(fptr, BYTE_IMG, 0, NULL, &status)) {
fits_report_error(stderr, status); // Print any error message
return;
}
// Construct the primary FITS HEADER
// Various indices and keywords in the primary header that depend on Band #
if (fits_header->unit == 6){ //ACS5 B1
IF_index = 0;
LO_index = 2;
cdelt = 5000./511.;
strcpy(line, "NII");
linefreq = 1461132.000000; //MHz
band = 1;
npix = 512;
syntmult = 108;
}
if (fits_header->unit == 4){ //ACS3 B2
IF_index = 1;
LO_index = 3;
cdelt = 5000./1023.;
strcpy(line, "CII");
linefreq = 1900536.9000000; //MHz
band = 2;
npix = 1024;
syntmult = 144;
}
// Create some Primary header keyword value pairs and fill them from the current fits_header struct
fits_write_key(fptr, TINT, "CALID", &fits_header->CALID, "ID of correlator calibration", &status);
// Spectral scaling
fits_write_key(fptr, TSTRING, "CUNIT1", "MHz", "Spectral unit", &status);
fits_write_key(fptr, TFLOAT, "CRPIX1", &crpix, "Index location", &status);
fits_write_key(fptr, TFLOAT, "CRVAL1", &crval, "Start of spectra (MHz)", &status);
fits_write_key(fptr, TFLOAT, "CDELT1", &cdelt, "Channel width (MHz)", &status);
// We only want to fill the primary header once, so don't bother with the fits_header struct,
// which is per extension table row, just get directly from influx now
// Note: This is a pretty high overhead task talking to the InfluxDB, but we only need to do it once per file
fits_write_key(fptr, TINT, "HKSCANID", &THOTID, "nearest H/K measurement", &status);
// new items 8-14
fits_write_key(fptr, TSTRING, "TELESCOP", "GUSTO", "", &status);
fits_write_key(fptr, TSTRING, "LINE", &line, "", &status);
fits_write_key(fptr, TFLOAT, "LINEFREQ", &linefreq, "", &status);
fits_write_key(fptr, TINT, "BAND", &band, "GUSTO band #", &status);
fits_write_key(fptr, TINT, "NPIX", &npix, "N spec pixels", &status);
fits_write_key(fptr, TSTRING, "DLEVEL", "0.7", "data level", &status);
get_proctime(proctime);
fits_write_key(fptr, TSTRING, "Proctime", proctime, "processing time", &status);
fits_write_key(fptr, TINT, "SER_FLAG", "0", "SERIES FLAG", &status);
fits_write_comment(fptr, " Housekeeping Temperatures", &status);
// Ambient HK_TEMP 0 1 2 3 4 5 6 7
const char *hktemp_names[]={"CRADLE02","CRYCSEBK","CRYOPORT","CALMOTOR","CRADLE03","QAVCCTRL","COOLRTRN","FERADIAT", \
"CRYCSEFT","CRADLE04","CONELOAD","OAVCCTRL","COOLSUPL","CRADLE01","EQUILREF","SECONDRY"};
// 8 9 10 11 12 13 14 15
const char *hktemp_descs[]={"Cradle 2 temp (C)", \
"Cryostat Back temp (C)", \
"Cryostat pumpout port temp (C)", \
"Calibration flip mirror motor temp (C)", \
"Cradle 3 temp (C)", \
"QCL AVC Cryocooler CTRL temp (C)", \
"Cooling Loop Return temp (C)", \
"Front End Radiator temp (C)", \
"Cryostat Left Side temp (C)", \
"Cradle 4 temp (C)", \
"Calibration load temp (C)", \
"OVCS AVC Cryocooler CTRL temp (C)", \
"Cooling Loop Supply temp (C)", \
"Cradle 1 temp (C)", \
"Equilibar Reference temp (C)", \
"Secondary temp (C)"};
curl = init_influx();
sprintf(query, "&q=SELECT * FROM /^HK_TEMP*/ WHERE scanID=~/^%d/ LIMIT 1", THOTID);
influxReturn = influxWorker(curl, query);
for (int i=0; i<influxReturn->length; i++){
if( strcmp(hktemp_names[i], "CONELOAD"))
fits_write_key(fptr, TFLOAT, hktemp_names[i], &influxReturn->value[i], hktemp_descs[i], &status);
}
freeinfluxStruct(influxReturn);
fits_write_comment(fptr, " LO Chain Temperatures", &status);
// LO AD590 0 1 10 11 2 3
const char *lotemp_names[]={"UNUSED ","B1_SYNTH","B1_PWR_3","B1_PWR_4","UNUSED ","UNUSED ", \
"B1M5_AMP","UNUSED ","UNUSED ","UNUSED ","B1_PWR_1","B1_PWR_2", \
"B2_UCTRL","B2MLTDRV","B2_PWR_3","B2_PWR_4","UNUSED ","UNUSED ", \
"UNUSED ","B2AVA183","B1M5MULT","B2M5_AMP","B2_PWR_1","B2_PWR_2"};
// 4 5 6 7 8 9
const char *lotemp_descs[]={"UNUSED", \
"B1 LO Synthsizer", \
"B1 LO Pwr Box 3", \
"B1 LO Pwr Box 4", \
"UNUSED", \
"UNUSED", \
"B1 LO Spacek amplifier Ch5", \
"UNUSED", \
"UNUSED", \
"UNUSED", \
"B1 LO Pwr Box 1", \
"B1 LO Pwr Box 2", \
"B2 MK66FX uCTRL", \
"B2 Mult Driver", \
"B2 LO Pwr 3", \
"B2 LO Pwr 4", \
"UNUSED", \
"UNUSED", \
"UNUSED", \
"B2 LO X-band Amplifier", \
"B1 LO final tripler Ch5", \
"B2 LO Spacek amplifier Ch5", \
"B2 LO Pwr Box 1", \
"B2 LO Pwr Box 2"};
curl = init_influx();
sprintf(query, "&q=SELECT * FROM /^B1_AD590_*/ WHERE scanID=~/^%d/ LIMIT 1", THOTID);
influxReturn = influxWorker(curl, query);
for (int i=0; i<influxReturn->length; i++){
if( strcmp(lotemp_names[i], "UNUSED ")){
fits_write_key(fptr, TFLOAT, lotemp_names[i], &influxReturn->value[i], lotemp_descs[i], &status);
}
}
freeinfluxStruct(influxReturn);
// Not sure why yet, but I can't parse B1 AND B2 AD590s. Do it again.
curl = init_influx();
sprintf(query, "&q=SELECT * FROM /^B2_AD590_*/ WHERE scanID=~/^%d/ LIMIT 1", THOTID);
influxReturn = influxWorker(curl, query);
for (int i=0; i<influxReturn->length; i++){
if( strcmp(lotemp_names[i+12], "UNUSED ")){
fits_write_key(fptr, TFLOAT, lotemp_names[i+12], &influxReturn->value[i], lotemp_descs[i+12], &status);
}
}
freeinfluxStruct(influxReturn);
// Cryogenic temps
fits_write_comment(fptr, " Cryogenic Temperatures", &status);
const char *cryo_descs[]= {"temp inner shield (K)", \
"temp inner vapor shield (K)", \
"temp LNA (K)", \
"temp mixers (K)", \
"temp outer shield (K)", \
"temp outer vapor shield (K)", \
"temp QCL (K)", \
"temp liquid-He tank (K)"};
curl = init_influx();
const char *cryo_names[]={"T_IS", "T_IVCS", "T_LNA", "T_MIXER","T_OS", "T_OVCS", "T_QCL", "T_TANK"};
sprintf(query, "&q=SELECT * FROM /^DT670*/ WHERE scanID=~/^%d/ LIMIT 1", THOTID);
influxReturn = influxWorker(curl, query);
for (int i=0; i<influxReturn->length; i++)
fits_write_key(fptr, TFLOAT, cryo_names[i], &influxReturn->value[i], "Cryogenic temps (K)", &status);
freeinfluxStruct(influxReturn);
// Geographic location and AZ EL pointing
fits_write_comment(fptr, " Geographic location and tuning", &status);
curl = init_influx();
sprintf(query, "&q=SELECT * FROM \"udpPointing\" WHERE scanID=~/^%d/ LIMIT 1", THOTID);
influxReturn = influxWorker(curl, query);
fits_write_key(fptr, TFLOAT, "GOND_ALT", &influxReturn->value[0], "Gondola altitude (m)", &status);
fits_write_key(fptr, TFLOAT, "GOND_LAT", &influxReturn->value[4], "Gondola latitude (deg)", &status);
fits_write_key(fptr, TFLOAT, "GOND_LON", &influxReturn->value[5], "Gondola longitude (deg)", &status);
fits_write_key(fptr, TFLOAT, "ELEVATON", &influxReturn->value[3], "Pointing Elevation (deg)", &status);
freeinfluxStruct(influxReturn);
// Last VLSR tuning from InfluxDB anytime before current obs time
// primary header telemetry objects
curl = init_influx();
sprintf(query, "&q=SELECT * FROM \"tuning\" WHERE time<=%d000000000 ORDER BY time DESC LIMIT 1" , (int)fits_header->fulltime);
influxReturn = influxWorker(curl, query);
fits_write_key(fptr, TSTRING,"OBJECT", &influxReturn->text, "Name of the target object", &status);
fits_write_key(fptr, TFLOAT, "IF0", &influxReturn->value[IF_index], "Frequency (MHz) of VLSR", &status);
fits_write_key(fptr, TFLOAT, "SYNTFREQ", &influxReturn->value[LO_index], "Synth (MHz)", &status);
fits_write_key(fptr, TINT, "SYNTMULT", &syntmult, "Synth Multiplier", &status);
fits_write_key(fptr, TFLOAT, "VLSR", &influxReturn->value[4], "Commanded VLSR (km/s)", &status);
freeinfluxStruct(influxReturn);
// Create some Primary header comments and fill them
get_git_commit_info("The Corrspec GUSTO pipeline is customizable combining raw spectrometer files and flight \
houskeeping database into minimal header level0.5 baseband spectra or level0.7 full H/K\
fits files. see github.com/abegyoung/gusto-corr for documentation", commit_info);
if (fits_write_comment(fptr, commit_info, &status)) {
fits_report_error(stderr, status);
return;
}
get_git_commit_info("corrspec.c", commit_info);
if (fits_write_comment(fptr, commit_info, &status)) {
fits_report_error(stderr, status);
return;
}
get_git_commit_info("callback.c", commit_info);
if (fits_write_comment(fptr, commit_info, &status)) {
fits_report_error(stderr, status);
return;
}
get_git_commit_info("influx.c", commit_info);
if (fits_write_comment(fptr, commit_info, &status)) {
fits_report_error(stderr, status);
return;
}
// Define the column parameters
char *ttype[] ={"MIXER", "NINT", "UNIXTIME", "NBYTES", "CORRTIME", "INTTIME", "ROW_FLAG", "Ihigh", \
"Qhigh", "Ilow", "Qlow", "Ierr", "Qerr", "VIhi", "VQhi", "VIlo", "VQlo", "scanID", \
"subScan", "scan_type", "THOT", "RA", "DEC", "filename", "PSat", "Imon", "Gmon", \
"spec", "CHANNEL_FLAG"};
char *tunit[] ={" ", " ", "sec", " ", " ", "sec", " ", "counts", "counts", "counts", \
"counts", " ", " ", "Volts", "Volts", "Volts", "Volts", " ", " ", " ", \
"Kelvin", "degrees", "degrees", "text", "Amps", "uA", "Amps", " ", " "};
// All header values are signed 32-bit except UNIXTIME which is uint64_t
char *tform[29];
tform[0] = "1J"; //int mixer
tform[1] = "1J"; //int nint
tform[2] = "1D"; //double 64 bit unixtime+fractional
tform[3] = "1J"; //int nbytes
tform[4] = "1J"; //int corrtime
tform[5] = "1E"; //float integration time
tform[6] = "1J"; //32 bit row flag
tform[7] = "1J"; //int ihi
tform[8] = "1J"; //int qhi
tform[9] = "1J"; //int ilo
tform[10] = "1J"; //int qlo
tform[11] = "1J"; //int ierr
tform[12] = "1J"; //int qerr
tform[13] = "1E"; //float Vdac
tform[14] = "1E"; //float Vdac
tform[15] = "1E"; //float Vdac
tform[16] = "1E"; //float Vdac
tform[17] = "1J"; //int scanID
tform[18] = "1J"; //int subScan
tform[19] = "6A"; //char scan type
tform[20] = "1E"; //float THOT
tform[21] = "1E"; //float RA
tform[22] = "1E"; //float DEC
tform[23] = "48A";//char filename
tform[24] = "1E"; //float PSat
tform[25] = "1E"; //float Imon
tform[26] = "1E"; //float Gmon
// Various indices and keywords in the per row header that depend on Band #
if (fits_header->unit==6){ //ACS5 B1
tform[27] = "512E"; //32 bit float
tform[28] = "512I"; //16 bit int
}
if (fits_header->unit==4){ //ACS3 B2
tform[27] = "1024E"; //32 bit float
tform[28] = "1024I"; //16 bit int
}
int tfields = 29;
// Create a binary table
if (fits_create_tbl(fptr, BINARY_TBL, 0, tfields ,ttype, tform, tunit, extname, &status)) {
fits_report_error(stderr, status); // Print any error message
return;
}
} else {
fits_report_error(stderr, status); // Print any error message
return;
}
} ////////// END PRIMARY HEADER SECTION //////////
// need to do this *again* because the one several lines back is only done for the fits file creation.
// that bug took a day to find.
if (fits_header->unit==6){ //ACS5 B1
array_length=512;
}
if (fits_header->unit==4){ //ACS3 B2
array_length=1024;
}
// Move to the named HDU (where the table is stored)
if (fits_movnam_hdu(fptr, BINARY_TBL, extname, 0, &status)) {
fits_report_error(stderr, status); // Print any error message
return;
}
// Get the current number of rows in the table
if (fits_get_num_rows(fptr, &nrows, &status)) {
fits_report_error(stderr, status); // Print any error message
return;
}
// insert a single empty row at the end of the output table
if (fits_insert_rows(fptr, nrows, 1, &status)) {
fits_report_error(stderr, status); // Print any error message
return;
}
// Write the header data
fits_write_col(fptr, TINT32BIT, 1, nrows+1, 1, 1, &fits_header->mixer, &status);
fits_write_col(fptr, TINT32BIT, 2, nrows+1, 1, 1, &fits_header->nint, &status);
fits_write_col(fptr, TDOUBLE, 3, nrows+1, 1, 1, &fits_header->fulltime, &status);
fits_write_col(fptr, TINT32BIT, 4, nrows+1, 1, 1, &fits_header->nbytes, &status);
fits_write_col(fptr, TINT32BIT, 5, nrows+1, 1, 1, &fits_header->corrtime, &status);
fits_write_col(fptr, TFLOAT, 6, nrows+1, 1, 1, &fits_header->inttime, &status);
fits_write_col(fptr, TINT32BIT, 7, nrows+1, 1, 1, &fits_header->row_flag, &status);
fits_write_col(fptr, TINT32BIT, 8, nrows+1, 1, 1, &fits_header->Ihi, &status);
fits_write_col(fptr, TINT32BIT, 9, nrows+1, 1, 1, &fits_header->Qhi, &status);
fits_write_col(fptr, TINT32BIT, 10, nrows+1, 1, 1, &fits_header->Ilo, &status);
fits_write_col(fptr, TINT32BIT, 11, nrows+1, 1, 1, &fits_header->Qlo, &status);
fits_write_col(fptr, TINT32BIT, 12, nrows+1, 1, 1, &fits_header->Ierr, &status);
fits_write_col(fptr, TINT32BIT, 13, nrows+1, 1, 1, &fits_header->Qerr, &status);
fits_write_col(fptr, TFLOAT, 14, nrows+1, 1, 1, &fits_header->VIhi, &status);
fits_write_col(fptr, TFLOAT, 15, nrows+1, 1, 1, &fits_header->VQhi, &status);
fits_write_col(fptr, TFLOAT, 16, nrows+1, 1, 1, &fits_header->VIlo, &status);
fits_write_col(fptr, TFLOAT, 17, nrows+1, 1, 1, &fits_header->VQlo, &status);
fits_write_col(fptr, TINT32BIT, 18, nrows+1, 1, 1, &fits_header->scanID, &status);
fits_write_col(fptr, TINT32BIT, 19, nrows+1, 1, 1, &fits_header->subScan, &status);
fits_write_col(fptr, TSTRING, 20, nrows+1, 1, 1, &fits_header->type, &status);
fits_write_col(fptr, TFLOAT, 21, nrows+1, 1, 1, &fits_header->THOT, &status);
fits_write_col(fptr, TFLOAT, 22, nrows+1, 1, 1, &fits_header->RA, &status);
fits_write_col(fptr, TFLOAT, 23, nrows+1, 1, 1, &fits_header->DEC, &status);
fits_write_col(fptr, TSTRING, 24, nrows+1, 1, 1, &fits_header->filename, &status);
// these change based on which mixer
// DEV 1 = B2M2 = psat[3]
// DEV 2 = B2M3 = psat[2]
// DEV 3 = B2M5 = psat[1]
// DEV 4 = B2M8 = psat[0]
//
int psat_index = (-1*fits_header->dev)+4;
fits_write_col(fptr, TFLOAT, 25, nrows+1, 1, 1, &fits_header->psat[psat_index], &status);
fits_write_col(fptr, TFLOAT, 26, nrows+1, 1, 1, &fits_header->imon[psat_index], &status);
fits_write_col(fptr, TFLOAT, 27, nrows+1, 1, 1, &fits_header->gmon[psat_index], &status);
// Write the spectra as a single 2*N column
if (fits_write_col(fptr, TDOUBLE, 28, nrows+1, 1, 1 * array_length, array, &status)) {
fits_report_error(stderr, status); // Print any error message
return;
}
// Write the channel flag as a single 2*N column
if (fits_write_col(fptr, TDOUBLE, 29, nrows+1, 1, 1 * array_length, array, &status)) {
fits_report_error(stderr, status); // Print any error message
return;
}
// Close the FITS file
if (fits_close_file(fptr, &status)) {
fits_report_error(stderr, status); // Print any error message
return;
}
if (DEBUG)
printf("Array appended as a new row in the FITS table successfully.\n");
}
void printDateTimeFromEpoch(time_t ts)
{
struct tm *tm = gmtime(&ts);
char buffer[26];
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", tm);
printf("UTC Date and Time: %s\n", buffer);
}
long get_seconds(const char *timestamp)
{
struct tm t;
char *pos;
memset(&t, 0, sizeof(struct tm));
strptime(timestamp, "%Y-%m-%dT%H:%M:%S", &t);
time_t seconds = mktime(&t) - 25200; //TODO: fix this hardcoded offset to UTC
return (long) seconds;
}
int numPlaces (int n)
{
if (n < 0) return numPlaces ((n == INT_MIN) ? INT_MAX: -n);
if (n < 10) return 1;
return 1 + numPlaces (n / 10);
}
char nthdigit(int x, int n)
{
while (n--) {
x /= 10;
}
return (x % 10) + '0';
}
// Callback function to process the file
void const callback(char *filein, int isREFHOT){
char *fullpath= malloc(48*sizeof(char));
strcpy(fullpath, filein); // make a copy leaving filein intact for later tokenization
char *datafile; // datafile is filename with no path - used in fits header
datafile = strrchr(fullpath, '/');
if (datafile != NULL) {
datafile++;
} else {
datafile = fullpath;
}
//char errfile[64] = "err.log";
// InfluxDB easy_curl objects
CURL *curl;
CURLcode res;
char *query = malloc(BUFSIZ);
char *query_list[] = {"_VIhi", "_VQhi", "_VIlo", "_VQlo"};
//timing
struct timeval begin, end;
gettimeofday(&begin, 0);
//correlator file objectsI
int N;
FILE *fp;
//FILE *fout;
//FILE *errf;
double P_I;
double P_Q;
double Ipwr;
double Qpwr;
struct corrType corr;
// correlator variables from datafile
uint64_t UNIXTIME;
int NINT;
int UNIT;
int DEV;
int NBYTES;
float FRAC;
int MIXER;
float FS_FREQ; // Full scale frequency, B1==5000MHz || B2==5000MHz
float dacV[4]; //0=VIhi, 1=VQhi, 2=VIlo, 3=VQlo
float VIhi, VQhi, VIlo, VQlo;
// For integer correlator lags
//int32_t *Rn;
//int32_t *Rn2;
// For normalized float correlator lags from Quant Corr
float *Rn;
float *Rn2;
// per row telemetry objects
float RA=0.;
float DEC=0.;
float THOT=0.;
float LO_PSat[4];
float HEBImon[4];
float LO_Gmon[4];
long THOT_time; // time at which HK_TEMP11 was taken (seconds since epoch)
// file open notification
printf("opened file: %s\n", filein);
fp = fopen(filein, "r");
// tokenize scanID from filename
char *token;
int position = 0;
int band = -1;
char *prefix=malloc(7*sizeof(char));;
int scanID = -1;
int subScan = -1;
int CALID = -1; // scanID of previous correlator calibration
int THOTID = -1; // scanID of most recent HK_TEMP11 relative to correlator timestamp
bool error = FALSE; // status of error which may end processing early
// Find file type from filename
int i=0;
char *ptr = NULL;
const char *prefix_names[]={"SRC", "REF", "OTF", "HOT", "COLD", "FOC", "UNK"};
// Use strtok to tokenize the filename using underscores as delimiters
// First use "/" to redact any relative path
//token = strtok(filein, "/");
//token = strtok(NULL, "/");
token = strtok(filein, "_");
// Iterate through the tokens until reaching the 2nd position
while (token != NULL ) {
if (position == 0 ) { //get band
if (strstr(token, "ACS3"))
band = 2;
if (strstr(token, "ACS5"))
band = 1;
printf("Band is: %d\n", band);
}
if (position == 1 ) { //get scan type
while ( ptr==NULL ){
ptr = strstr(token, prefix_names[i]);
i++;
}
int len = strlen(prefix_names[i-1]);
strncpy(prefix, ptr, len);
prefix[len] = '\0';
printf("The type is %s\n", prefix);
}
if (position == 2 ) { //get scanID
if (atoi(token)>0) scanID = atoi(token);
printf("The scanID is: %d\n", scanID);
}
if (position == 3 ) { //get subscanID
subScan = atoi(token);
printf("The data file index # is: %05d\n", subScan);
}
token = strtok(NULL, "_");
position++;
}
// override scan_type from filename
if( isREFHOT ){
strncpy(prefix, "REFHOT\0", 7);
}
// Build a regex with the range of the previous 16 scanID #s for Correlator DACs
char scanIDregex[512];
int pos = 0;
pos += sprintf(&scanIDregex[pos], "^(");
for (int k=0; k<15; k++){
pos += sprintf(&scanIDregex[pos], "%d|", scanID-k);
}
pos += sprintf(&scanIDregex[pos], "%d)$", scanID-15);
if (DEBUG)
printf("%s\n", scanIDregex);
// Build a regex with the range of the previous 12 and next 12 scanID #s for HK_TEMP11
char HOTregex[512];
pos = 0;
pos += sprintf(&HOTregex[pos], "^(");
for (int k=0; k<24; k++){
pos += sprintf(&HOTregex[pos], "%d|", scanID-k+12);
}
pos += sprintf(&HOTregex[pos], "%d)$", scanID-12);
if (DEBUG)
printf("%s\n", HOTregex);
// integer variables for fread from datafile
int32_t value;
uint32_t value1; // for first 32 bits of UNIXTIMRE
uint32_t value2; //
// figure out how many spectra in the file
fseek(fp, 24, SEEK_SET); // go to header position
fread(&value, 4, 1, fp);
int32_t bps = value; // get bytes per spectra
fseek(fp, 0L, SEEK_END);
int sz = ftell(fp); // get total bytes in file
fseek(fp, 0L, SEEK_SET); // go back to beginning of file
printf("File has %.1f spectra\n", (float)sz/bps);
int32_t header[22];
const char *header_names[]={"UNIT", "DEV", "NINT", "UNIXTIME", "FRAC", "NBYTES", "CORRTIME", \
"EMPTY", "Ihigh", "Qhigh", "Ilow", "Qlow", "Ierr", "Qerr"};
////////////////////////////// LOOP OVER ALL SPECTRA IN FILE ///////////////////////////////////
int gotHot = 0; //have we gotten the per row h/k based on unixtime yet?
// Start at beginning of data file
for (int j=0; j<(int)sz/bps; j++)
{
// Declare all Python objects for refpower
// pArgs
PyObject *pArgs;
PyObject *pValue;
// Python objects for quantization correction
PyObject *pArgsII, *pArgsQI, *pArgsIQ, *pArgsQQ;
PyObject *pListII, *pListQI, *pListIQ, *pListQQ;
PyObject *pValueII, *pValueQI, *pValueIQ, *pValueQQ;
// Arguments to relpower(XmonL, XmonH)
if (DOQC){
pArgs = PyTuple_New(2); // for relpower(XmonL, XmonH)
pArgsII = PyTuple_New(5); // for qc(ImonL, ImonH, ImonL, ImonH, corr.II)
pArgsIQ = PyTuple_New(5); // for qc(ImonL, ImonH, QmonL, QmonH, corr.IQ)
pArgsQI = PyTuple_New(5); // for qc(QmonL, QmonH, ImonL, ImonH, corr.IQ)
pArgsQQ = PyTuple_New(5); // for qc(QmonL, QmonH, QmonL, QmonH, corr.QQ)
}
if (DEBUG)
printf("The type is %s\n", prefix);
// Loop over header location
for (int i=0; i<22; i++){
if (i==3){
//UNIXTIME is 64 bits
fread(&value1, 4, 1, fp); //Least significant 32 bits
fread(&value2, 4, 1, fp); //Most significant 32 bis
UNIXTIME = (((uint64_t)value2 << 32) | value1 ) / 1000.; //unixtime is to msec, store as 1sec int
FRAC = (((uint64_t)value2 << 32) | value1 ) % 1000 ; //fractional part is 1msec
}
else{
fread(&value, 4, 1, fp);
}
header[i] = (value);
}
// data file *fp is now at start of lag data
if(!gotHot)
{
// Most recent HOT temperature from current scanID or ahead/behind 2 scanIDs
// sigh. InfluxDB v1.8 doesn't have an abs() function, so two queries sorted by time are
// needed to find the *nearest* hot load temp relative to a timestamp. TODO: test whether scanID regex helps speed
int time1, time2;
int scanID1, scanID2;
float temp1, temp2;
curl = init_influx();
sprintf(query, "&q=SELECT * FROM \"HK_TEMP11\" WHERE time>=%ld000000000 ORDER by time ASC LIMIT 1", UNIXTIME);
influxReturn = influxWorker(curl, query);
time1 = get_seconds(influxReturn->time);
scanID1 = influxReturn->scanID;
temp1 = influxReturn->value[0];
freeinfluxStruct(influxReturn);
curl = init_influx();
sprintf(query, "&q=SELECT * FROM \"HK_TEMP11\" WHERE time<=%ld000000000 ORDER by time DESC LIMIT 1", UNIXTIME);
influxReturn = influxWorker(curl, query);
time2 = get_seconds(influxReturn->time);
scanID2 = influxReturn->scanID;
temp2 = influxReturn->value[0];
THOT = influxReturn->value[0] + 273.13; //Kelvin -> Celsius
THOTID = influxReturn->scanID;
freeinfluxStruct(influxReturn);
// LO Drive currents
curl = init_influx();
if (band==1){ //ACS5 B1
sprintf(query, "&q=SELECT * FROM /^PSatI_B1M2|PSatI_B1M3|PSatI_B1M4|PSatI_B1M6/ WHERE time<=%ld000000000 ORDER by time DESC LIMIT 1", UNIXTIME);
}
if (band==2){ //ACS3 B2
sprintf(query, "&q=SELECT * FROM /^PSatI_B2M2|PSatI_B2M3|PSatI_B2M5|PSatI_B2M8/ WHERE time<=%ld000000000 ORDER by time DESC LIMIT 1", UNIXTIME);
}
influxReturn = influxWorker(curl, query);
for (int i=0; i<influxReturn->length; i++){
LO_PSat[i] = influxReturn->value[i]; // LO Drive Currents (Amps)
}
freeinfluxStruct(influxReturn);
// HEB Mixer Currents
curl = init_influx();
if (band==1){ //ACS5 B1
sprintf(query, "&q=SELECT * FROM /^biasCurB1M2|biasCurB1M3|biasCurB1M4|biasCurB1M6/ WHERE time<=%ld000000000 ORDER by time DESC LIMIT 1", UNIXTIME);
}
if (band==2){ //ACS3 B2
sprintf(query, "&q=SELECT * FROM /^biasCurB2M2|biasCurB2M3|biasCurB2M5|biasCurB2M8/ WHERE time<=%ld000000000 ORDER by time DESC LIMIT 1", UNIXTIME);
}
influxReturn = influxWorker(curl, query);
for (int i=0; i<influxReturn->length; i++){
HEBImon[i] = influxReturn->value[i]; // Mixer Currents (mA)
}
freeinfluxStruct(influxReturn);
// LO Gate Monitor
curl = init_influx();
if (band==1){ //ACS5 B1
sprintf(query, "&q=SELECT * FROM /^B1_GMONI_2|B1_GMONI_3|B1_GMONI_4|B1_GMONI_6/ WHERE time<=%ld000000000 ORDER by time DESC LIMIT 1", UNIXTIME);
}
if (band==2){ //ACS3 B2
sprintf(query, "&q=SELECT * FROM /^B2_GMONI_2|B2_GMONI_3|B2_GMONI_5|B2_GMONI_8/ WHERE time<=%ld000000000 ORDER by time DESC LIMIT 1", UNIXTIME);
}
influxReturn = influxWorker(curl, query);
for (int i=0; i<influxReturn->length; i++){
LO_Gmon[i] = influxReturn->value[i]; // Mixer Currents (mA)
}
freeinfluxStruct(influxReturn);
gotHot = 1;
///////////// FAST CADENCE HOUSEKEEPING - GOES INTO per row fits_header ////////////////
}
// fill variables from header array
UNIT = header[0];
DEV = header[1];
NINT = header[2];
//UNIXTIME = header[3]; 64 bits
//CPU = header[4]; broken?
NBYTES = header[5];
corr.corrtime = header[6];
//EMPTY header[7];
corr.Ihi = header[8];
corr.Qhi = header[9];
corr.Ilo = header[10];
corr.Qlo = header[11];
corr.Ierr = header[12];
corr.Qerr = header[13];
// Since we know UNIT and NLAGS, set correlator frequency and fits spectrum for later use
// And also secret decoder ring (unit,dev) -> (Mixer #)
int mixerTable[2][4] = {
{2, 3, 4, 6}, // band 1 mixers
{2, 3, 5, 8} // band 2 mixers
};
MIXER = mixerTable[band-1][DEV-1];
if (band==1){ //ACS5 B1
FS_FREQ = 5000.;
}
if (band==2){ //ACS3 B2
FS_FREQ = 5000.;
}
// Indication that this is a broken header file from correlator STOP signal
if (corr.Ierr!=0 || corr.Qerr!=0 || \
corr.Ihi==0 || corr.Qhi==0 || corr.Ilo==0 || corr.Qlo==0 || \
(corr.corrtime*256.)/(FS_FREQ*1000000.)<0.1 || (corr.corrtime*256.)/(FS_FREQ*1000000.)>10.0 )
{
printf("######################## ERROR ###########################\n");
printf("# #\n");
printf("# Error, data is no good! #\n");
printf("# Exiting! #\n");
printf("# #\n");
printf("######################## ERROR ###########################\n");
printf("CORRTIME was %.6f\n\n", (corr.corrtime*256.)/(FS_FREQ*1000000.));
error = TRUE;
break;
}
/////////// Get data for the HIGH SPEED Housekeeping for per row fits header ///////////
/////////// This data *does* change every spectra ///////////
// RA, DEC from InfluxDB 0.5s ahead or behind time
curl = init_influx();
sprintf(query, "&q=SELECT * FROM \"udpPointing\" WHERE \"scanID\"=~/^%d/ AND time>\%" PRIu64 "500000000 AND time<\%" PRIu64 "500000000", scanID, UNIXTIME-1, UNIXTIME+1);
influxReturn = influxWorker(curl, query);
RA = influxReturn->value[6];
DEC = influxReturn->value[2];
// Free the allocated memory from udpPointing
freeinfluxStruct(influxReturn);
if (DEBUG)
printf("======== RA=%.3f DEC=%.3f ==========\n", RA, DEC); //Info print
//
// Single SELECT for CORRELATOR DACS from current or nearest previous Correlator Cal
curl = init_influx();
sprintf(query, "&q=SELECT * FROM /^ACS%d_DEV%d_*/ WHERE \"scanID\"=~/^%s/ ORDER BY time DESC LIMIT 10", UNIT-1, DEV, scanIDregex);
influxReturn = influxWorker(curl, query);
dacV[0] = influxReturn->value[3]; //VIhi Order is reverse alphabetical from InfluxDB SELECT
dacV[1] = influxReturn->value[1]; //VQhi
dacV[2] = influxReturn->value[2]; //VIlo
dacV[3] = influxReturn->value[0]; //VQlo
CALID = influxReturn->scanID;
// Free Influx struct from ACS_DEV_VDAC
freeinfluxStruct(influxReturn);
// don't trust myself to rewrite the below, just copy from vector into floats
VIhi = dacV[0];
VQhi = dacV[1];
VIlo = dacV[2];
VQlo = dacV[3];
// this section unfuck-ifys special cases when ICE was off by one
if (VQlo==0.){
VIhi=VIhi-(VIlo-VQhi); //make up this lost data, it'l be close enough
VQhi = dacV[0];
VIlo = dacV[1];
VQlo = dacV[2];
}
if (VIhi==0.){ //Still no values? bail and don't make spectra
printf("######################## ERROR ###########################\n");
printf("# #\n");
printf("# Error, no DAC values! #\n");
printf("# Exiting! #\n");
printf("# #\n");
printf("######################## ERROR ###########################\n");
break;
}
// DEBUG
if (DEBUG)
printf("VIhi %.3f\tVQhi %.3f\tVIlo %.3f\tVQlo %.3f\n", VIhi, VQhi, VIlo, VQlo);
// Build the spectra filename and put it in the spectra directory
//char fileout[512];
//sprintf(fileout, "spectra/ACS%d_%s_%05d_DEV%d_INDX%04d_NINT%03d.txt", UNIT-1, prefix, scanID, DEV, subScan, j);
//fout = fopen(fileout, "w");
//read human readable "Number of Lags"
if (NBYTES==8256)
N = 512;
else if (NBYTES==6208)
N = 384;
else if (NBYTES==4160)
N = 256;
else if (NBYTES==2112)
N = 128;
int specA = (int) N/128 - 1;
//We don't know the lag # until we open the file, so malloc now
corr.II = malloc(N*sizeof(int32_t)); //Uncorrected ints
corr.QI = malloc(N*sizeof(int32_t));
corr.IQ = malloc(N*sizeof(int32_t));
corr.QQ = malloc(N*sizeof(int32_t));
corr.IIqc = malloc(N*sizeof(float)); //Normalized Quantization Corrected floats
corr.QIqc = malloc(N*sizeof(float));
corr.IQqc = malloc(N*sizeof(float));
corr.QQqc = malloc(N*sizeof(float));
//Rn = malloc(2*N*sizeof(int32_t)); //Rn,Rn2 ints for unquantization corrected
//Rn2 = malloc(4*N*sizeof(int32_t));
Rn = malloc(2*N*sizeof(float)); //Rn,Rn2 floats for normalizaed, quantization corrected
Rn2 = malloc(4*N*sizeof(float));
// Read lags in from file in order after header
for (int i=0; i<N; i++){
fread(&value, 4, 1, fp);
corr.II[i] = value;
fread(&value, 4, 1, fp);
corr.QI[i] = value;
fread(&value, 4, 1, fp);
corr.IQ[i] = value;
fread(&value, 4, 1, fp);
corr.QQ[i] = value;
}
// PASS THE UNCORRECTED LAGS INTO PYTHON FOR QUANTIZATION CORRECTION HERE !!!
if (DOQC){
// create a Python list and fill it with normalized uncorrected correlation coefficients
// Check for errors
if (pModule != NULL) {
// Get the function from the module
if (pFunc2 && PyCallable_Check(pFunc2)) {
// For first four arguments: XmonL, XmonH, YmonL, YmonH
// II
PyTuple_SetItem(pArgsII, 0, PyFloat_FromDouble((double)corr.Ilo/(double)corr.corrtime));
PyTuple_SetItem(pArgsII, 1, PyFloat_FromDouble((double)corr.Ihi/(double)corr.corrtime));
PyTuple_SetItem(pArgsII, 2, PyFloat_FromDouble((double)corr.Ilo/(double)corr.corrtime));
PyTuple_SetItem(pArgsII, 3, PyFloat_FromDouble((double)corr.Ihi/(double)corr.corrtime));
// IQ
PyTuple_SetItem(pArgsIQ, 0, PyFloat_FromDouble((double)corr.Ilo/(double)corr.corrtime));
PyTuple_SetItem(pArgsIQ, 1, PyFloat_FromDouble((double)corr.Ihi/(double)corr.corrtime));
PyTuple_SetItem(pArgsIQ, 2, PyFloat_FromDouble((double)corr.Qlo/(double)corr.corrtime));
PyTuple_SetItem(pArgsIQ, 3, PyFloat_FromDouble((double)corr.Qhi/(double)corr.corrtime));
// QI
PyTuple_SetItem(pArgsQI, 0, PyFloat_FromDouble((double)corr.Qlo/(double)corr.corrtime));
PyTuple_SetItem(pArgsQI, 1, PyFloat_FromDouble((double)corr.Qhi/(double)corr.corrtime));
PyTuple_SetItem(pArgsQI, 2, PyFloat_FromDouble((double)corr.Ilo/(double)corr.corrtime));
PyTuple_SetItem(pArgsQI, 3, PyFloat_FromDouble((double)corr.Ihi/(double)corr.corrtime));
// QQ
PyTuple_SetItem(pArgsQQ, 0, PyFloat_FromDouble((double)corr.Qlo/(double)corr.corrtime));
PyTuple_SetItem(pArgsQQ, 1, PyFloat_FromDouble((double)corr.Qhi/(double)corr.corrtime));
PyTuple_SetItem(pArgsQQ, 2, PyFloat_FromDouble((double)corr.Qlo/(double)corr.corrtime));
PyTuple_SetItem(pArgsQQ, 3, PyFloat_FromDouble((double)corr.Qhi/(double)corr.corrtime));
// For fifth argument: convert C array to a Python List
// Creates new reference here. pList** must be DECREF to free