-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAres.c
More file actions
executable file
·1546 lines (1393 loc) · 51.2 KB
/
Copy pathAres.c
File metadata and controls
executable file
·1546 lines (1393 loc) · 51.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************************************************************************************
* Ares.c
*
* Software to read beam data from (TEL_SHM) and create the FRB_SHM.
* COMPILE: gcc -g -O3 -Wall -Wextra -std=gnu99 Ares.c -o Ares -lm -lc
* USAGE: ./Ares [observation duration (seconds) = 3600]
mpicc -std=c99 -mtune=nocona -O3 -ffast-math -msse2 -lm -I. -g -fopenmp -O4
-lgomp -I /lustre_archive/apps/correlator/cuda-9.1/include -o Ares Ares.c
-D_XOPEN_SOURCE=700
*
*
******************************************************************************************************************************************************/
#define _POSIX_C_SOURCE 200809L
#include "acqpsr.h"
#include "frb_shm.h"
#include "gmrt_newcorr.h"
#include <float.h>
#include <math.h>
#include <mpi.h>
#include <omp.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/shm.h>
#include <sys/time.h>
#include <time.h>
// #define _XOPEN_SOURCE 700
// #define _DEFAULT_SOURCE
#include <unistd.h>
#define BeamHdrKey 1050
int commSize, myrank;
int bandsign;
float bandwidth;
static BeamHeaderType *dataHdr_TEL;
static RecType *Rec;
GlobalInfoType *dataBuffer_TEL;
BeamHeaderType *dataHdr_FRB;
DataBuffer *dataBuffer_FRB;
unsigned char *Shmp, *blkp_TEL, *blkp_FRB;
unsigned int RecNum = 0, TEL_to_FRB_RecNum = 0, RecNum_FRB = 0, DataSeq = 0,
DataSeq_FRB = 0;
// RecNum goes from 0 to MaxRecs (MaxRecs = 8 for TEL_SHM and 12*32 for
// FRB_SHM.) Only for the sake of this program, I am pretending as if FRB_SHM is
// 12 * 32 blocks long, with each block equal in size to that of TEL_SHM. In the
// FRB_SHM, the curRecord and curBlock are updated after accumulating 32 blocks
// of TEL_SHM. DataSeq keeps track of the number of blocks (or records) read
// since the starting of the observation. It is, in a sense, cummulative RecNum.
unsigned int *shm_marker_p;
double Data_Time[MaxRecs + 1] = {0.0};
int ind = 0, beam_ID = 0;
struct tm *local_t;
char time_string[40];
int usec = 0;
double blk_nano = 0;
struct timeval tv1;
// struct timezone tz1;
typedef struct {
int tz_minuteswest; /* minutes west of Greenwich */
int tz_dsttime; /* type of DST correction */
} timezone1;
timezone1 tz1;
int nBeams;
long int CurrRecSize;
long dataSize;
int curr_chans;
double Freq, chWidth, chan_freq;
// Filter related parameters + initialization
int block_size;
float thresig;
int filltype;
int nchans;
float outmean;
float outstd;
float width;
float tsamp;
size_t raw_size;
size_t nsamples;
size_t block_len;
size_t n_full;
uint8_t *block_ptr;
/*
* rfi_mitigation_omp_fixed.c
* C conversion of original C++ code by Raghav Wani (Last edited 18th Feb 2026)
* Converted to C11 + OpenMP. Correctness-fixed parallel version.
*
* Compile:
* gcc -O2 -std=c11 -fopenmp -o rfi_mitigation rfi_mitigation_omp_fixed.c -lm
*
* Control thread count at runtime:
* OMP_NUM_THREADS=8 ./rfi_mitigation <file> <block_size> <threshold>
*
*/
/* =========================================================================
* Portability helpers
* ====================================================================== */
static float clampf(float v, float lo, float hi) {
if (v < lo)
return lo;
if (v > hi)
return hi;
return v;
}
static double now_usec(void) { return omp_get_wtime() * 1e6; }
static double now_msec(void) { return omp_get_wtime() * 1e3; }
/* =========================================================================
* Error macros
* ====================================================================== */
#define FATAL(msg) \
do { \
fprintf(stderr, "Error: %s\n", msg); \
exit(1); \
} while (0)
#define FATALF(fmt, ...) \
do { \
fprintf(stderr, "Error: " fmt "\n", __VA_ARGS__); \
exit(1); \
} while (0)
/* =========================================================================
* Kahan compensated summation helper
* Gives the same result as serial left-to-right double accumulation
* regardless of the order in which partial sums arrive.
* ====================================================================== */
typedef struct {
double sum;
double c;
} KahanSum;
static inline void kahan_add(KahanSum *ks, double v) {
double y = v - ks->c;
double t = ks->sum + y;
ks->c = (t - ks->sum) - y;
ks->sum = t;
}
/* =========================================================================
* Thread-local Box-Muller RNG (Xorshift64 + Box-Muller)
* ====================================================================== */
typedef struct {
unsigned long long state;
} Rng;
static void rng_init(Rng *r, int extra_seed) {
r->state = (unsigned long long)time(NULL) ^ (unsigned long long)(uintptr_t)r ^
((unsigned long long)extra_seed * 6364136223846793005ULL);
r->state ^= r->state << 13;
r->state ^= r->state >> 7;
r->state ^= r->state << 17;
}
static double rng_uniform(Rng *r) {
r->state ^= r->state << 13;
r->state ^= r->state >> 7;
r->state ^= r->state << 17;
return (double)(r->state >> 11) / (double)(1ULL << 53);
}
static float rng_normal(Rng *r, float mean, float std) {
double u1 = rng_uniform(r);
double u2 = rng_uniform(r);
if (u1 < 1e-300)
u1 = 1e-300;
double z = sqrt(-2.0 * log(u1)) * cos(2.0 * 3.14159265358979323846 * u2);
return (float)(mean + std * z);
}
/* =========================================================================
* I/O
* ====================================================================== */
uint8_t *read_binary_data(const char *filename, size_t num_freq,
size_t *out_size) {
FILE *f = fopen(filename, "rb");
if (!f)
FATALF("Cannot open file: %s", filename);
fseek(f, 0, SEEK_END);
long file_size = ftell(f);
fseek(f, 0, SEEK_SET);
if (file_size < 0)
FATAL("ftell failed");
if ((size_t)file_size % num_freq != 0)
FATAL("File size not multiple of num_freq");
uint8_t *data = (uint8_t *)malloc((size_t)file_size);
if (!data)
FATAL("malloc failed in read_binary_data");
if (fread(data, 1, (size_t)file_size, f) != (size_t)file_size)
FATAL("Error reading file");
fclose(f);
*out_size = (size_t)file_size;
return data;
}
void write_binary_data(const char *filename, const uint8_t *data,
size_t data_size, size_t nsamples, size_t nchans) {
FILE *f = fopen(filename, "wb");
if (!f)
FATALF("Cannot open file for writing: %s", filename);
// if (data_size % nsamples != 0 || data_size % nchans != 0) FATALF("Data
// dimensions mismatch: %s", filename);
if (fwrite(data, 1, data_size, f) != data_size)
FATAL("Error writing file");
fclose(f);
}
/* =========================================================================
* Type conversions
* ====================================================================== */
void uint8_to_float(const uint8_t *in, float *out, size_t N, float zero_off) {
/* Pure element-wise transform — no accumulation, no ordering issue. */
#pragma omp parallel for schedule(static)
for (size_t k = 0; k < N; ++k)
out[k] = (float)in[k] - zero_off;
}
void float_to_uint8(float *in, uint8_t *out, size_t N, float outmean,
float outstd) {
int max_threads = omp_get_max_threads();
double *t_mean = (double *)calloc((size_t)max_threads, sizeof(double));
double *t_sq = (double *)calloc((size_t)max_threads, sizeof(double));
if (!t_mean || !t_sq)
FATAL("malloc failed float_to_uint8");
int actual_threads = 1;
#pragma omp parallel shared(actual_threads)
{
int tid = omp_get_thread_num();
double lmean = 0.0, lsq = 0.0;
#pragma omp for schedule(static) nowait
for (size_t k = 0; k < N; ++k) {
double v = in[k];
lmean += v;
lsq += v * v;
}
t_mean[tid] = lmean;
t_sq[tid] = lsq;
#pragma omp single
actual_threads = omp_get_num_threads();
}
KahanSum ks_mean = {0, 0}, ks_sq = {0, 0};
for (int t = 0; t < actual_threads; ++t) {
kahan_add(&ks_mean, t_mean[t]);
kahan_add(&ks_sq, t_sq[t]);
}
free(t_mean);
free(t_sq);
double tmpmean = ks_mean.sum / (double)N;
double tmpstd = ks_sq.sum / (double)N - tmpmean * tmpmean;
tmpstd = sqrt(tmpstd);
float scl = outstd / (float)tmpstd;
float offs = outmean - scl * (float)tmpmean;
#pragma omp parallel for schedule(static)
for (size_t k = 0; k < N; ++k) {
float tmp = scl * in[k] + offs;
tmp = roundf(tmp);
tmp = clampf(tmp, 0.0f, 255.0f);
out[k] = (uint8_t)tmp;
}
}
/* =========================================================================
* Comparators
* ====================================================================== */
static int cmp_float_asc(const void *a, const void *b) {
float fa = *(const float *)a, fb = *(const float *)b;
return (fa > fb) - (fa < fb);
}
static int cmp_float_desc(const void *a, const void *b) {
return -cmp_float_asc(a, b);
}
static int cmp_double_asc(const void *a, const void *b) {
double fa = *(const double *)a, fb = *(const double *)b;
return (fa > fb) - (fa < fb);
}
static int cmp_double_desc(const void *a, const void *b) {
return -cmp_double_asc(a, b);
}
/* =========================================================================
* skf_filter — Statistical Kurtosis Filter
* ====================================================================== */
void skf_filter(float *data, float thresig, size_t nsamples, size_t nchans) {
if (nsamples == 0 || nchans == 0)
FATAL("Empty data in skf_filter");
/* ---- Step 1: raw moments per channel (each channel independent) ---- */
double *chmean1 = (double *)calloc(nchans, sizeof(double));
double *chmean2 = (double *)calloc(nchans, sizeof(double));
double *chmean3 = (double *)calloc(nchans, sizeof(double));
double *chmean4 = (double *)calloc(nchans, sizeof(double));
double *chcorr = (double *)calloc(nchans, sizeof(double));
if (!chmean1 || !chmean2 || !chmean3 || !chmean4 || !chcorr)
FATAL("malloc failed skf step1");
#pragma omp parallel for schedule(static)
for (size_t j = 0; j < nchans; ++j) {
double m1 = 0, m2 = 0, m3 = 0, m4 = 0, corr = 0;
double last = data[j];
for (size_t i = 0; i < nsamples; ++i) {
double v = data[i * nchans + j];
double v2 = v * v;
m1 += v;
m2 += v2;
m3 += v2 * v;
m4 += v2 * v2;
corr += v * last;
last = v;
}
chmean1[j] = m1;
chmean2[j] = m2;
chmean3[j] = m3;
chmean4[j] = m4;
chcorr[j] = corr;
}
/* ---- Step 2: derived statistics (each channel independent) ---- */
float *chmean = (float *)calloc(nchans, sizeof(float));
float *chstd = (float *)calloc(nchans, sizeof(float));
float *chskewness = (float *)calloc(nchans, sizeof(float));
float *chkurtosis = (float *)calloc(nchans, sizeof(float));
if (!chmean || !chstd || !chskewness || !chkurtosis)
FATAL("malloc failed skf step2");
#pragma omp parallel for schedule(static)
for (size_t j = 0; j < nchans; ++j) {
chmean1[j] /= nsamples;
chmean2[j] /= nsamples;
chmean3[j] /= nsamples;
chmean4[j] /= nsamples;
chcorr[j] /= (nsamples - 1);
double mu = chmean1[j];
double mu2 = mu * mu;
double var = chmean2[j] - mu2;
chmean[j] = (float)mu;
if (var > 0.0) {
chskewness[j] =
(float)(chmean3[j] - 3.0 * chmean2[j] * mu + 2.0 * mu2 * mu);
chkurtosis[j] = (float)(chmean4[j] - 4.0 * chmean3[j] * mu +
6.0 * chmean2[j] * mu2 - 3.0 * mu2 * mu2);
chkurtosis[j] /= (float)(var * var);
chkurtosis[j] -= 3.0f;
chskewness[j] /= (float)(var * sqrt(var));
chcorr[j] -= mu2;
chcorr[j] /= var;
chstd[j] = sqrtf((float)var);
} else {
chstd[j] = 1.0f;
chkurtosis[j] = FLT_MAX;
chskewness[j] = FLT_MAX;
chcorr[j] = FLT_MAX;
}
}
size_t q_idx = nchans / 4;
float kurtosis_q1, kurtosis_q3, kurtosis_R;
float skewness_q1, skewness_q3, skewness_R;
double corr_q1, corr_q3, corr_R;
{
float *tmp = (float *)malloc(nchans * sizeof(float));
memcpy(tmp, chkurtosis, nchans * sizeof(float));
qsort(tmp, nchans, sizeof(float), cmp_float_asc);
kurtosis_q1 = tmp[q_idx];
qsort(tmp, nchans, sizeof(float), cmp_float_desc);
kurtosis_q3 = tmp[q_idx];
kurtosis_R = kurtosis_q3 - kurtosis_q1;
memcpy(tmp, chskewness, nchans * sizeof(float));
qsort(tmp, nchans, sizeof(float), cmp_float_asc);
skewness_q1 = tmp[q_idx];
qsort(tmp, nchans, sizeof(float), cmp_float_desc);
skewness_q3 = tmp[q_idx];
skewness_R = skewness_q3 - skewness_q1;
free(tmp);
}
{
double *tmp = (double *)malloc(nchans * sizeof(double));
for (size_t j = 0; j < nchans; ++j)
tmp[j] = chcorr[j];
qsort(tmp, nchans, sizeof(double), cmp_double_asc);
corr_q1 = tmp[q_idx];
qsort(tmp, nchans, sizeof(double), cmp_double_desc);
corr_q3 = tmp[q_idx];
corr_R = corr_q3 - corr_q1;
free(tmp);
}
int8_t *weights = (int8_t *)calloc(nchans, sizeof(int8_t));
if (!weights)
FATAL("malloc failed skf step4");
long kill_count = 0;
if (thresig >= 0) {
#pragma omp parallel for reduction(+ : kill_count) schedule(static)
for (size_t j = 0; j < nchans; ++j) {
if (chkurtosis[j] >= kurtosis_q1 - thresig * kurtosis_R &&
chkurtosis[j] <= kurtosis_q3 + thresig * kurtosis_R &&
chskewness[j] >= skewness_q1 - thresig * skewness_R &&
chskewness[j] <= skewness_q3 + thresig * skewness_R &&
chcorr[j] >= corr_q1 - thresig * corr_R &&
chcorr[j] <= corr_q3 + thresig * corr_R) {
weights[j] = 1;
} else {
++kill_count;
}
}
} else {
#pragma omp parallel for schedule(static)
for (size_t j = 0; j < nchans; ++j)
weights[j] = 1;
}
/* ---- Step 5: normalise — each row independent ---- */
#pragma omp parallel for schedule(static)
for (size_t i = 0; i < nsamples; ++i) {
float *row = &data[i * nchans];
for (size_t j = 0; j < nchans; ++j)
row[j] = (float)weights[j] * (row[j] - chmean[j]) / chstd[j];
}
/* ---- Step 6: bad-channel fill — thread-local RNG ---- */
#pragma omp parallel
{
Rng rng;
rng_init(&rng, omp_get_thread_num());
#pragma omp for schedule(static)
for (size_t i = 0; i < nsamples; ++i)
for (size_t j = 0; j < nchans; ++j)
if (weights[j] == 0)
data[i * nchans + j] = rng_normal(&rng, 0.0f, 1.0f);
}
free(chmean1);
free(chmean2);
free(chmean3);
free(chmean4);
free(chcorr);
free(chmean);
free(chstd);
free(chskewness);
free(chkurtosis);
free(weights);
}
/* =========================================================================
* patch_filter
* ====================================================================== */
void patch_filter(float *data, size_t nsamples, size_t nchans, int filltype) {
int *mask = (int *)calloc(nsamples, sizeof(int));
if (!mask)
FATAL("malloc failed patch_filter mask");
/* ---- Step 1: detect zero-variance rows ---- */
#pragma omp parallel for schedule(static)
for (size_t i = 0; i < nsamples; ++i) {
double sum = 0.0, sq_sum = 0.0;
for (size_t j = 0; j < nchans; ++j) {
double v = data[i * nchans + j];
sum += v;
sq_sum += v * v;
}
double mean = sum / nchans;
double var = sq_sum / nchans - mean * mean;
if (var == 0.0) {
#pragma omp atomic write
mask[i] = 1;
if (i != 0) {
#pragma omp atomic write
mask[i - 1] = 1;
}
if (i != nsamples - 1) {
#pragma omp atomic write
mask[i + 1] = 1;
}
}
}
long kill_count = 0;
for (size_t i = 0; i < nsamples; ++i)
kill_count += mask[i];
printf("Patch Filter: Kill rate = %.6f\n",
(double)kill_count / (double)nsamples);
/* ---- Step 2: mean/var of non-flagged samples ----
* NOTE: Original C++ bug preserved — `continue` always fires here,
* so count stays 0 and chmean_patch/chvar_patch stay zero.
* See original conversion comment for details. */
double *chmean_patch = (double *)calloc(nchans, sizeof(double));
double *chvar_patch = (double *)calloc(nchans, sizeof(double));
if (!chmean_patch || !chvar_patch)
FATAL("malloc failed patch step2");
long count = 0;
for (size_t i = 0; i < nsamples; ++i) {
if (mask[i])
printf("This time sample is flagged: %zu\n", i);
continue; /* faithfully reproduces original bug */
for (size_t j = 0; j < nchans; ++j) {
chmean_patch[j] += data[i * nchans + j];
chvar_patch[j] += data[i * nchans + j] * data[i * nchans + j];
}
++count;
}
if (count > 0) {
for (size_t j = 0; j < nchans; ++j) {
chmean_patch[j] /= count;
chvar_patch[j] =
chvar_patch[j] / count - chmean_patch[j] * chmean_patch[j];
}
}
/* ---- Step 3: fill ---- */
if (filltype == 0) { /* mean fill */
#pragma omp parallel for schedule(static)
for (size_t i = 0; i < nsamples; ++i) {
if (!mask[i])
continue;
for (size_t j = 0; j < nchans; ++j)
data[i * nchans + j] = (float)chmean_patch[j];
}
} else { /* rand fill — thread-local RNG */
float *ch_std = (float *)malloc(nchans * sizeof(float));
if (!ch_std)
FATAL("malloc failed patch rand std");
for (size_t j = 0; j < nchans; ++j)
ch_std[j] = (float)sqrt(chvar_patch[j] > 0.0 ? chvar_patch[j] : 0.0);
#pragma omp parallel
{
Rng rng;
rng_init(&rng, omp_get_thread_num());
#pragma omp for schedule(static)
for (size_t i = 0; i < nsamples; ++i) {
if (!mask[i])
continue;
for (size_t j = 0; j < nchans; ++j)
data[i * nchans + j] =
rng_normal(&rng, (float)chmean_patch[j], ch_std[j]);
}
}
free(ch_std);
}
free(mask);
free(chmean_patch);
free(chvar_patch);
}
/* =========================================================================
* equalization
* ====================================================================== */
void equalization(float *data, size_t nsamples, size_t nchans, float *chmean,
float *chstd) {
memset(chmean, 0, nchans * sizeof(float));
memset(chstd, 0, nchans * sizeof(float));
int max_threads = omp_get_max_threads();
/* double scratch: avoids float precision loss during accumulation */
double *acc_mean =
(double *)calloc((size_t)max_threads * nchans, sizeof(double));
double *acc_sq =
(double *)calloc((size_t)max_threads * nchans, sizeof(double));
if (!acc_mean || !acc_sq)
FATAL("malloc failed equalization");
int actual_threads = 1;
#pragma omp parallel shared(actual_threads)
{
int tid = omp_get_thread_num();
double *lmean = acc_mean + (size_t)tid * nchans;
double *lsq = acc_sq + (size_t)tid * nchans;
#pragma omp for schedule(static) nowait
for (size_t i = 0; i < nsamples; ++i) {
const float *row = &data[i * nchans];
for (size_t j = 0; j < nchans; ++j) {
lmean[j] += (double)row[j];
lsq[j] += (double)row[j] * row[j];
}
}
#pragma omp single
actual_threads = omp_get_num_threads();
}
double *dmean = (double *)calloc(nchans, sizeof(double));
double *dsq = (double *)calloc(nchans, sizeof(double));
double *cmean_c =
(double *)calloc(nchans, sizeof(double)); /* Kahan compensators */
double *csq_c = (double *)calloc(nchans, sizeof(double));
if (!dmean || !dsq || !cmean_c || !csq_c)
FATAL("malloc failed equalization merge");
for (int t = 0; t < actual_threads; ++t) {
double *lmean = acc_mean + (size_t)t * nchans;
double *lsq = acc_sq + (size_t)t * nchans;
for (size_t j = 0; j < nchans; ++j) {
/* Kahan add for dmean[j] */
double y, tmp;
y = lmean[j] - cmean_c[j];
tmp = dmean[j] + y;
cmean_c[j] = (tmp - dmean[j]) - y;
dmean[j] = tmp;
/* Kahan add for dsq[j] */
y = lsq[j] - csq_c[j];
tmp = dsq[j] + y;
csq_c[j] = (tmp - dsq[j]) - y;
dsq[j] = tmp;
}
}
free(acc_mean);
free(acc_sq);
free(cmean_c);
free(csq_c);
for (size_t j = 0; j < nchans; ++j) {
double m = dmean[j] / (double)nsamples;
double s2 = dsq[j] / (double)nsamples - m * m;
chmean[j] = (float)m;
chstd[j] = (float)sqrt(s2 > 0.0 ? s2 : 0.0);
if (chstd[j] == 0.0f)
chstd[j] = 1.0f;
}
free(dmean);
free(dsq);
#pragma omp parallel for schedule(static)
for (size_t i = 0; i < nsamples; ++i) {
float *row = &data[i * nchans];
for (size_t j = 0; j < nchans; ++j)
row[j] = (row[j] - chmean[j]) / chstd[j];
}
}
typedef struct {
float *arr;
size_t size, cap;
int is_max;
} Heap;
static void heap_init(Heap *h, size_t cap, int is_max) {
h->arr = (float *)malloc(cap * sizeof(float));
h->size = 0;
h->cap = cap;
h->is_max = is_max;
}
static void heap_free_h(Heap *h) {
free(h->arr);
h->size = 0;
}
static int heap_cmp(const Heap *h, float a, float b) {
return h->is_max ? (a > b) : (a < b);
}
static void heap_push(Heap *h, float v) {
size_t i = h->size++;
h->arr[i] = v;
while (i > 0) {
size_t p = (i - 1) / 2;
if (heap_cmp(h, h->arr[i], h->arr[p])) {
float t = h->arr[i];
h->arr[i] = h->arr[p];
h->arr[p] = t;
i = p;
} else
break;
}
}
static float heap_top(const Heap *h) { return h->arr[0]; }
static void heap_pop(Heap *h) {
h->arr[0] = h->arr[--h->size];
size_t i = 0;
for (;;) {
size_t l = 2 * i + 1, r = 2 * i + 2, best = i;
if (l < h->size && heap_cmp(h, h->arr[l], h->arr[best]))
best = l;
if (r < h->size && heap_cmp(h, h->arr[r], h->arr[best]))
best = r;
if (best == i)
break;
float t = h->arr[i];
h->arr[i] = h->arr[best];
h->arr[best] = t;
i = best;
}
}
static void heap_remove(Heap *h, float v) {
for (size_t i = 0; i < h->size; ++i) {
if (h->arr[i] == v) {
h->arr[i] = h->arr[--h->size];
while (i > 0) {
size_t p = (i - 1) / 2;
if (heap_cmp(h, h->arr[i], h->arr[p])) {
float t = h->arr[i];
h->arr[i] = h->arr[p];
h->arr[p] = t;
i = p;
} else
break;
}
size_t j = i;
for (;;) {
size_t l = 2 * j + 1, r = 2 * j + 2, best = j;
if (l < h->size && heap_cmp(h, h->arr[l], h->arr[best]))
best = l;
if (r < h->size && heap_cmp(h, h->arr[r], h->arr[best]))
best = r;
if (best == j)
break;
float t = h->arr[j];
h->arr[j] = h->arr[best];
h->arr[best] = t;
j = best;
}
return;
}
}
}
static void heap_rebalance(Heap *low, Heap *high) {
if (low->size > high->size + 1) {
heap_push(high, heap_top(low));
heap_pop(low);
} else if (high->size > low->size + 1) {
heap_push(low, heap_top(high));
heap_pop(high);
}
}
static float heap_median(const Heap *low, const Heap *high) {
if (low->size > high->size)
return heap_top(low);
if (high->size > low->size)
return heap_top(high);
return (heap_top(low) + heap_top(high)) / 2.0f;
}
static void sliding_median_float(const float *data, float *out, long size,
int w) {
if (w > (int)size)
w = (int)size;
Heap low, high;
heap_init(&low, (size_t)w + 2, 1);
heap_init(&high, (size_t)w + 2, 0);
int a = -w / 2 - 1, b = (w - 1) / 2;
heap_push(&low, data[0]);
float median = data[0];
for (int i = 1; i < b && i < (int)size; ++i) {
if (data[i] >= median)
heap_push(&high, data[i]);
else
heap_push(&low, data[i]);
heap_rebalance(&low, &high);
median = heap_median(&low, &high);
}
for (int i = 0; i < w / 2 + 1 && b < (int)size; ++i) {
if (data[b] >= median)
heap_push(&high, data[b]);
else
heap_push(&low, data[b]);
heap_rebalance(&low, &high);
median = heap_median(&low, &high);
out[i] = median;
++a;
++b;
}
for (int i = w / 2 + 1; i < (int)size - (w - 1) / 2; ++i) {
if (data[b] >= median)
heap_push(&high, data[b]);
else
heap_push(&low, data[b]);
int fl = 0;
for (size_t k = 0; k < low.size; ++k)
if (low.arr[k] == data[a]) {
fl = 1;
break;
}
if (fl)
heap_remove(&low, data[a]);
else
heap_remove(&high, data[a]);
heap_rebalance(&low, &high);
median = heap_median(&low, &high);
out[i] = median;
++a;
++b;
}
for (int i = (int)size - (w - 1) / 2; i < (int)size; ++i) {
int fl = 0;
for (size_t k = 0; k < low.size; ++k)
if (low.arr[k] == data[a]) {
fl = 1;
break;
}
if (fl)
heap_remove(&low, data[a]);
else
heap_remove(&high, data[a]);
heap_rebalance(&low, &high);
median = heap_median(&low, &high);
out[i] = median;
++a;
}
heap_free_h(&low);
heap_free_h(&high);
}
static void sliding_median_double(const double *data, double *out, long size,
int w) {
float *fi = (float *)calloc((size_t)size, sizeof(float));
float *fo = (float *)malloc((size_t)size * sizeof(float));
if (!fi || !fo)
FATAL("malloc failed sliding_median_double");
for (long i = 0; i < size; ++i)
fi[i] = (float)data[i];
sliding_median_float(fi, fo, size, w);
for (long i = 0; i < size; ++i)
out[i] = fo[i];
free(fi);
free(fo);
}
/* =========================================================================
* baseline_filter
* ====================================================================== */
void baseline_filter(float *data, size_t nsamples, size_t nchans, float width,
float tsamp) {
double *s = (double *)calloc(nsamples, sizeof(double));
if (!s)
FATAL("malloc failed baseline s");
int window_size = (int)(width / tsamp);
int max_threads = omp_get_max_threads();
/* ---- Step 1: channel mean per time sample (each row independent) ---- */
#pragma omp parallel for schedule(static)
for (size_t i = 0; i < nsamples; ++i) {
double sum = 0.0;
const float *row = &data[i * nchans];
for (size_t j = 0; j < nchans; ++j)
sum += row[j];
s[i] = sum / nchans;
}
/* ---- Step 2: sliding median (inherently serial) ---- */
double *s_med = (double *)malloc(nsamples * sizeof(double));
if (!s_med)
FATAL("malloc failed baseline s_med");
sliding_median_double(s, s_med, (long)nsamples, window_size);
memcpy(s, s_med, nsamples * sizeof(double));
free(s_med);
/* ---- Step 3: regression accumulation ---- */
double *t_xe = (double *)calloc((size_t)max_threads * nchans, sizeof(double));
double *t_xs = (double *)calloc((size_t)max_threads * nchans, sizeof(double));
double *t_se = (double *)calloc((size_t)max_threads, sizeof(double));
double *t_ss = (double *)calloc((size_t)max_threads, sizeof(double));
if (!t_xe || !t_xs || !t_se || !t_ss)
FATAL("malloc failed baseline regression");
int actual_threads = 1;
#pragma omp parallel shared(actual_threads)
{
int tid = omp_get_thread_num();
double *lxe = t_xe + (size_t)tid * nchans;
double *lxs = t_xs + (size_t)tid * nchans;
double lse = 0.0, lss = 0.0;
#pragma omp for schedule(static) nowait
for (size_t i = 0; i < nsamples; ++i) {
const float *row = &data[i * nchans];
double si = s[i];
for (size_t j = 0; j < nchans; ++j) {
lxe[j] += (double)row[j];
lxs[j] += (double)row[j] * si;
}
lse += si;
lss += si * si;
}
t_se[tid] = lse;
t_ss[tid] = lss;
#pragma omp single
actual_threads = omp_get_num_threads();
}
double *xe = (double *)calloc(nchans, sizeof(double));
double *xs = (double *)calloc(nchans, sizeof(double));
double *cxe = (double *)calloc(nchans, sizeof(double)); /* compensators */
double *cxs = (double *)calloc(nchans, sizeof(double));
if (!xe || !xs || !cxe || !cxs)
FATAL("malloc failed baseline merge");
double se = 0.0, ss = 0.0, cse = 0.0, css = 0.0;
for (int t = 0; t < actual_threads; ++t) {
double *lxe = t_xe + (size_t)t * nchans;
double *lxs = t_xs + (size_t)t * nchans;
/* Kahan merge for xe, xs per channel */
for (size_t j = 0; j < nchans; ++j) {
double y, tmp;
y = lxe[j] - cxe[j];
tmp = xe[j] + y;
cxe[j] = (tmp - xe[j]) - y;
xe[j] = tmp;
y = lxs[j] - cxs[j];
tmp = xs[j] + y;
cxs[j] = (tmp - xs[j]) - y;
xs[j] = tmp;
}
/* Kahan merge for se, ss */
{
double y = t_se[t] - cse;
double tmp = se + y;
cse = (tmp - se) - y;
se = tmp;
}
{
double y = t_ss[t] - css;
double tmp = ss + y;
css = (tmp - ss) - y;
ss = tmp;
}
}
free(t_xe);
free(t_xs);
free(t_se);
free(t_ss);
free(cxe);
free(cxs);
/* ---- Step 4: coefficients (serial, cheap) ---- */
double denom = se * se - ss * (double)nsamples;
double *alpha = (double *)calloc(nchans, sizeof(double));
double *beta = (double *)calloc(nchans, sizeof(double));
if (!alpha || !beta)
FATAL("malloc failed baseline coeffs");
if (denom != 0.0) {
for (size_t j = 0; j < nchans; ++j) {
alpha[j] = (xe[j] * se - xs[j] * (double)nsamples) / denom;
beta[j] = (xs[j] * se - xe[j] * ss) / denom;
}
}
/* ---- Step 5: subtract baseline (each row independent) ---- */
#pragma omp parallel for schedule(static)
for (size_t i = 0; i < nsamples; ++i) {
float *row = &data[i * nchans];
double si = s[i];
for (size_t j = 0; j < nchans; ++j)
row[j] -= (float)(alpha[j] * si + beta[j]);
}
free(s);
free(xe);
free(xs);
free(alpha);
free(beta);
}
/* =========================================================================
* process_block
* ====================================================================== */
static void process_block(uint8_t *block_ptr, size_t block_N, size_t nsamples,
size_t nchans, int filltype, float thresig,
float outmean, float outstd, float width,
float tsamp) {
float *fd = (float *)malloc(block_N * sizeof(float));
float *cmean = (float *)malloc(nchans * sizeof(float));
float *cstd = (float *)malloc(nchans * sizeof(float));
if (!fd || !cmean || !cstd)
FATAL("malloc failed in process_block");
uint8_to_float(block_ptr, fd, block_N, -64.0f);
// patch_filter(fd, nsamples, nchans, filltype);
skf_filter(fd, thresig, nsamples, nchans);
equalization(fd, nsamples, nchans, cmean, cstd);
baseline_filter(fd, nsamples, nchans, width, tsamp);
float_to_uint8(fd, block_ptr, block_N, outmean, outstd);
free(fd);