-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRanBox.cpp
3816 lines (3577 loc) · 151 KB
/
RanBox.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
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// R A N B O X
// -----------
//
// This program searches for overdensities in multi-dimensional data
// by first transforming the feature space into its copula by the integral transform on all
// variables. Optionally, principal component
// analysis or a correlated variables removal can be applied to reduce dimensionality.
// The algorithm searches the data for a multi-D box of dimensionality smaller than the original
// one, to locate the box where a test statistic connected to the highest local density is maximized.
// The expected background in the box is computed by considering the box volume, or by
// considering the amount of data in a sideband constructed around the
// box. An iteration of subspaces where the box is constructed scans
// the space of possible overdensities. Two methods are used to find
// the most promising region of space: either with the ZPL maximization
// or with the maximization of the ratio of observed and predicted events.
//
// This version of the code scans in random subspaces where Nvar intervals define the box.
// A twin version of the code instead performs an incremental scan by considering an interval in two of the
// features, locating the Nbest more promising regions, and then incrementing iteratively the number
// of dimensions where an interval smaller than [0,1] is requested, until Nvarmax intervals have
// been imposed (see code RanBoxIter.cpp).
//
// T. Dorigo, 2019-2022
//
//
// To prepare this code for running in your working area, please do the following:
//
// 1) Save this file to the disk area you want to run it on
//
// 2) Change address of input data file and input and output directories:
// dataname = "/lustre/cmswork/dorigo/RanBox/datafiles/HEPMASS/...";
// dataname = "/lustre/cmswork/dorigo/RanBox/datafiles/MiniBooNE/...";
// dataname = "/lustre/cmswork/dorigo/RanBox/datafiles/Fraud/...";
// dataname = "/lustre/cmswork/dorigo/RanBox/datafiles/EEG/...";
// dataname = "/lustre/cmswork/dorigo/RanBox/datafiles/LHCOlympics/...";
// to the correct paths where you stored data. Also change:
// string outputPath = "/lustre/cmswork/dorigo/RanBox/Output";
// string asciiPath = "/lustre/cmswork/dorigo/RanBox/Ascii";
// to your Output and Ascii directories.
//
// 3) To compile, execute the following command
// > g++ -g `root-config --libs --cflags` RanBox.cpp -o RanBox
// 4) To run, try e.g.
// > ./RanBox -Dat 4 -Nsi 1000 -Nba 9000 -Nva 10 -Alg 5
// which generates 10% gaussian signal events (in Gaussian_dims features) on
// a flat background, and searches with a maximum of 10 variables defining the box,
// initializing the box with kernel density estimate.
//
/////////////////////////////////////////////////////////////////////////////////////////////////
#include "TFile.h"
#include "TTree.h"
#include "TCanvas.h"
#include "TStyle.h"
#include "TH1.h"
#include "TH2.h"
#include "TProfile.h"
#include "TF1.h"
#include "TMath.h"
#include "TROOT.h"
#include "TRandom.h"
#include "TRandom3.h"
#include "Riostream.h"
#include "TPrincipal.h" // for PCA
#include <iostream>
#include <fstream>
#include <sstream>
#include <string> // to be able to read in data with commas
using namespace std;
#include "pca.C" // file created by previous iteration on same file
void X2Pmia(Double_t *x, Double_t *p) {
for (Int_t i = 0; i < gNVariables; i++) {
p[i] = 0;
for (Int_t j = 0; j < gNVariables; j++) {
p[i] += (x[j] - gMeanValues[j])
* gEigenVectors[j * gNVariables + i] / gSigmaValues[j];
}
}
}
// Constants
// ---------
static const int maxNtr = 10000;
static bool force_gaussians = false; // In gaussian toy gen, force to pick gaussian dims for subspace
static const int ND = 50; // total number of considered space dimensions
static const int maxNvar = ND; // max dimensionality of search box
static const int maxEvents = 100000;
static const double sqrt2 = sqrt(2.);
static const int maxClosest = 20;
static const int N2var = 105; // maxNvar*(maxNvar-1)/2;
static const double alpha = 0.05;
// Control variables
// -----------------
static int RegFactor = 1; // But it could be larger if using useSB true, because of flukes
static int maxJumps = 10; // max number of jumps in each direction to search for new minima
static double maxBoxVolume = 0.5; // max volume of search box
static double syst = 0.; // systematics on tau!
static int maxGDLoops = 100; // max number of GD loops
static bool verbose = false; // control printouts on screen
static bool plots = true; // whether to plot distributions
static bool RemoveHighCorr = false; // high-correlation vars are removed, NSEL are kept among NAD
static bool Multivariate = true; // whether signal shows correlations among features
static bool debug = false; // couts toggle
static bool compactify = false; // If true, empty space in domain of features is removed
static bool fixed_gaussians = true; // In gaussian toy generations, controls shape of signal
static bool narrow_gaussians = true; // In gaussian toy generations, controls what kind of signal is injected
static int Gaussian_dims = 15;
static double maxRho = 0.2;
static double maxHalfMuRange = 0.35;
static int NseedTrials = 1; // Number of repetition of same subspace search, for tests of clustering
static double shrinking_factor = 0.9; // decreasing factor for steps in direction not previously taken
static double widening_factor = 1.0; // widening factor for steps in same direction
static double InitialLambda = 0.5; // step size in search
static double sidewidth = 0.5;
static double D2kernel = 0.04;
// Other control variables
// -----------------------
static double bignumber = pow(10,20.);
static double smallnumber = pow(10,-20.);
static double epsilon = 0.01; // coarseness of scan of multi-D unit cube
static double InvEpsilon = 100.; // inverse of epsilon
// Factorial function
// ------------------
double Factorial (int n) {
if (n<=1) return 1;
double r = 1.;
for (int i=1; i<=n; i++) {
r *= i;
}
return r;
}
// Tail probability for observing >=n events when mu are expected from a Poisson
// -----------------------------------------------------------------------------
double Poisson (double n, double mu) {
return TMath::Gamma(n,mu);
}
// Return Z score for a Poisson counting exp seeing n, expecting mu events
// -----------------------------------------------------------------------
double Zscore_Poisson (double n, double mu) {
double p = TMath::Gamma(n,mu);
if (p<1.E-310) return 37.7; // for larger significances it breaks down
return sqrt(2)*TMath::ErfcInverse(2*p);
}
// Ratio maximization based on on/off using box volume and total stat in full space
// --------------------------------------------------------------------------------
double R (int Non, int Ntot, double volume) {
if (volume==0.) return 0.;
double tau = (1.-volume)/volume;
int Noff = Ntot-Non;
return (double)Non/(Ntot*volume+1.);
}
// Ratio maximization based on on/off, version 2 with regularization
// -----------------------------------------------------------------
double R2 (int Non, double Noff) {
double r = (double)Non/(RegFactor+Noff);
return r;
}
// Profile likelihood Z score from Li and Ma for on/off problem - we will use this,
// as it is defined without problem for arbitrarily large inputs
// --------------------------------------------------------------------------------
double ZPL (int Non, int Ntot, double volume) {
if (volume==0 || volume==1 || Non==0) return 0.;
if (Non>0 && Ntot-Non==0) return 0.;
double tau = (1.-volume)/volume;
if (Non==(Ntot-Non)/tau) return 0.;
int Noff = Ntot-Non;
double z = sqrt(2)* pow (Non*log(Non*(1+tau)/Ntot)+Noff*log(Noff*(1+tau)/(Ntot*tau)),0.5);
if (z!=z) return 0.;
if ((double)Non<Noff/tau) return -z;
return z;
}
// Profile likelihood Z score from Li and Ma for on/off problem
// Version with direct tau input
// ------------------------------------------------------------
double ZPLtau (int Non, int Noff, double tau) {
if (Non==0 || Noff==0 || Non==Noff/tau || tau==0) return 0;
if (Non>0 && Noff==0) return 0.;
int Ntot = Non+Noff;
double z = sqrt2 * pow (Non*log(Non*(1+tau)/Ntot)+Noff*log(Noff*(1+tau)/(Ntot*tau)),0.5);
if (z!=z) return 0.;
if ((double)Non<Noff/tau) return -z;
return z;
}
// Version of ZPL which incorporates a possible background systematic in the form
// of passing lowest Z considering tau variations by syst*100%
// ------------------------------------------------------------------------------
double ZPLsyst (int Non, int Ntot, double volume, double syst) {
if (volume==0 || volume==1 || Non==0) return 0.;
if (Non>0 && Ntot-Non==0) return 0.;
double tau = (1.-volume)/volume;
if (Non==(Ntot-Non)/tau) return 0.;
double taulow = (1.-syst)*(1.-volume)/volume;
double tauhig = (1.+syst)*(1.-volume)/volume;
int Noff = Ntot-Non;
double z = sqrt2 * pow (Non*log(Non*(1+tau)/Ntot)+Noff*log(Noff*(1+tau)/(Ntot*tau)),0.5);
double zhig = sqrt2 * pow (Non*log(Non*(1+tauhig)/Ntot)+Noff*log(Noff*(1+tauhig)/(Ntot*tauhig)),0.5);
double zlow = sqrt2 * pow (Non*log(Non*(1+taulow)/Ntot)+Noff*log(Noff*(1+taulow)/(Ntot*taulow)),0.5);
if ((double)Non<Noff/tau) z = -z;
if ((double)Non<Noff/tauhig) zhig = -zhig;
if ((double)Non<Noff/taulow) zlow = -zlow;
if (z>zhig) z = zhig;
if (z>zlow) z = zlow;
if (z!=z) return 0.;
return z;
}
// Cholesky-Banachiewicz decomposition of covariance matrix, used to generate a multivariate
// Gaussian distribution in N dimensions.
// NB It returns false (without finishing the calculation of L) if A is not pos.def., thereby
// it can be directly used to check that A is indeed positive definite.
// ------------------------------------------------------------------------------------------
static double A[ND][ND];
static double L[ND][ND];
bool Cholesky(int N) {
// We take a covariance matrix A, of dimension NxN, and we find a lower triangular
// matrix L such that LL^T = A. See https://en.wikipedia.org/wiki/Cholesky_decomposition
// -------------------------------------------------------------------------------------
double sum1;
double sum2;
for (int i=0; i<N; i++) {
for (int j=0; j<N; j++) {
L[i][j] = 0;
}
}
for (int i=0; i<N; i++) {
for (int j=0; j<=i; j++) {
sum1 = 0;
sum2 = 0;
if (j>0) {
for (int k=0; k<j-1; k++) {
sum1 += L[i][k] * L[j][k];
}
for (int k=0; k<j-1; k++) {
sum2 += L[j][k] * L[j][k];
}
}
if (i==j) {
L[j][j] = sqrt(A[j][j]-sum2);
} else { // i>j
L[i][j] = (A[i][j]-sum1)/L[j][j];
} // all others remain zero
if (L[i][j] != L[i][j]) return false;
}
}
return true;
}
// This routine determines the sidebands of a box in a foul-proof way
// NB unlike before, we allow boundaries of sidebands to have any value
// --------------------------------------------------------------------
void determineSB (double Smi[maxNvar], double Sma[maxNvar], double Bmi[maxNvar], double Bma[maxNvar], int Nvar) {
double minratio = bignumber;
double AvailableRatio[maxNvar];
// Find minimum ratio of available space to box space, among all directions
for (int i=0; i<Nvar; i++) {
Smi[i] = Bmi[i]*(1+sidewidth)-Bma[i]*sidewidth;
if (Smi[i]<0.) Smi[i] = 0.;
Sma[i] = Bma[i]*(1+sidewidth)-Bmi[i]*sidewidth;
if (Sma[i]>1.) Sma[i] = 1.;
AvailableRatio[i] = (1.-(Bma[i]-Bmi[i]))/(Bma[i]-Bmi[i]);
if (AvailableRatio[i]<minratio) minratio = AvailableRatio[i];
}
// Order by available ratio
int ind[maxNvar];
for (int i=0; i<Nvar; i++) { ind[i]=i; };
for (int times=0; times<Nvar; times++) {
for (int i=Nvar-1; i>0; i--) {
if (AvailableRatio[ind[i]]<AvailableRatio[ind[i-1]]) {
// Swap indices
int tmp = ind[i];
ind[i] = ind[i-1];
ind[i-1] = tmp;
}
}
}
// Now AvailableRatio[ind[Nvar-1]] is the largest, AvailableRatio[ind[0]] is the smallest
double NeededRatioPerVar;
double CurrentFactor = 1.;
for (int i=0; i<Nvar; i++) {
if (AvailableRatio[ind[i]]==0) continue; // can't use this dimension
NeededRatioPerVar = pow(2./CurrentFactor,1./(Nvar-i))-1.;
if (AvailableRatio[ind[i]]<NeededRatioPerVar) { // use all the space available for this var
Smi[ind[i]] = 0.;
Sma[ind[i]] = 1.;
CurrentFactor = CurrentFactor*(1.+AvailableRatio[ind[i]]);
if (i<Nvar-1) NeededRatioPerVar = pow(2./CurrentFactor,Nvar-i-1)-1.; // rescaled needed ratio for the others
} else { // We can evenly share the volume in the remaining coordinates
double distmin = Bmi[ind[i]];
double deltax = Bma[ind[i]]-Bmi[ind[i]];
if (distmin>1.-Bma[ind[i]]) { // Upper boundary is closest
distmin = 1.-Bma[ind[i]];
if (2.*distmin/deltax>=NeededRatioPerVar) {
Smi[ind[i]] = Bmi[ind[i]]-NeededRatioPerVar*deltax/2.; // epsilon*(int)(InvEpsilon*(Bmi[ind[i]]-NeededRatioPerVar*deltax/2.));
Sma[ind[i]] = Bma[ind[i]]+NeededRatioPerVar*deltax/2.; // epsilon*(int)(InvEpsilon*(Bma[ind[i]]+NeededRatioPerVar*deltax/2.));
} else {
Sma[ind[i]] = 1.;
Smi[ind[i]] = 1.-deltax*(1.+NeededRatioPerVar); // epsilon*(int)(InvEpsilon*(1.-deltax*(1.+NeededRatioPerVar)));
}
CurrentFactor = CurrentFactor*(1.+NeededRatioPerVar);
} else { // lower boundary is closest
if (2.*distmin/deltax>=NeededRatioPerVar) {
Smi[ind[i]] = Bmi[ind[i]]-NeededRatioPerVar*deltax/2.; // epsilon*(int)(InvEpsilon*(Bmi[ind[i]]-NeededRatioPerVar*deltax/2.));
Sma[ind[i]] = Bma[ind[i]]+NeededRatioPerVar*deltax/2.; // epsilon*(int)(InvEpsilon*(Bma[ind[i]]+NeededRatioPerVar*deltax/2.));
} else {
Smi[ind[i]] = 0.;
Sma[ind[i]] = deltax*(1.+NeededRatioPerVar); // epsilon*(int)(InvEpsilon*(deltax*(1.+NeededRatioPerVar)));
}
CurrentFactor = CurrentFactor*(1.+NeededRatioPerVar);
}
}
}
return;
}
// This routine checks whether n has binary decomposition with bit index on
// ------------------------------------------------------------------------
bool bitIsOn (int n, int index) {
int imax = (int)(log(n)/log(2));
if (imax<index) return false;
for (int i=imax; i>=index; i--) {
if (n-pow(2,i)>=0) {
n = n-pow(2,i);
if (imax==index) return true;
}
}
return false;
}
// ----------------------------------------------------------------------------------------------
//
// ----------------
// R A N B O X
// ----------------
//
// This macro scans NSEL-dimensional subspaces of a NAD dimensional feature
// space, in search for a multidimensional interval which contains significantly
// more data than predicted from uniform density assumptions.
// The data are preprocessed to fit in a hypercube whose marginals are all flat,
// and optionally reduced by principal component analysis.
// The box scanning each subspace is initialized at random (if Algorithm=0) or by
// finding a dense region with a cluster search.
// The test statistic that defines the most dense regions can be chosen between
// a "Profile likelihood" Z-value and a density ratio.
// It is possible to generate synthetic data flat in all features or with an injected
// fraction of signal sampled from a multidimensional gaussian of customizable parameters.
// In this version the code may also read in data from the "HEPMASS" dataset available
// from the UCI repository, the miniBooNE dataset, or a credit card fraud dataset.
//
// Original creation - Tommaso Dorigo, 2019-2022
// ------------------------------------------------------------------------------------------------------
int main (int argc, char *argv[]) {
// dataset: type of dataset used in search:
// 0=HEPMASS; (see http://archive.ics.uci.edu/ml/datasets/hepmass)
// 1=miniBooNE; (see https://archive.ics.uci.edu/ml/datasets/MiniBooNE+particle+identification)
// 2=credit card fraud data; (see https://archive.ics.uci.edu/ml/datasets/default+of+credit+card+clients)
// 3=EEG data; (see https://archive.ics.uci.edu/ml/datasets/EEG+Eye+State)
// 4=synthetic dataset (mock - generated on demand);
// 5=LHC olympics 2020 qq dataset (see https://zenodo.org/record/6466204#.Ypdsl-ixVhF).
// 6=LHC olympics 2020 qqq dataset (see https://zenodo.org/record/6466204#.Ypdsl-ixVhF).
// Defaults
// --------
int dataset = 0;
int Ntrials = 1000;
int Nsignal = 200;
int Nbackground = 4800;
int Algorithm = 5;
bool useZPL = false;
bool useSB = true;
bool PCA = false;
int Nvar = 8;
int Nremoved = 0;
int speedup = 1;
int NH0 = 1;
for (int i=1; i<argc; i++) { // NNBB the first argv is the command launching the program itself! so i=1
if (!strcmp(argv[i],"-h")) {
cout << "List of arguments:" << endl;
cout << "-Dat Dataset type" << endl;
cout << "-Ntr Number of trials" << endl;
cout << "-Nsi Number of signal events" << endl;
cout << "-Nba Number of background events" << endl;
cout << "-Alg Initialization algorithm (1-5)" << endl;
cout << "-Zpl Use ZPL test stat (default false)" << endl;
cout << "-Pca Whether to do PCA (def false)" << endl;
cout << "-Nva Number of variables" << endl;
cout << "-Nre Variables to remove" << endl;
cout << "-Spe Speedup factor in search" << endl;
cout << "-Reg regularization factor (only if not using -Zpl)" << endl;
return 0;
}
else if (!strcmp(argv[i],"-Dat")) {dataset = atoi(argv[++i]);}
else if (!strcmp(argv[i],"-Ntr")) {Ntrials = atoi(argv[++i]);}
else if (!strcmp(argv[i],"-Nsi")) {Nsignal = atoi(argv[++i]);}
else if (!strcmp(argv[i],"-Nba")) {Nbackground = atoi(argv[++i]);}
else if (!strcmp(argv[i],"-Alg")) {Algorithm = atoi(argv[++i]);}
else if (!strcmp(argv[i],"-Nva")) {Nvar = atoi(argv[++i]);}
else if (!strcmp(argv[i],"-Nre")) {Nremoved = atoi(argv[++i]);}
else if (!strcmp(argv[i],"-Spe")) {speedup = atoi(argv[++i]);}
else if (!strcmp(argv[i],"-Reg")) {RegFactor = atoi(argv[++i]);}
else if (!strcmp(argv[i],"-Zpl")) {useZPL = true; useSB = false; ++i;}
else if (!strcmp(argv[i],"-Pca")) {PCA = true; ++i;}
else {
cout << "Warning, choices not allowed" << endl;
return 0;
}
}
// dataset: type of dataset used in search:
// 0=HEPMASS; 1=miniBooNE; 2=fraud data; 3=EEG data; 4=synthetic dataset (mock); 5=LHC olympics 2020 dataset.
// Ntrials: number of random subspaces investigated
// Algorithm: type of seeding clustering used in initialization of box
// useZPL: whether to use ZPL as test statistic to maximize
// useSB: whether to use sidebands in density prediction inside box
// PCA: whether to apply PCA to data (removing lowest Nremoved components)
// Nvar: box dimension
// Nremoved: removed dimensions (with PCA or with discarding highly correlated variables)
// speedup: reduction factor of used data in initial clustering
// RegFactor: added number of exp background to denominator of R_reg test statistic
// If one_off, we provide a single list of features for the only subspace to investigate.
// This allows to keep RanBox and RanBoxIter code versions aligned.
// --------------------------------------------------------------------------------------
bool one_off = false;
if (one_off) {
Nvar = 12;
}
int Ivar_fix[12] = { 17, 21, 9, 5, 10, 13, 14, 18, 26, 6, 24, 11 };
// int Ivar_fix[12] = { 0, 1, 3, 5, 7, 9, 10, 11, 14, 15, 16, 19 };
// Depending on user choices, dimensions are set differently:
// ----------------------------------------------------------
int NAD;
int NSEL;
if (Nremoved>0) {
if (PCA) {
RemoveHighCorr = false;
} else {
RemoveHighCorr = true;
}
}
bool mock = false;
if (dataset==0) { // HEPMASS data
NAD = 27;
NSEL = NAD-Nremoved;
} else if (dataset==1) { // MiniBooNE data
NAD = 50;
NSEL = NAD-Nremoved;
D2kernel = 0.1;
} else if (dataset==2) { // credit card data
NAD = 30;
NSEL = NAD-Nremoved;
D2kernel = 0.04;
} else if (dataset==3) { // EEG eye detection data
NAD = 14;
NSEL = NAD-Nremoved;
D2kernel = 0.04;
} else if (dataset==4) { // mock data
NAD = 20;
NSEL = 20;
mock = true;
} else if (dataset==5) { // LHC olympics 2020
NAD = 14;
NSEL = NAD-Nremoved;
D2kernel = 0.01; // check
mock = false;
} else if (dataset==6) { // LHC olympics 2020
NAD = 14;
NSEL = NAD-Nremoved;
D2kernel = 0.01; // check
mock = false;
}
// Change preset generator
// NB other versions of TRandom are flawed
// ---------------------------------------
delete gRandom;
double seed = 0.1;
TRandom3 * myRNG = new TRandom3();
gRandom = myRNG;
gRandom->SetSeed(seed);
// Check if input parameters and other user choices are consistent
// ---------------------------------------------------------------
if (pow(0.5,Nvar)*(Nsignal+Nbackground)<1) cout << "Warning - too few events for this Nvar" << endl;
if (NAD<Nvar) {
cout << " Sorry, cannot set subspace dimension larger than active variables dim." << endl;
return 0; // (to avoid infinite loop in choosing vars)
}
if (Nvar<2) {
cout << " Sorry, Nvar must be >=2" << endl;
return 0;
}
if (maxHalfMuRange>=0.5) maxHalfMuRange = 0.499;
if (Algorithm!=0) maxJumps = 0; // It is only useful for random seeding
if ((Gaussian_dims>0 && Nsignal==0 && mock) ||
(NseedTrials>1 && Ntrials>1) || (!fixed_gaussians && maxHalfMuRange!=0.35)) {
cout << " Inconsistent choice of pars." << endl;
return 0;
}
if (dataset==1 && NH0>1) {
cout << " Sorry, can only do 1 trial with miniBoone data for now" << endl;
return 0;
}
if (force_gaussians && Gaussian_dims<Nvar && Gaussian_dims>0) {
cout << " Cannot have forced gaussians on with these settings!" << endl;
return 0;
}
if (NH0>1) plots = false;
if (speedup<1) speedup = 1; // factor to speed up algorithms of clustering, set >1 (e.g. 4 or 8) for quick checks
double did = 999.999*gRandom->Uniform(); // Identifier for summary printouts
int id = (int)did;
if (Nbackground+Nsignal<=100) return 0; // Avoid too small datasets;
double FlatFrac = Nbackground/(Nbackground+Nsignal); // FlatFrac: fraction of flat events in toy
// (the rest are multivariate normal)
// Defaults
// --------
string outputPath = "/lustre/cmswork/dorigo/RanBox/Output";
string asciiPath = "/lustre/cmswork/dorigo/RanBox/Ascii";
std::stringstream sstr;
std::stringstream sstr2;
if (mock) {
sstr << "/RB_mock_" << id << "_Ntr" << Ntrials
<< "_NS" << Nsignal << "_NB" << Nbackground << "_A" << Algorithm;
if (Algorithm>0) sstr << "_SP" << speedup;
if (fixed_gaussians) {
sstr << "_FiG";
if (narrow_gaussians) {
sstr << 0.05;
} else {
sstr << 0.10;
}
}
sstr << "_FoG" << force_gaussians
<< "_NG" << Gaussian_dims; // << "_MR" << maxRho << "_MHW" << maxHalfMuRange;
if (NH0>1) sstr << "_Nrep" << NH0;
} else {
if (dataset==0) {
sstr << "/RB_HEPMASS_" << id << "_Ntr" << Ntrials
<< "_NS" << Nsignal << "_NB" << Nbackground << "_A" << Algorithm;
} else if (dataset==1) {
sstr << "/RB_miniBooNE_" << id << "_Ntr" << Ntrials
<< "_NS" << Nsignal << "_NB" << Nbackground << "_A" << Algorithm;
} else if (dataset==2) {
sstr << "/RB_fraud_" << id << "_maxNv" << Ntrials
<< "_NS" << Nsignal << "_NB" << Nbackground << "_A" << Algorithm;
} else if (dataset==3) {
sstr << "/RB_EEG_" << id << "_maxNv" << Ntrials
<< "_NS" << Nsignal << "_NB" << Nbackground << "_A" << Algorithm;
} else if (dataset==4) {
sstr << "/RB_mock_" << id << "_maxNv" << Ntrials
<< "_NS" << Nsignal << "_NB" << Nbackground << "_A" << Algorithm;
} else if (dataset==5) {
sstr << "/RB_LHCOlympics_" << id << "_maxNv" << Ntrials
<< "_NS" << Nsignal << "_NB" << Nbackground << "_A" << Algorithm;
} else if (dataset==6) {
sstr << "/RB_LHCOlympics_qqq_" << id << "_maxNv" << Ntrials
<< "_NS" << Nsignal << "_NB" << Nbackground << "_A" << Algorithm;
}
}
if (Algorithm>0) sstr << "_SP" << speedup;
if (useZPL) {
sstr << "_ZPL";
} else {
sstr << "_R2";
}
if (useSB) {
sstr << "_SB";
} else {
sstr << "_Vol";
}
string rootfile = outputPath + sstr.str() + ".root";
string asciifile = asciiPath + sstr.str() + ".asc";
string summaryfile;
string zplfile;
if (dataset==0) {
summaryfile = asciiPath + "/SummaryRB_HEPMASS.asc";
} else if (dataset==1) {
summaryfile = asciiPath + "/SummaryRB_miniBooNE.asc";
} else if (dataset==2) {
summaryfile = asciiPath + "/SummaryRB_fraud.asc";
} else if (dataset==3) {
summaryfile = asciiPath + "/SummaryRB_EEG.asc";
} else if (dataset==4) {
summaryfile = asciiPath + "/SummaryRB_mock.asc";
} else if (dataset==5) {
summaryfile = asciiPath + "/SummaryRB_LHCOlympics.asc";
} else if (dataset==6) {
summaryfile = asciiPath + "/SummaryRB_LHCOlympics_qqq.asc";
}
ofstream results; // output file
ofstream summary; // summary file
ofstream zpl;
// Create big array to store event kinematics
// ------------------------------------------
float * feature_all = new float[(maxEvents)*ND];
int * order_ind_all = new int[(maxEvents)*ND];
float ** feature = new float*[ND];
int ** order_ind = new int*[ND];
for (int i=0; i<ND; i++) {
feature[i] = feature_all+(maxEvents)*i;
order_ind[i] = order_ind_all+(maxEvents)*i;
}
double * xtmp = new double[maxEvents];
bool * isSignal = new bool[maxEvents];
int * cum_ind = new int[maxEvents];
// Arrays used for cluster search
// ------------------------------
int * Closest = new int[maxEvents];
int * PB_all = new int[(maxEvents)*maxClosest];
int ** PointedBy = new int*[maxClosest];
for (int i=0; i<maxClosest; i++) {
PointedBy[i] = PB_all+(maxEvents)*i;
}
int * AmClosest = new int[maxEvents];
// Header Printout
// ---------------
cout << endl;
cout << " -------------------------------------------------------------------------------------------" << endl;
cout << endl;
cout << " R A N B O X" << endl;
cout << " ----------------" << endl;
cout << endl;
// Set up ascii output
// -------------------
results.open(asciifile);
summary.open(summaryfile, std::ios::out | std::ios::app);
if (NH0>1) zpl.open(zplfile, std::ios::out | std::ios::app);
results << " ----------------------------- " << endl;
results << " R A N B O X " << endl;
results << " ----------------------------- " << endl << endl << endl;
results << " Parameters: " << endl;
results << " ----------------------------- " << endl << endl;
results << " Dataset = ";
if (dataset==0) results << "HEPMASS data" << endl;
if (dataset==1) results << "miniBooNE data " << endl;
if (dataset==2) results << "Credit card frauds" << endl;
if (dataset==3) results << "EEG data" << endl;
if (dataset==4) results << "MOCK data" << endl;
if (dataset==5) results << "LHC olymplics data" << endl;
if (dataset==6) results << "LHC olymplics data qqq" << endl;
results << " Nsignal = " << Nsignal << endl;
results << " Nbackground = " << Nbackground << endl;
results << " NAD = " << NAD << endl;
results << " PCA = " << PCA << endl;
if (PCA) results
<< " NSEL = " << NSEL << endl;
results << " Nvar = " << Nvar << endl;
results << " Algorithm = " << Algorithm << endl;
results << " Speedup = " << speedup << endl;
results << " useSB = " << useSB <<endl;
results << " useZPL = " << useZPL << endl;
if (useZPL) {
results << " Syst = " << syst << endl;
} else {
results << " RegFactor = " << RegFactor << endl;
}
results << " Root file = " << rootfile << endl;
results << " maxBoxVolume = " << maxBoxVolume <<endl;
results << " maxGDLoops = " << maxGDLoops << endl;
if (mock) {
results << " Fixed gauss = " << fixed_gaussians << endl;
results << " Narrow gauss = " << narrow_gaussians << endl;
results << " Gaussian dims= " << Gaussian_dims << endl;
results << " Force gauss = " << force_gaussians << endl;
results << " maxRho = " << maxRho << endl;
results << " maxHalfMuR = " << maxHalfMuRange << endl;
}
results << " Nremoved = " << Nremoved << endl;
results << " id = " << id << endl;
results << endl;
// Control histograms
// ------------------
TH1F * Zvalue_in = new TH1F ( "Zvalue_in", "", 200, 0., 50.);
TH1F * Zvalue_fi = new TH1F ( "Zvalue_fi", "", 200, 0., 50.);
TH2F * Bounds_in = new TH2F ( "Bounds_in", "", 60, -0.1, 1.1, 60, -0.1, 1.1);
TH2F * Bounds_fi = new TH2F ( "Bounds_fi", "", 60, -0.1, 1.1, 60, -0.1, 1.1);
TH2F * Drift = new TH2F ( "Drift", "", 50, -1., 1., 50, -1., 1.);
TH1F * NGDsteps = new TH1F ( "NGDsteps", "", maxGDLoops+1, -0.5, maxGDLoops+0.5);
TH1F * Ninbox_in = new TH1F ( "Ninbox_in", "", 100, 0., 200.);
TH1F * Ninbox_fi = new TH1F ( "Ninbox_fi", "", 100, 0., 200.);
TH2F * Ninbox_in_vs_fi = new TH2F ( "Ninbox_in_vs_fi", "", 50, 0., 200., 50, 0., 200.);
TH1F * InitialDensity = new TH1F ( "InitialDensity", "", 100, 0., 5.);
TH1F * InitialVolume = new TH1F ( "InitialVolume", "", 100, 0., 0.5);
TH1F * NClomax = new TH1F ( "NClomax", "", 40, 0., 40. );
TH1F * ZH0 = new TH1F ( "ZH0", "", 1000, 0., 100.);
TProfile * ZvsOrder = new TProfile ("ZvsOrder", "", 20, 0., 2., 0., 30.);
TCanvas * PP;
TCanvas * OP;
TCanvas * UP;
TCanvas * P2;
TCanvas * OP2;
TCanvas * UP2;
// Construct plots of marginals for the considered features in the best box
// ------------------------------------------------------------------------
// If PCA, transformed components; otherwise original
TH1D * Plot_al[maxNvar];
TH1D * Plot_in[maxNvar];
TH1D * Plot_ex[maxNvar];
TH1D * Plot_si[maxNvar];
// Original coordinates - NB the PCA untransformed space has all coordinates
TH1D * OPlot_al[maxNvar];
TH1D * OPlot_in[maxNvar];
TH1D * OPlot_si[maxNvar];
// no exclusive n-1 plot since this has no meaning in backtransformed space
// Uniform marginals transforms (of PCA or normal, depending if PCA)
TH1D * UPlot_al[maxNvar];
TH1D * UPlot_in[maxNvar];
TH1D * UPlot_ex[maxNvar];
TH1D * UPlot_si[maxNvar];
// Scatterplots now
// ----------------
TH2D * SCP_al[N2var];
TH2D * SCP_in[N2var];
TH2D * SCP_ex[N2var];
TH2D * OSCP_al[N2var];
TH2D * OSCP_in[N2var];
// for original space n-2 plots make no sense
TH2D * USCP_al[N2var];
TH2D * USCP_in[N2var];
TH2D * USCP_ex[N2var];
// Generic variable names
// ----------------------
TString varname[ND] = { "V00", "V01", "V02", "V03", "V04", "V05", "V06", "V07", "V08", "V09",
"V10", "V11", "V12", "V13", "V14", "V15", "V16", "V17", "V18", "V19",
"V20", "V21", "V22", "V23", "V24", "V25", "V26", "V27", "V28", "V29",
"V30", "V31", "V32", "V33", "V34", "V35", "V36", "V37", "V38", "V39",
"V40", "V41", "V42", "V43", "V44", "V45", "V46", "V47", "V48", "V49" };
TString varname_mock[ND];
// Variables to print out progress information during run time
// -----------------------------------------------------------
char progress[53] = {"[--10%--20%--30%--40%--50%--60%--70%--80%--90%-100%]"};
int currchar;
int block;
bool messaged = false;
ifstream events; // input file
// Other vars and counters
// -----------------------
float Xmin[ND];
float Xmax[ND];
float OXmin[ND];
float OXmax[ND];
double mean[ND];
double sigma[ND];
bool Gaussian[ND];
double gauss[ND];
// Variables used for best box
// ---------------------------
int Ivar[maxNvar]; // Nvar is the number of features used to create a box
double Blockmin[maxNvar]; // Blockmin is the left boundary of the block
double Blockmax[maxNvar]; // Blockmax is the right boundary of the block
double Sidemin[maxNvar];
double Sidemax[maxNvar];
// And for the best block found:
int Ivar_best[maxNvar];
double Blockmin_best[maxNvar];
double Blockmax_best[maxNvar];
double Zval_best = -bignumber; // Absolute best Z value in all trials
double Nin_best = 0; // N in best box
double Nexp_best = 0; // expected N from volume
int gd_best = 0; // Loops for best Z region
int trial_best = 0;
double ID_best = 0; // initial density of box
int Ivar_int[8] = {0,1,2,3,4,5,6,7}; // orig vars for scatterplots
// Check if Ntrials is consistent
// ------------------------------
bool doall = false;
double comb = Factorial(NSEL)/(Factorial(Nvar)*Factorial(NSEL-Nvar));
if (Ntrials>comb/3) {
cout << " Ntrials large for random subspace search:" << endl;
cout << " Number of combinations is " << comb << " - will do all" << endl;
doall = true;
for (int k=0; k<Nvar; k++) { Ivar[k] = k; }; // if we are doing the combinatorial, we need to init
Ntrials = comb;
}
// But don't forget the max dimensions!
// ------------------------------------
if (Ntrials>maxNtr) {
cout << " max number of trials is " << maxNtr
<< " - setting Ntrials to " << maxNtr << endl;
Ntrials = maxNtr;
}
// If we are testing the accuracy of different seeding algorithms, we need to
// keep track of the following:
// --------------------------------------------------------------------------
double Aver_SF_caught = 0.;
double Aver2_SF_caught = 0.;
double Aver_1s_contained = 0.;
double Aver2_1s_contained = 0.;
if (!mock) NseedTrials = 1;
int goodevents;
// Variables used to keep track of results
// ---------------------------------------
int * bv_all = new int[maxNvar*maxNtr];
int ** BoxVar = new int*[maxNtr];
for (int i=0; i<maxNtr; i++) {
BoxVar[i] = bv_all+(maxNvar)*i;
}
// int BoxVar[maxNtr][maxNvar];
double * BoxVol = new double[maxNtr];
double * BoxNin = new double[maxNtr];
double * BoxNex = new double[maxNtr];
double * BoxZpl = new double[maxNtr];
double * BoxSFr = new double[maxNtr];
int * BoxInd = new int[maxNtr];
for (int i=0; i<maxNtr; i++) {
BoxVol[i] = 1.;
BoxNin[i] = 0.;
BoxNex[i] = 0.;
BoxZpl[i] = 0.;
BoxSFr[i] = 0.;
BoxInd[i] = 0;
for (int j=0; j<maxNvar; j++) {
BoxVar[j][i] = 0;
}
}
// Loop for test of cluster seeding (uncomment if necessary)
// ---------------------------------------------------------
// for (int Ntestseed=0; Ntestseed<NseedTrials; Ntestseed++) {
string alphabet [] = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p",
"q","r","s","t","u","v","w","x","y","z"};
int save_p = 0;
int save_q = 0;
bool closed = true;
ifstream file;
string dataname;
// BIG LOOP FOR H0 //////////////////////////////////////////////////////////////////
for (int IH0=0; IH0<NH0; IH0++) {
results << "\n\nCycle n: " << IH0 << endl << endl;
Zval_best = -bignumber;
Nin_best = 0;
Nexp_best = 0;
gd_best = 0;
ID_best = 0;
int NSread = 0;
int NBread = 0;
// This macro can process data from input files, or generate mock data from flat and gaussians
// -------------------------------------------------------------------------------------------
if (mock) {
int Nmock = Nsignal+Nbackground;
if (Gaussian_dims==0) {
// Generate flat data for calibration of Z-values
// ----------------------------------------------
for (int i=0; i<Nmock; i++) {
for (int dim=0; dim<NAD; dim++) {
feature[dim][i] = gRandom->Uniform();
}
}
NBread = Nmock;
NSread = 0;
for (int dim=0; dim<NAD; dim++) {
varname_mock[dim] = "Flat";
}
} else { // >0 gaussian dims
// First of all, generate multivariate gaussian means and covariance matrix, and decomposition
// -------------------------------------------------------------------------------------------
// Generate covariance matrix
// First the diagonal terms
for (int dimx=0; dimx<Gaussian_dims; dimx++) {
if (fixed_gaussians) {
if (narrow_gaussians) {
sigma[dimx] = 0.05;
} else {
sigma[dimx] = 0.10;
}
} else {
if (narrow_gaussians) {
sigma[dimx] = gRandom->Uniform(0.01,0.1);
} else {
sigma[dimx] = gRandom->Uniform(0.05,0.15);
}
}
if (fixed_gaussians) {
mean[dimx] = gRandom->Uniform(0.5-maxHalfMuRange,0.5+maxHalfMuRange);
} else {
mean[dimx] = gRandom->Uniform(3*sigma[dimx],1.-3*sigma[dimx]);
}
A[dimx][dimx] = sigma[dimx]*sigma[dimx];
}
if (Multivariate) {
// Then the off-diagonal terms
double maxcorr = 1.;
int Nattempts = 0;
bool success = false;
do {
for (int dimx=0; dimx<Gaussian_dims-1; dimx++) {
for (int dimy = dimx+1; dimy<Gaussian_dims; dimy++) {
if (fixed_gaussians) {
double rnd = gRandom->Uniform();
double rho = 2.*(rnd-0.5)*maxRho;
/* if (rnd<1/3.) { */
/* rho = -maxRho; */
/* } else if (rnd<2/3.) { */
/* rho = 0.; */
/* } else { */
/* rho = maxRho; */
A[dimx][dimy] = rho * sqrt(A[dimx][dimx]*A[dimy][dimy]);
} else {
A[dimx][dimy] = gRandom->Uniform(-maxcorr,maxcorr) * sqrt(A[dimx][dimx]*A[dimy][dimy]);
}
A[dimy][dimx] = A[dimx][dimy];
}
}
// The following is necessary in order to keep a good chance
// that a positive-defined matrix is found, when Gaussian_dims is large (NB it's not useful for fixed_gaussians=true)
maxcorr = maxcorr/1.001;
Nattempts++;
success = Cholesky(Gaussian_dims);
} while (!success && Nattempts<10000);
// Find Cholesky decomposition A = L * L^T
if (success) {
cout << " Cholesky decomposition of covariance done after " << Nattempts
<< " attempts, maxcorr = " << maxcorr << endl;
} else {
cout << " Could not decompose covariance, stopping." << endl;
return 0;
}
} // end if Multivariate
// Generate flat data plus a Gaussian multivariate in some of the features
// -----------------------------------------------------------------------
for (int dim=0; dim<NAD; dim++) {
if (dim>=Gaussian_dims) {
Gaussian[dim] = false;
varname_mock[dim] = "Flat";
} else {
Gaussian[dim] = true;
varname_mock[dim] = "Gaus";
}
}
NSread = 0;
NBread = 0;
for (int i=0; i<Nmock; i++) {
bool unif;
double f;
if (i<Nbackground) {
unif = true;
NBread++;
isSignal[i] = false;
} else {
unif = false;
NSread++;
isSignal[i] = true;
}
// Vector of normals
int gausdim = 0;