-
Notifications
You must be signed in to change notification settings - Fork 0
/
ecoduet.cpp
1719 lines (1323 loc) · 53.8 KB
/
ecoduet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "duet.h"
// Stream stats.
int ACQUIRED_STREAMS = 0; // How many streams were acquired during the whole program execution.
int HIGHEST_STREAM_ID = 0; // The highest stream id ever achieved.
int MERGED_STREAMS = 0; // How many streams were merged (permanently deleted and whole information cleared -- this leaves wholes behind but stats will give nan values for the holes if left unfilled)
//#define OLD_MASK_BUILD
//#define OLD_PEAK_ASSIGN
const int N_EXPORT_DIGITS = 5; // Number of digits to output in the output serial number.
/// Returns the score for the DUET histogram based on the parameters p and q
real DUEThist_score(real x1re, real x1im, real x2re, real x2im, real omega, real p, real q)
{
real s_re, s_im, s_abs;
complex_multiply(x1re,x1im, x2re,x2im, &s_re,&s_im);
s_abs = abs(s_re,s_im);
// PERFORMANCE: The tables of the powers of omega could be reused.
return std::pow(s_abs,p)*std::pow(omega,q);
}
/** Taken from bessel.c, also distributed in this folder. Calculates the modified Bessel function I0. */
/*
double bessi0( double x )
{
double ax,ans;
double y;
if ((ax=fabs(x)) < 3.75) {
y=x/3.75,y=y*y;
ans=1.0+y*(3.5156229+y*(3.0899424+y*(1.2067492
+y*(0.2659732+y*(0.360768e-1+y*0.45813e-2)))));
} else {
y=3.75/ax;
ans=(exp(ax)/sqrt(ax))*(0.39894228+y*(0.1328592e-1
+y*(0.225319e-2+y*(-0.157565e-2+y*(0.916281e-2
+y*(-0.2057706e-1+y*(0.2635537e-1+y*(-0.1647633e-1
+y*0.392377e-2))))))));
}
return ans;
}
*/
/**
@param[in] K - Number of active sources: theta.size() >= K
@param[in] x - Must have fewer than RAND_MAX elements.
*/
/*
void RANSAC (Buffer<real> &theta, Buffer<real> &x, int K, int RANSAC_samples_per_source)
{
const int N = x.size();
const int M = K * RANSAC_samples_per_source;
const int MAX_N = 5000;
const int MAX_M = 200; // Maximum number of RANSAC samples.
static Buffer<int> y(MAX_M);
Assert(MAX_N > N && MAX_M > M, "RANSAC compile-time constants too small.");
static Buffer<bool> I(MAX_N * MAX_M); // Since memory must be reused it will be dynamically addressed as if it was a linear 2D-array of dimensions (N,M).
I.clear();
for (int m=0; m < M; ++m)
{
y[m] = rand() % N;
// Fit(y[m])
}
}
*/
void DUET_hist_add_score(Histogram2D<real> &hist, Histogram<real> &hist_alpha, Histogram<real> &hist_delta, real alpha, real delta, real X1_re, real X1_im, real X2_re, real X2_im, real omega, const DUETcfg &DUET)
{
if (std::isnan(alpha))
{
// This test can be taken out in the final system supposedly because it won't be padded with 0's, instead there will always be noise in the signal, and whatever the noise is it will produce frequencies. The thesis on the circular duet talks about this, that the window should have at least the size of the biggest consecutive chain of 0's possible to appear in the data ( so this doesn't happen ).
/*
static size_t alpha_isnan_count = 0;
++alpha_isnan_count;
printf("alpha=nan occurred %lu times.\n", alpha_isnan_count);
*/
//printf("nan value in alpha for t_block=%lu, f=%lu\n", time_block, f);
return;
}
real score = DUEThist_score(X1_re,X1_im, X2_re, X2_im, omega, DUET.p, DUET.q);
hist(alpha, delta) += score;
hist_alpha(alpha) += score;
hist_delta(delta) += score;
}
/// Calculates (alpha,delta) for a time block and adds to the histogram.
void calc_alpha_delta(idx time_block, idx pN, idx sample_rate_Hz,
Buffer<real> &X1, Buffer<real> &X2,
Matrix<real,MatrixAlloc::Rows> &alpha,
Matrix<real,MatrixAlloc::Rows> &delta,
Histogram2D<real> &hist,
Histogram<real> &hist_alpha, Histogram<real> &hist_delta,
const DUETcfg &DUET)
{
static real df = sample_rate_Hz/(real)pN;
/*
f = 0 Hz:
d_Re = X1(0) / X2(0);
d_Im = 0;
*/
real a = X2[0] / X1[0];
alpha(time_block, 0) = a - 1/a;
delta(time_block, 0) = 0.0;
idx fI; // imaginary part index
real _alpha, _delta; // aliases to avoid unneeded array re-access.
real omega;
if (DUET.FFT_p > 1) // Use the phase-aliasing correction extension.
{
for (idx f = DUET.Fmin; f < pN/2 - 1; ++f)
{
fI = pN-f; // imaginary part index
std::complex<real> F (std::complex<real>(X2[f ],X2[fI ])/std::complex<real>(X1[f ],X1[fI ]));
std::complex<real> Feps(std::complex<real>(X2[f+1],X2[fI-1])/std::complex<real>(X1[f+1],X1[fI-1]));
omega = _2Pi * f*df; // f_Hz = f*df
a = std::abs(F);
_alpha = alpha(time_block, f) = a - 1/a;
_delta = delta(time_block, f) = std::fmod(pN/_2Pi * (std::arg(F)-std::arg(Feps)), pN);
DUET_hist_add_score(hist, hist_alpha, hist_delta, _alpha, _delta, X1[f],X1[fI], X2[f],X2[fI], omega, DUET);
}
}
else // Standard DUET without phase-aliasing correction.
{
for (idx f = DUET.Fmin; f < DUET.Fmax; ++f)
{
idx fI = pN-f; // imaginary part index
std::complex<real> F(std::complex<real>(X2[f],X2[fI])/std::complex<real>(X1[f],X1[fI]));
omega = _2Pi * f*df; // f_Hz = f*df
a = std::abs(F);
_alpha = alpha(time_block, f) = a - 1/a;
_delta = delta(time_block, f) = - std::arg(F)/omega;
DUET_hist_add_score(hist, hist_alpha, hist_delta, _alpha, _delta, X1[f],X1[fI], X2[f],X2[fI], omega, DUET);
}
}
}
void ransac_test(idx time_block, idx pN, idx sample_rate_Hz,
Buffer<real> &X1, Buffer<real> &X2,
Matrix<real,MatrixAlloc::Rows> &alpha,
Matrix<real,MatrixAlloc::Rows> &delta,
Histogram2D<real> &hist,
Histogram<real> &hist_alpha, Histogram<real> &hist_delta,
const DUETcfg &DUET)
{
static real df = sample_rate_Hz/(real)pN;
/*
f = 0 Hz:
d_Re = X1(0) / X2(0);
d_Im = 0;
*/
real a = X2[0] / X1[0];
alpha(time_block, 0) = a - 1/a;
delta(time_block, 0) = 0.0;
real _alpha, _delta; // aliases to avoid unneeded array re-access.
real omega;
// ELIMINATE THIS LATER
static Gnuplot pransac("points");
pransac.set_labels("delta", "f index");
static Buffer<real> f_axis(pN/2), delta_axis(pN/2);
///////////////////////
for (idx f = 1; f < pN/2; ++f)
{
idx fI = pN-f; // imaginary part index
std::complex<real> F1(X1[f],X1[fI]), F2(X2[f],X2[fI]), F(F2/F1);
omega = _2Pi * f*df; // f_Hz = f*df
a = std::abs(F);
// Do not override alpha and delta, for those are for DUET right now
_alpha /*=alpha(time_block, f)*/ = a - 1/a;
// Wrong
//_delta = delta(time_block, f) = std::fmod(std::arg(F1) - std::arg(F2), M_PI);///omega;
//_delta /*= delta(time_block, f)*/ = std::arg(std::polar<real>(1,std::arg(F1) - std::arg(F2)));///omega;
_delta = std::fmod(std::arg(F1)-std::arg(F2) + M_PI, 2*M_PI) - M_PI;
// _delta = std::fmod(std::arg(F1)-std::arg(F2),M_PI);
f_axis[f] = f;
delta_axis[f] = _delta;
//DUET_hist_add_score(hist, hist_alpha, hist_delta, _alpha, _delta, X1[f],X1[fI], X2[f],X2[fI], omega, DUET);
}
pransac.replot(delta_axis(), f_axis(), pN/2, "Frame RANSAC");
//wait();
}
#define RELEASE(x) {}
// After giving one buffer in one call (new_buffer), at the end of the next (blocking) call, it can be released.
// Cannot be reassigned to a different output because it stores the previous buffer and it would have conflicts, thus all the data must be passed
size_t write_data(Buffers<real> &o, Buffers<real> *new_buffers, const size_t FFT_N, const size_t FFT_slide)
{
static int overlapping_buffers = 1; // how many buffers are in current use (state variable)
static Buffers<real> *a=new_buffers, *b=NULL;
static size_t i = 0, p = 0;
unsigned int buffers = o.buffers();
if (FFT_slide < FFT_N) // Up to 50% overlap
{
if (overlapping_buffers == 2)
{
b = new_buffers;
while (i < FFT_N)
{
//o[p] = a[i] + b[i-FFT_slide];
for (uint buf = 0; buf < buffers; ++buf)
(*o(buf))[p] = (*(*a)(buf))[i] + (*(*b)(buf))[i-FFT_slide];
++p;
++i;
}
RELEASE(a);
i = FFT_N-FFT_slide;
a = b;
overlapping_buffers = 1;
}
// overlapping_buffers == 1
while (i < FFT_slide)
{
// o[p] = a[i]
for (uint buf = 0; buf < buffers; ++buf)
(*o(buf))[p] = (*(*a)(buf))[i];
++p;
++i;
}
overlapping_buffers = 2;
// Now wait for new call with new_buffer
}
else // No overlap
{
i = 0;
a = new_buffers;
while (i < FFT_slide) // == FFT_N
{
// o[p] = a[i]
for (uint buf = 0; buf < buffers; ++buf)
(*o(buf))[p] = (*(*a)(buf))[i];
++p;
++i;
}
}
return p;
}
/// Transforms alpha back to a.
real alpha2a (real alpha)
{
return (alpha + std::sqrt(alpha*alpha + 4.0)) * 0.5;
}
/// Fills a buffer of size FFT_N/2 // To each bin will be assigned the number of the source. values < 0 indicate that the bin won't be assigned a source (noise or intentional algorithm rejection/discard).
/// Thus, a single buffer is required to hold all the masks
/// tmp must have size = max(N_clusters)
void build_masks(Buffer<int> &masks, real *alpha, real *delta, real *X1, real *X2, Buffer<Point2D<real> > &clusters, int N_clusters, idx FFT_N, idx FFT_half_N, real FFT_df, Buffer<real> &tmp, const DUETcfg &DUET)
{
Buffer<int> old_masks(masks);
idx masks_diffs = 0;
for (idx f = DUET.Fmin; f < DUET.Fmax; ++f)
{
real omega = _2Pi * f * FFT_df;
idx f_im = FFT_N - f;
for (int k=0; k < N_clusters; ++k)
{
real a_k = alpha2a(clusters[k].x);
real delta_k = clusters[k].y;
tmp[k] = std::norm(a_k*std::polar<real>(1,-delta_k*omega) * std::complex<real>(X1[f],X1[f_im]) - std::complex<real>(X2[f],X2[f_im])) / (1.0 + a_k*a_k);
}
masks[f] = array_ops::min_index(tmp(), N_clusters);
old_masks[f] = closest_cluster(Point2D<real>(alpha[f],delta[f]), clusters);
if (masks[f]!=old_masks[f])
masks_diffs += 1;
}
#ifdef OLD_MASK_BUILD
masks = old_masks;
cout << "#Mask diffs = " << masks_diffs << endl;
#endif // OLD_MASK_BUILD
// cout << RED << masks_diffs << NOCOLOR << endl;
}
void apply_masks(Buffers<real> &buffers, real *alpha, real *X1, real *X2, Buffer<int> &masks, Buffer<Point2D<real> > &clusters, uint active_sources, idx FFT_N, idx FFT_half_N, real FFT_df, fftw_plan &FFTi_plan, Buffer<real> &Xo, const DUETcfg &DUET)
{
buffers.clear();
// Rebuild one source per iteration to reuse the FFT plan (only 1 needed).
for (uint source = 0; source < active_sources; ++source)
{
Xo.clear();
if (masks[0] == source)
{
real a_k = alpha2a(clusters[source].x);
Xo[0] = a_k*X1[0]-X2[0];
Xo[0] *= Xo[0] / (1 + a_k*a_k);
}
real maxXabs=0;
for (uint f = DUET.Fmin; f < DUET.Fmax; ++f)
{
if (masks[f] == source)
{
uint f_im = FFT_N - f;
real a_k = alpha2a(clusters[source].x);
real delta_k = clusters[source].y;
real omega = _2Pi * f * FFT_df;
std::complex<real> X(std::complex<real>(X1[f],X1[f_im])+std::polar<real>(a_k,delta_k*omega) * std::complex<real>(X2[f],X2[f_im]));
real Xabs = std::norm(X);
if (Xabs > maxXabs)
maxXabs = Xabs;
#ifdef OLD_PEAK_ASSIGN
Xo[f ] = X1[f ];
Xo[f_im] = X1[f_im];
#else
Xo[f ] = X.real();
Xo[f_im] = X.imag();
#endif // OLD_PEAK_ASSIGN
}
}
/*
// Tried to filter weak components for the .5s windows but degrades the signal until musical noise is generated.
for (int f = 1, fmax = FFT_N/2; f < fmax; ++f)
{
real fabs2 = abs2(Xo[f],Xo[FFT_N-f]);
if (fabs2 < maxXabs*1e-2)
{
// printf("f=%d %g\n", f, fabs2/maxXabs);
Xo[f] = Xo[FFT_N-f] = 0;
}
}
*/
fftw_execute_r2r(FFTi_plan, Xo(), buffers.raw(source));
}
buffers /= (real)FFT_N;
}
void LDMB2C(StreamSet &Streams, IdList &active_streams, Buffers<real> *new_buffers, Buffer<Point2D<real> > &clusters_pos, int N_clusters, idx time_block, Buffer<real> &W, Buffer<int> &C, const DUETcfg &DUET)
{
static const int MAX_CLUSTERS = DUET.max_clusters;
static const int MAX_ACTIVE_STREAMS = DUET.max_active_streams;
static const int FFT_N = DUET.FFT_N;
static const int FFT_slide = DUET.FFT_slide;
static const int FFT_overlap = FFT_N-FFT_slide;
static const int MAX_SILENCE_BLOCKS = DUET.max_silence_blocks;
static const int MIN_ACTIVE_BLOCKS = DUET.min_active_blocks;
//// Solve the permutations to achieve continuity of the active streams. ///////////
static Buffer<real> dist_k (MAX_CLUSTERS, FLT_MAX );
static Buffer<real> acorr_k (MAX_CLUSTERS, -FLT_MAX);
static Matrix<real>
D (MAX_ACTIVE_STREAMS, MAX_CLUSTERS, FLT_MAX),
A0(MAX_ACTIVE_STREAMS, MAX_CLUSTERS, -FLT_MAX);
static IdList
merging_streams (MAX_ACTIVE_STREAMS),
assigned_clusters(MAX_CLUSTERS);
// LDB
C.clear(); D.clear(); A0.clear();
merging_streams.clear();
assigned_clusters.clear();
// Calculate the distance between old streams and new buffers in terms of D and A0. A0 requires applying the complementary window.
for (int s=0; s < active_streams.N(); ++s)
{
static Buffer<real> W_buf_stream(FFT_overlap), W_buf_new_stream(FFT_overlap);
int id = active_streams[s];
W_buf_stream.copy(Streams.last_buf_raw(id,FFT_slide), FFT_overlap);
for (int u=0; u < FFT_overlap; ++u)
W_buf_stream[u] *= W[u]; // Apply the complementary window of the next block.
for (int j=0; j < N_clusters; ++j)
{
// D
D (s,j) = Lambda_distance(Streams.pos(id),clusters_pos[j]);
// A0 (with complementary windows applied)
// Since streams haven't been assigned yet, streams assigned right at the last block have a difference of 1.
if (time_block - Streams.last_active_time_block(id) == 1)
{
// PERFORMANCE: We could calculate them all only once beforehand since they're reutilized for each old stream.
W_buf_new_stream.copy(new_buffers->raw(j), FFT_overlap);
for (int u=0; u < FFT_overlap; ++u)
W_buf_new_stream[u] *= W[u+FFT_slide]; // Apply the past complementary window.
// PERFORMANCE: Can do the normalization outside manually.
A0(s,j) = array_ops::a0(W_buf_stream(), W_buf_new_stream(), FFT_N-FFT_slide);
}
}
}
for (int s=0; s < active_streams.N(); ++s)
Streams.print(active_streams[s]);
printf("Active_Streams=%u clusters = %u\n", active_streams.N(), N_clusters);
puts("D:");
D.print (active_streams.N(), N_clusters);
puts("A0:");
A0.print(active_streams.N(), N_clusters);
// Life
if (active_streams.N() && N_clusters)
{
// Life Stage 1 : global A0 > A0MIN assignment
printf(GREEN "Streams that live by A0 (stream@cluster): ");
while( 1 )
{
static size_t s, j; // no need to init at 0 every turn.
A0.max_index(s,j, active_streams.N(), N_clusters);
real a0(A0(s,j));
if ( a0 > DUET.a0min ) // Life
{
int id(active_streams[s]);
assigned_clusters.add(j);
C[j] = id;
/* Remove entries that are no longer candidates for assignment from lookup
(stream id=active_streams[s] and cluster j). */
// Eliminate the already processed stream s from lookup.
if (! DUET.multiple_assign)
{
A0.fill_row_with(s, -FLT_MAX);
D .fill_row_with(s, FLT_MAX);
}
// Eliminate the already processed cluster j from lookup.
A0.fill_col_with(j, -FLT_MAX);
D .fill_col_with(j, FLT_MAX);
printf("%d@%lu ", id, j);
}
else
break; // no more a0 > A0MIN
}
puts("\n" NOCOLOR);
// Life Stage 2 : global pos assignment (Lambda_distance < threshold)
printf(GREEN "Streams that live by pos (stream@cluster): ");
while( 1 )
{
static size_t s, j; // no need to init at 0 every turn.
D.min_index(s,j, active_streams.N(), N_clusters);
real d(D(s,j));
if ( d < DUET.max_Lambda_distance ) // Life
{
int id(active_streams[s]);
C[j] = id;
assigned_clusters.add(j);
// Eliminate the already processed stream s from lookup.
if (! DUET.multiple_assign)
{
A0.fill_row_with(s, -FLT_MAX);
D .fill_row_with(s, FLT_MAX);
}
// Eliminate the already processed cluster j from lookup.
A0.fill_col_with(j, -FLT_MAX);
D .fill_col_with(j, FLT_MAX);
printf("%d@%lu ", id, j);
}
else
break; // no more a0 > A0MIN
}
puts("\n" NOCOLOR);
}
// Death
for (int s = 0; s < active_streams.N(); ++s)
{
int id = active_streams[s];
// The difference is zero for freshly active streams (right at the previous block).
int stream_inactive_blocks = time_block - Streams.last_active_time_block(id) - 1;
if (stream_inactive_blocks > MAX_SILENCE_BLOCKS)
{
active_streams.del(id);
// Add stream to the list of streams to merge. Note we won't merge to other streams in the same condition but only streams that remain active.
if ( Streams.active_blocks(id) <= MIN_ACTIVE_BLOCKS )
merging_streams.add(id);
else
printf(RED "Stream id %d has died.\n" NOCOLOR, id);
}
else if (stream_inactive_blocks)
printf(GREEN "Stream %d remains inactive by %d/%d time_blocks.\n" NOCOLOR, id, stream_inactive_blocks, MAX_SILENCE_BLOCKS);
}
// Merge
// Merge to the closest active stream. Note that this is the only stage at which more than one stream can be assigned to a destination stream (merging procedure).
if (active_streams.N())
{
for (int m = 0; m < merging_streams.N(); ++m )
{
int m_id = merging_streams[m];
// Find the closest active stream to stream id=m_id.
real min_distance = FLT_MAX;
int s_id_match = active_streams[0];
for (int s = 0; s < active_streams.N(); ++s)
{
int s_id = active_streams[s];
real distance = Lambda_distance(Streams.pos(m_id), Streams.pos(s_id));
if (distance < min_distance)
{
min_distance = distance;
s_id_match = s_id;
}
}
++MERGED_STREAMS;
// PERFORMANCE: This can be implemented more efficiently by adding only the active portion.
Streams.stream(s_id_match)->add_at(*(Streams.stream(m_id)),0);
// Now we can free up this stream since it has been merged.
Streams.release_id(m_id);
printf(GREEN "Stream %d merged to %d.\n" NOCOLOR, m_id, s_id_match);
}
}
// Birth
// For each cluster left unassigned a new stream is born.
printf(GREEN "Born streams: ");
for (int j = 0; j < N_clusters; ++j)
{
if (! assigned_clusters.has(j))
{
int id = Streams.acquire_id();
active_streams.add(id);
if (id > HIGHEST_STREAM_ID)
HIGHEST_STREAM_ID = id;
++ACQUIRED_STREAMS;
C[j] = id;
printf("%d ", id);
}
}
puts("\n" NOCOLOR);
} // End of LDMB
// Calculated to 4sigma (3 would suffice, as the generated gaussian kernels).
// WARN: it sorts the peaks.
real confidence(Histogram<real> &H, Buffer<real> &peaks_k, int K, real sigma)
{
Buffer<real> *h = H.raw();
// Sort the peaks to process partial peak overlap integration gracefully.
std::sort(peaks_k(), peaks_k()+peaks_k.size());
// Not multiplying by H.dx() since the quotient will erase it.
real H_integral = h->sum(), peaks_integral=0;
size_t prev_k_max_bin=0, bin=0, max_k_bin=0;
for (int k=0; k < K; ++k)
{
// Get the minimum and maximum bins for peak_k for integration (integration limits)
H.get_bin_index(peaks_k[k]-4.0*sigma, bin );
H.get_bin_index(peaks_k[k]+4.0*sigma, max_k_bin);
// If peak integration regions overlap do not integrate twice. Resume where we left peak k-1.
if (bin <= prev_k_max_bin)
bin = prev_k_max_bin+1;
for (; bin <= max_k_bin; ++bin)
peaks_integral += (*h)[bin];
prev_k_max_bin = max_k_bin;
}
return peaks_integral / H_integral;
}
void draw_trajectories(StreamSet &streams, unsigned int time_blocks, real slide_time, Gnuplot &pTalpha, Gnuplot &pTdelta, Gnuplot &pT)
{
pTalpha.reset(); pTdelta.reset(); pT.reset();
pTalpha.set_labels("Localization step", "alpha");
pTdelta.set_labels("Localization step", "delta (s)");
pT .set_labels("alpha" , "delta");
Buffer<real> times(time_blocks), alphas(time_blocks), deltas(time_blocks);
times.fill_range(0, slide_time*(time_blocks-1));
for (int id=1; id <= HIGHEST_STREAM_ID; ++id)
{
unsigned int start = streams.first_active_time_block(id);
unsigned int stop = streams.last_active_time_block(id);
unsigned int blocks = stop - start;
if (blocks)
{
Buffer<Point2D<real> > &path = *streams.trajectory(id);
for (unsigned int tb = start; tb < stop; ++tb)
{
alphas[tb] = path[tb].x;
deltas[tb] = path[tb].y;
}
std::string title = std::to_string(id);
pTalpha.plot(× [start], &alphas[start], blocks, title.c_str());
pTdelta.plot(× [start], &deltas[start], blocks, title.c_str());
pT .plot(&alphas[start], &deltas[start], blocks, title.c_str());
printf("Stream %d: alpha=[%g,%g] delta=[%g,%g]\n", id,
array_ops::min(&alphas[start],blocks),
array_ops::max(&alphas[start],blocks),
array_ops::min(&deltas[start],blocks),
array_ops::max(&deltas[start],blocks));
}
}
}
real local_confidence(Histogram2D<real> &H, Matrix<real> &kernel, Point2D<real> &pos)
{
// Calculate the error from the Gaussian profile to the local histogram profile
real error = 0;
size_t kx_bins = kernel.rows();
size_t ky_bins = kernel.cols();
size_t kcx_bin = kx_bins/2;
size_t kcy_bin = ky_bins/2;
size_t Hcx_bin, Hcy_bin;
H.get_bin_index(pos.x, pos.y, Hcx_bin, Hcy_bin);
real factor = H(pos.x, pos.y) / kernel(kcx_bin, kcy_bin);
// No need to sum the central bin as it has beem scaled to have 0 error.
for (size_t i=1; i <= kcx_bin; ++i)
for (size_t j=1; j <= kcy_bin; ++j)
{
real e1=0, e2=0, e3=0, e4=0;
// PERFORMANCE: TESTS CAN BE MERGED
if (i<=Hcx_bin && j<= Hcy_bin)
e1 = (H.bin(Hcx_bin-i,Hcy_bin-j) - factor * kernel(kcx_bin-i, kcy_bin-j));
if (Hcx_bin+i<H.xbins())
e2 = (H.bin(Hcx_bin+i,Hcy_bin-j) - factor * kernel(kcx_bin+i, kcy_bin-j));
if (i<=Hcx_bin && Hcy_bin+j<H.ybins())
e3 = (H.bin(Hcx_bin-i,Hcy_bin+j) - factor * kernel(kcx_bin-i, kcy_bin+j));
if (Hcx_bin+i<H.xbins() && Hcy_bin+j<=H.ybins())
e4 = (H.bin(Hcx_bin+i,Hcy_bin+j) - factor * kernel(kcx_bin+i, kcy_bin+j));
error += e1*e1 + e2*e2 + e3*e3 + e4*e4;
}
return 1/error;
}
bool excess_kurtosis(real &kurtosis, Histogram<real> &H, Buffer<real> &kernel, real pos)
{
const int kcbin = kernel.size()/2;
size_t cbin;
if ( ! H.get_bin_index(pos, cbin) )
return false;
real mu4=0, mu2=0;
const real dx = H.dx();
// Add the centrum which is not added up in the loops.
real Hsum = H.bin(cbin);
// The center bin won't be summed.
// Since the kernel is symmetric we run left (r) and right (r) terms inside the same loop iteration.
// Starts at the smoothing kernel edges. i= distance to centre of the smoothing kernel from the left
for (size_t i=kcbin; i; --i)
{
real D = dx*i;
real Hl = ( cbin>=i ? H.bin(cbin-i) : 0 );
real Hr = ( cbin+i<H.bins() ? H.bin(cbin+i) : 0 );
real Hs = Hl + Hr;
mu4 += std::pow(D, 4) * Hs;
mu2 += D*D * Hs;
Hsum += Hs;
}
kurtosis = mu4/(mu2*mu2) * Hsum - 3.0;
return true;
}
bool excess_kurtosis(real &kurtosis_x, real &kurtosis_y, Histogram2D<real> &H, Matrix<real> &kernel, real pos_x, real pos_y, const DUETcfg &DUET)
{
int kcxbin = kernel.rows()/2;
int kcybin = kernel.cols()/2;
size_t cxbin, cybin;
if ( ! H.get_bin_index(pos_x,pos_y, cxbin, cybin) )
return false;
real mu4x=0, mu4y=0, mu2x=0, mu2y=0;
const real dx = H.dx(), dy = H.dy();
// Add the centrum which is not added up in the loops.
real Hxsum(H.bin(cxbin,cybin)), Hysum(Hxsum);
// The center bin won't be summed.
// Since the kernel is symmetric we run left (r) and right (r) terms inside the same loop iteration.
// Starts at the smoothing kernel edges. i= distance to centre of the smoothing kernel from the left
for (size_t i=kcxbin; i; --i)
{
real D = dx*i;
real Hl = ( cxbin>=i ? H.bin(cxbin-i, cybin) : 0 );
real Hr = ( cxbin+i<H.xbins() ? H.bin(cxbin+i, cybin) : 0 );
real Hs = Hl + Hr;
mu4x += std::pow(D, 4) * Hs;
mu2x += D*D * Hs;
Hxsum += Hs;
}
for (size_t i=kcybin; i; --i)
{
real D = dy*i;
real Hl = ( cybin>=i ? H.bin(cxbin, cybin-i) : 0 );
real Hr = ( cybin+i<H.ybins() ? H.bin(cxbin, cybin+i) : 0 );
real Hs = Hl + Hr;
mu4y += std::pow(D, 4) * Hs;
mu2y += D*D * Hs;
Hysum += Hs;
}
kurtosis_x = mu4x/(mu2x*mu2x) * Hxsum - 3.0;
kurtosis_y = mu4y/(mu2y*mu2y) * Hysum - 3.0;
return true;
}
void constrained_excess_kurtosis(real &kurtosis_x, real &kurtosis_y, Histogram2D<real> &H, Matrix<real> &kernel, real pos_x, real pos_y, const DUETcfg &DUET)
{
int kcxbin = kernel.rows()/2;
int kcybin = kernel.cols()/2;
size_t cxbin, cybin;
H.get_bin_index(pos_x,pos_y, cxbin, cybin);
real mu4x=0, mu4y=0, mu2x=0, mu2y=0;
const real dx = H.dx(), dy = H.dy();
// Normalization constants
// Add the centrum which is not added up in the loops.
real Hxsum(H.bin(cxbin,cybin)), Hysum(Hxsum);
// The center bin won't be summed.
// Since the kernel is symmetric we run left (r) and right (r) terms inside the same loop iteration.
// Starts at the smoothing kernel edges. i= distance to centre of the smoothing kernel from the left
for (size_t i=kcxbin; i; --i)
{
real D = dx*i;
real Hl = ( cxbin>=i ? H.bin(cxbin-i, cybin) : 0 );
real Hr = ( cxbin+i<H.xbins() ? H.bin(cxbin+i, cybin) : 0 );
real Hs = Hl + Hr;
mu4x += std::pow(D, 4) * Hs;
mu2x += D*D * Hs;
Hxsum += Hs;
}
for (size_t i=kcybin; i; --i)
{
real D = dy*i;
real Hl = ( cybin>=i ? H.bin(cxbin, cybin-i) : 0 );
real Hr = ( cybin+i<=H.ybins() ? H.bin(cxbin, cybin+i) : 0 );
real Hs = Hl + Hr;
mu4y += std::pow(D, 4) * Hs;
mu2y += D*D * Hs;
Hysum += Hs;
}
printf(CYAN "o%g e%g reo%g o%g e%g reo%g\n" NOCOLOR,
DUET.sigma_alpha, mu2x/Hxsum, (mu2x/Hxsum)/DUET.sigma_alpha,
DUET.sigma_delta, mu2y/Hysum, (mu2y/Hysum)/DUET.sigma_delta);
kurtosis_x = mu4x/(DUET.sigma_alpha*DUET.sigma_alpha) / Hxsum - 3.0;
kurtosis_y = mu4y/(DUET.sigma_delta*DUET.sigma_delta) / Hysum - 3.0;
}
int main(int argc, char **argv)
{
/* Name convention throughout this file:
i - input
o - output
m - magnitude
and capital letters for the frequency domain
*/
OptionParser *opt = new OptionParser();
opt->setFlag("help",'h');
opt->setOption("x1");
opt->setOption("x2");
opt->setOption("FFT_N");
opt->setOption("window",'w');
int arg0 = opt->parse(argc,argv);
if (arg0 == argc || opt->getFlag("help"))
{
printf("Usage:\n\tPrgm [-x1 x] [-x2 x] [-FFT_N N] [-w/--window type] file.duet\n\n");
exit(1);
}
Options o(argv[arg0], Quit, 0);
DUETcfg _DUET; // Just to initialize, then a const DUET is initialized from this one.
// Stream behaviour
const int MAX_CLUSTERS = o.i("max_clusters");
const int MAX_ACTIVE_STREAMS = o.i("max_active_streams");
const int MIN_ACTIVE_BLOCKS = o.i("min_active_blocks");
const real A0MIN = o.f("a0min");
const bool STATIC_REBUILD = o.i("DUET.static_rebuild");
_DUET.max_clusters = MAX_CLUSTERS;
_DUET.max_active_streams = MAX_ACTIVE_STREAMS;
_DUET.min_active_blocks = MIN_ACTIVE_BLOCKS;
_DUET.a0min = A0MIN;
_DUET.max_Lambda_distance = o.f("max_Lambda_distance");
_DUET.multiple_assign = o.i("multicluster_assign");
int N_accum = o.i("N_accum_frames"); // how many frames should be accumulated.
// int WAIT = o.i("wait");
fftw_plan xX1_plan, xX2_plan, Xxo_plan;
int FFT_flags;
const int N_max = o.i("N_max");
int N;
Buffer<real> tmp_real_buffer_N_max(N_max); // For calculations in sub-functions but we must allocate the space already
// Choose mic input files
std::string x1_filepath = (opt->Option("x1") ? opt->getOption("x1") : o("x1_wav"));
std::string x2_filepath = (opt->Option("x1") ? opt->getOption("x1") : o("x2_wav"));
// simulation (true) centroids
real true_alpha[N_max];
real true_delta[N_max];
// Read simulation parameters
std::ifstream sim;
sim.open("simulation.log");
Guarantee(sim.is_open(), "Couldn't open simulation log!");
sim >> N;
printf(YELLOW "N=%d" NOCOLOR, N);
for (uint i = 0; i < N; ++i)
sim >> true_alpha[i] >> true_delta[i];
// If N_max > N: Make the remaining true locations invisible by drawing over the same position of one of the active sources
for (uint i = N; i < N_max; ++i)
{
true_alpha[i] = true_alpha[0];
true_delta[i] = true_delta[0];
}
sim.close();
// Write data for gnuplot real source positions overlay.
std::ofstream sim_log;
sim_log.open("s.dat");
for (idx i=0; i < N; ++i)
// The last column is required for splot (0 height suffices for the 2D hist, not the 3D, which should have the height at that point).
sim_log << true_alpha[i] << " " << true_delta[i] << " 0\n\n";
sim_log.close();
SndfileHandle x1_file(x1_filepath), x2_file(x2_filepath);
Guarantee( wav::ok(x1_file) && wav::ok(x2_file) , "Input file doesn't exist.");
Guarantee(wav::mono(x1_file) && wav::mono(x2_file), "Input files must be mono.");
const uint sample_rate_Hz = x1_file.samplerate();
const idx samples = x1_file.frames();
const real Ts = 1.0/(real)sample_rate_Hz;
Buffer<real> x1_wav(samples), x2_wav(samples);
x1_file.read(x1_wav(), samples);
x2_file.read(x2_wav(), samples);
// Only x1's are needed since that's the chosen channel for source separation
Buffers<real> original_waves_x1(N, samples,0,fftw_malloc,fftw_free);
for (int i = 0; i < N; ++i)
{
SndfileHandle wav_file("sounds/s"+std::to_string(i)+"x0.wav");
if (! wav::ok (wav_file))
return EXIT_FAILURE;
wav_file.read(original_waves_x1.raw(i), samples);
}
printf("\nProcessing input file with %lu frames @ %u Hz.\n\n",
samples, sample_rate_Hz);
printf("Max int: %d\n"
"Max idx: %ld\n", INT_MAX, LONG_MAX);
printf("Indexing usage: %.2f%%\n\n", 0.01*(float)x1_file.frames()/(float)LONG_MAX);
const idx FFT_N = (opt->Option("FFT_N") ?