-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKalibri.cc
1147 lines (1054 loc) · 39.1 KB
/
Kalibri.cc
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
// $Id: Kalibri.cc,v 1.29 2012/02/06 22:41:55 kirschen Exp $
#include "Kalibri.h"
#include <algorithm>
#include <iomanip>
//Boost
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
boost::mutex io_mutex;
// User
#include "CalibMath.h"
#include "ConfigFile.h"
#include "Parameters.h"
#include "ControlPlots.h"
#include "ControlPlotsResolution.h"
#include "external.h"
#include "ToyMC.h"
#include "PhotonJetReader.h"
#include "ThreadedDiJetReader.h"
#include "TriJetReader.h"
#include "ZJetReader.h"
#include "TopReader.h"
#include "ParameterLimitsReader.h"
#include "EventProcessor.h"
#include "DiJetEventCuts.h"
#include "EventWeightProcessor.h"
#include "PUTruthReweighting.h"
#include "PUEventWeightProcessor.h"
#include "EventBinning.h"
#include "DiJetEventWeighting.h"
#include "DiJetEventBinning.h"
#include <dlfcn.h>
#include "Math/Minimizer.h"
#include "Math/Factory.h"
#include "Math/Functor.h"
using namespace std;
typedef std::vector<Event*>::iterator DataIter;
typedef std::vector<Event*>::const_iterator DataConstIter;
//! \brief Outlier Rejection
// -----------------------------------------------------------------
struct OutlierRejection {
OutlierRejection(double cut):_cut(cut){};
bool operator()(Event *d){
if(d->type()==typeTowerConstraint) return true;
return (d->chi2()/d->weight())<_cut;
}
double _cut;
};
unsigned int Kalibri::Funct::NDim() const
{
return k_->par_->numberOfParameters();
}
// -----------------------------------------------------------------
class ComputeThread {
private:
int npar_;
double chi2_;
double * td1_;
double * td2_;
double * td3_;
double * td4_;
Parameters *parorig_, *mypar_;
const double *epsilon_;
std::vector<Event*> data_;
bool data_changed_;
struct calc_chi2_on
{
private:
ComputeThread *parent_;
public:
calc_chi2_on(ComputeThread *parent) : parent_(parent) {}
void operator()()
{
{
//boost::mutex::scoped_lock lock(io_mutex);
//std::cout << "start Thread for " << parent_ << " "
// << parent_->data_changed_ << " " << parent_->mypar_->parameters() << std::endl;
}
for(int param = 0 ; param < parent_->npar_ ; ++param) {
parent_->td1_[param]= 0.0;
parent_->td2_[param]= 0.0;
parent_->td3_[param]= 0.0;
parent_->td4_[param]= 0.0;
parent_->mypar_->parameters()[param] = parent_->parorig_->parameters()[param];
}
if(parent_->data_changed_) {
for (DataIter it=parent_->data_.begin() ; it!= parent_->data_.end() ; ++it) {
(*it)->setParameters(parent_->mypar_);
}
parent_->data_changed_ = false;
}
parent_->chi2_ = 0;
for (DataIter it=parent_->data_.begin() ; it != parent_->data_.end() ; ++it) {
//boost::mutex::scoped_lock lock(io_mutex);
parent_->chi2_ += (*it)->chi2_fast(parent_->td1_, parent_->td2_, parent_->td3_, parent_->td4_, parent_->epsilon_);
}
}
};
boost::thread *thread_;
friend class calc_chi2_on;
public:
ComputeThread(int npar,Parameters *par, const double *epsilon)
: npar_(npar), td1_(new double[npar]), td2_(new double[npar]), td3_(new double[npar]), td4_(new double[npar]), parorig_(par),
mypar_(par->clone()), epsilon_(epsilon), data_changed_(false) {
//std::cout << "threads par array:" << mypar << '\n';
}
~ComputeThread() {
clearData();
delete [] td1_;
delete [] td2_;
delete [] td3_;
delete [] td4_;
Parameters::removeClone(mypar_);
}
void addData(Event* d) {
//d->ChangeParAddress(parorig, mypar);
data_changed_ = true;
data_.push_back(d);
}
void clearData() {
for (DataIter it= data_.begin() ; it!= data_.end() ; ++it) {
(*it)->setParameters(parorig_);
}
data_.clear();
}
void start() { thread_ = new boost::thread(calc_chi2_on(this)); }
bool isDone() { thread_->join(); delete thread_; return true;}
void syncParameters() {
for (int param = 0 ; param < npar_ ; ++param) mypar_->parameters()[param] = parorig_->parameters()[param];
}
double chi2() const { return chi2_;}
double tempDeriv1(int i) const { return td1_[i];}
double tempDeriv2(int i) const { return td2_[i];}
double tempDeriv3(int i) const { return td3_[i];}
double tempDeriv4(int i) const { return td4_[i];}
};
double Kalibri::eval(const double* x, double *f1, double *f2)
{
double fsum = 0.0;
const int npar = par_->numberOfParameters();
for(int param=0; param< npar ; ++param) {
temp_derivative1_[param]=0.0;
temp_derivative2_[param]=0.0;
temp_derivative3_[param]=0.0;
temp_derivative4_[param]=0.0;
par_->parameters()[param] = x[param];
}
if(f1) {
//computed step sizes for derivative calculation
if(printParNDeriv_) std::cout << "new par:\n";
for(int param = 0 ; param < npar ; ++param) {
if(printParNDeriv_) {
std::cout << std::setw(5) << param;
std::cout << std::setw(15) << par_->parameters()[param];
}
epsilon_[param] = derivStep_ * std::abs(par_->parameters()[param]);
if( epsilon_[param] <= derivStep_ ) epsilon_[param] = derivStep_;
volatile double temp = par_->parameters()[param] + epsilon_[param];
//volatile double temp2 = k->par_->parameters()[param] + k->epsilon_[param];
epsilon_[param] = temp - par_->parameters()[param];
}
if(printParNDeriv_) std::cout << std::endl;
} else {
for(int param = 0 ; param < npar ; ++param) {
epsilon_[param] = 0;
}
}
//use zero step for fixed pars
for( std::vector<int>::const_iterator iter = fixedJetPars_.begin();
iter != fixedJetPars_.end() ; ++ iter) {
epsilon_[*iter] = 0;
}
for( std::vector<int>::const_iterator iter = fixedGlobalJetPars_.begin();
iter != fixedGlobalJetPars_.end() ; ++ iter) {
epsilon_[*iter] = 0;
}
for (int ithreads=0; ithreads < nThreads_; ++ithreads) threads_[ithreads]->start();
for (int ithreads=0; ithreads < nThreads_; ++ithreads){
if(threads_[ithreads]->isDone()) {
fsum += threads_[ithreads]->chi2();
if(f1) {
for (int param=0 ; param < npar ; ++param) {
assert(threads_[ithreads]->tempDeriv1(param) == threads_[ithreads]->tempDeriv1(param));
temp_derivative1_[param] += threads_[ithreads]->tempDeriv1(param);
temp_derivative2_[param] += threads_[ithreads]->tempDeriv2(param);
temp_derivative3_[param] += threads_[ithreads]->tempDeriv3(param);
temp_derivative4_[param] += threads_[ithreads]->tempDeriv4(param);
}
}
}
}
/* might not be necessary????
for( std::vector<int>::const_iterator iter = k->fixedGlobalJetPars_.begin();
iter != k->fixedGlobalJetPars_.end() ; ++ iter) {
temp_derivative1_[*iter] = 0;
temp_derivative2_[*iter] = 0;
temp_derivative3_[*iter] = 0;
temp_derivative4_[*iter] = 0;
}
*/
fsum *= 0.5;//lvmini uses log likelihood not chi2
if(f1) {
//fast derivative calculation:
for( int param = 0 ; param < npar ; ++param ) {
//std::cout << "hier:" << step << " " << k->epsilon_[param] << " "
// << k->temp_derivative1_[param] << '\n';
if(epsilon_[param] > 0) {
if(temp_derivative3_[param]) {
//f'(x) \approx \frac{-f(x+2 h)+8 f(x+h)-8 f(x-h)+f(x-2h)}{12 h}
f1[param] = 0.5*(8*temp_derivative1_[param]-
temp_derivative3_[param])/(12 * epsilon_[param]);
} else {
f1[param] = 0.5 * temp_derivative1_[param]/(2.0*epsilon_[param]);
}
if(f2) {
if(temp_derivative4_[param]) {
f2[param] = 0.5*(16*temp_derivative2_[param]-temp_derivative4_[param])/(12*epsilon_[param]*epsilon_[param]);
} else {
f2[param] = 0.5 * temp_derivative2_[param]/(epsilon_[param]*epsilon_[param]);
}
}
} else {
f1[param] = 0;
if(f2) f2[param] = 0;
}
if(f1[param] != f1[param]) {
std::cout << "bad derivative: par = " << param << " td = " << temp_derivative1_[param] << " epsilon = " << epsilon_[param] << '\n';
}
assert(f1[param] == f1[param]);
}
//print derivatives:
if(printParNDeriv_) {
std::cout << std::setw(5) << "\npar";
std::cout << std::setw(15) << "p";
std::cout << std::setw(15) << "dp/dx";
std::cout << std::setw(15) << "d^2p/dx^2\n";
for( int param = 0 ; param < npar ; ++param ) {
std::cout << std::setw(5) << param;
std::cout << std::setw(15) << par_->parameters()[param];
std::cout << std::setw(15) << f1[param]
<< std::setw(15) << (f2 ? f2[param] : 0) << std::endl;
}
std::cout << "fsum:" << fsum << std::endl;
}
}
assert( fsum > 0 );
return fsum;
}
//--------------------------------------------------------------------------------------------
void Kalibri::run()
{
if (fitMethod_!=3){
time_t start = time(0);
std::cout << "****Processing events:****\n";
std::vector<EventProcessor*> processors;
processors.push_back(new DiJetEventCuts(configFile_,par_));
processors.push_back(new EventWeightProcessor(configFile_,par_));
processors.push_back(new PUTruthReweighting(configFile_,par_));
processors.push_back(new DiJetEventWeighting(configFile_,par_));
processors.push_back(new PUEventWeightProcessor(configFile_,par_));
processors.push_back(new EventBinning(configFile_,par_));
processors.push_back(new DiJetEventBinning(configFile_,par_));
for(std::vector<EventProcessor*>::iterator i = processors.begin() ; i != processors.end() ; ++i) {
ConfigFile config( configFile_.c_str() );
//test std:: cout << "create TwoJetsPtBalanceEvent " +(*i)->name()+" plots" << std::endl;
if( config.read<bool>("create TwoJetsPtBalanceEvent " +(*i)->name()+" plots",0) ){
std:: cout << "creating TwoJetsPtBalanceEvent " +(*i)->name()+" plots before "+(*i)->name()+" is executed" << std::endl;
std::vector<std::vector<Event*>* > samples;
samples.push_back(&data_);
samples.push_back(&control_[0]);
samples.push_back(&control_[1]);
(*i)->produceControlPlots(samples);
}
(*i)->process(data_,control_[0],control_[1]);
}
if(! data_.size()) {
std::cout << "Warning: No events to perform the fit!\n";
return;
}
if((fitMethod_==1) || (fitMethod_==0) || (fitMethod_==-1) || (fitMethod_==-2)) {
int npar = par_->numberOfParameters();
epsilon_ = new double[npar];
temp_derivative1_ = new double[npar];
temp_derivative2_ = new double[npar];
temp_derivative3_ = new double[npar];
temp_derivative4_ = new double[npar];
cout << "****Fitting " << npar << " parameters:****\n";
par_->print();
if(fitMethod_==1)
cout << " with LVMINI.\n";
else if(fitMethod_==-1)
cout << " with lbfgs.\n";
else if(fitMethod_==0)
cout << " stressTest.\n";
else if(fitMethod_==-2)
cout << " with ROOT::Minimizer using " << minName_ << " and "
<< algoName_ << ".\n";
else
cout << "\n";
cout << "Using " << data_.size() << " total events and ";
cout << nThreads_ << " threads.\n";
// Fixed pars
if( fixedJetPars_.size() > 0 ) cout << "Fixed jet parameters:\n";
for(unsigned int i = 0; i < fixedJetPars_.size(); i++) {
int idx = fixedJetPars_.at(i);
cout << " " << idx+1 << ": " << par_->parameters()[idx] << endl;
}
if( fixedGlobalJetPars_.size() > 0 ) cout << "Fixed global jet parameters:\n";
for(unsigned int i = 0; i < fixedGlobalJetPars_.size(); i++) {
int idx = fixedGlobalJetPars_.at(i);
cout << " " << idx+1 << ": " << par_->parameters()[idx] << endl;
}
threads_ = new ComputeThread*[nThreads_];
for (int ithreads=0; ithreads<nThreads_; ++ithreads){
threads_[ithreads] = new ComputeThread(npar, par_,epsilon_);
}
if(fitMethod_==1) {
run_Lvmini();
time_t end = time(0);
cout << "Done, fitted " << par_->numberOfParameters() << " parameters in " << difftime(end,start) << " sec." << endl;
} else if(fitMethod_==0) {
stressTest();
time_t end = time(0);
cout << "Done, fitted " << par_->numberOfParameters() << " parameters in " << difftime(end,start) << " sec." << endl;
} else if(fitMethod_==-1) {
run_lbfgs();
time_t end = time(0);
cout << "Done, fitted " << par_->numberOfParameters() << " parameters in " << difftime(end,start) << " sec." << endl;
} else if(fitMethod_==-2) {
run_Minimizer();
time_t end = time(0);
cout << "Done, fitted " << par_->numberOfParameters() << " parameters in " << difftime(end,start) << " sec." << endl;
}
for (int ithreads=0; ithreads<nThreads_; ++ithreads){
delete threads_[ithreads];
}
delete [] threads_;
delete [] epsilon_;
delete [] temp_derivative1_;
delete [] temp_derivative2_;
delete [] temp_derivative3_;
delete [] temp_derivative4_;
}
else {
if( par_->needsUpdate() ) par_->update();
}
for(std::vector<EventProcessor*>::iterator i = processors.begin() ; i != processors.end() ; ++i) {
(*i)->revert(data_,control_[0],control_[1]);
delete *i;
}
}
}
// code for lbfgs
lbfgsfloatval_t Kalibri::lbfgs_evaluate(void *instance,
const lbfgsfloatval_t *x,
lbfgsfloatval_t *g,
const int npar,
const lbfgsfloatval_t step)
{
Kalibri *k = static_cast<Kalibri*>(instance);
return k->eval(x,g);
}
int Kalibri::lbfgs_progress(void *instance,
const lbfgsfloatval_t *x,
const lbfgsfloatval_t *g,
const lbfgsfloatval_t fx,
const lbfgsfloatval_t xnorm,
const lbfgsfloatval_t gnorm,
const lbfgsfloatval_t step,
int n, int k, int ls)
{
std::cout << std::setw(5) << k << std::setw(15) << std::setprecision(10)
<< fx << std::setw(15) << xnorm << std::setw(15) << gnorm
<< std::setw(20) << step << '\n';
std::cout << std::setprecision(5);
return 0;
}
void Kalibri::stressTest()
{
const int N = 2;
double chi2 = 0, tempchi2 = 0;
const int npar = par_->numberOfParameters();
double *f1 = new double[npar];
double *f2 = new double[npar];
double *tempf1 = new double[npar];
double *tempf2 = new double[npar];
double *t1 = new double[npar];
double *tempt1 = new double[npar];
//second parameter object
Parameters* par2=par_->clone();
//set epsilons
for(int i = 0 ; i < npar ; ++i) {
epsilon_[i] = derivStep_ * std::abs(par_->parameters()[i]);
if( epsilon_[i] <= derivStep_) epsilon_[i] = derivStep_;
volatile double temp = par_->parameters()[i] + epsilon_[i];
//volatile double temp2 = k->par_->parameters()[i] + k->epsilon_[i];
epsilon_[i] = temp - par_->parameters()[i];
par2->parameters()[i] = par_->parameters()[i];
};
for( std::vector<int>::const_iterator iter = fixedJetPars_.begin();
iter != fixedJetPars_.end() ; ++ iter) {
epsilon_[*iter] = 0;
}
for( std::vector<int>::const_iterator iter = fixedGlobalJetPars_.begin();
iter != fixedGlobalJetPars_.end() ; ++ iter) {
epsilon_[*iter] = 0;
}
for (DataIter it=data_.begin() ; it != data_.end() ; ++it) {
(*it)->setParameters(par_);
}
// no threads
for(int i = 0 ; i < 2*N ; ++i) {
if(i == N/2) {
std::cout << "changing parameter object:\n";
for (DataIter it=data_.begin() ; it != data_.end() ; ++it) {
(*it)->setParameters(par2);
}
}
for(int j = 0 ; j < npar ; ++j) {
temp_derivative1_[j]=0.0;
temp_derivative2_[j]=0.0;
temp_derivative3_[j]=0.0;
temp_derivative4_[j]=0.0;
}
tempchi2 = 0;
for (DataIter it=data_.begin() ; it != data_.end() ; ++it) {
tempchi2 += (*it)->chi2_fast(temp_derivative1_, temp_derivative2_, temp_derivative3_, temp_derivative4_, epsilon_);
}
tempchi2 *= 0.5;
for(int j = 0 ; j < npar ; ++j) {
tempt1[j] = temp_derivative1_[j];
if(epsilon_[j] == 0) {
tempf1[j] = 0;
tempf2[j] = 0;
continue;
}
if( temp_derivative3_[j] ) {
tempf1[j] = 0.5*(8*temp_derivative1_[j]-temp_derivative3_[j])/(12*epsilon_[j]);
tempf2[j] = 0.5*(16*temp_derivative2_[j]-temp_derivative4_[j])/(12*epsilon_[j]*epsilon_[j]);
} else {
tempf1[j] = 0.5 * temp_derivative1_[j]/(2.0*epsilon_[j]);
tempf2[j] = 0.5 * temp_derivative2_[j]/(epsilon_[j]*epsilon_[j]);
}
}
if(i == 0) {
chi2 = tempchi2;
for(int j = 0 ; j < npar ; ++j) {
f1[j] = tempf1[j];
f2[j] = tempf2[j];
t1[j] = tempt1[j];
}
}
//compare results
std::cout << " Trial: " << std::setw(4) << i << " chi2 rel. diff:" << std::setw(15) << (chi2 - tempchi2)/chi2 << '\n';
for(int j = 0 ; j < npar ; ++j) {
std::cout << " " << std::setw(4) << j << " f1 rel. diff:" << std::setw(15) << (f1[j] ? (f1[j] - tempf1[j])/f1[j] : tempf1[j])
<< " f2 rel. diff:" << std::setw(15) << (f2[j] ? (f2[j] - tempf2[j])/f2[j] : tempf2[j])
<< " t1 rel. diff:" << std::setw(15) << (t1[j] ? (t1[j] - tempt1[j])/t1[j] : tempt1[j])
<< '\n';
}
std::cout << '\n';
}
//with threads
//nThreads_ = 2;
std::cout << "Now with " << nThreads_ << " threads\n";
int n = 0;
const double h = derivStep_;
for(DataIter it = data_.begin() ; it < data_.end() ; ++it) {
threads_[n]->addData(*it);
n++;
if(n == nThreads_) n = 0;
}
for(int i = 0 ; i < 3*N ; ++i) {
if(i == N) {
derivStep_ = h/2;
std::cout << "changing derivStep from " << derivStep_ << " to " << h << '\n';
}
if(i == 2*N) {
derivStep_ = h * 2;
std::cout << "changing derivStep from " << derivStep_ << " to " << h << '\n';
}
tempchi2 = eval(par_->parameters(),tempf1,tempf2);
//compare results
std::cout << " Trial: " << std::setw(4) << i << " chi2 rel. diff:" << std::setw(15) << (chi2 - tempchi2)/chi2 << '\n';
for(int j = 0 ; j < npar ; ++j) {
std::cout << " " << std::setw(4) << j << " f1 rel. diff:" << std::setw(15) << (f1[j] ? (f1[j] - tempf1[j])/f1[j] : tempf1[j])
<< " f2 rel. diff:" << std::setw(15) << (f2[j] ? (f2[j] - tempf2[j])/f2[j] : tempf2[j])
<< " t1 rel. diff:" << std::setw(15) << (t1[j] ? (t1[j] - tempt1[j])/t1[j] : tempt1[j])
<< '\n';
}
std::cout << '\n';
}
derivStep_ = h;
Parameters::removeClone(par2);
delete [] f1;
delete [] f2;
delete [] tempf1;
delete [] tempf2;
}
void Kalibri::run_Minimizer()
{
// original from http://root.cern.ch/root/html/tutorials/fit/NumericalMinimization.C.html
// by L. Moneta Dec 2010
//
// create minimizer giving a name and a name (optionally) for the specific
// algorithm
// possible choices are:
// minName algoName
// Minuit /Minuit2 Migrad, Simplex,Combined,Scan (default is Migrad)
// Minuit2 Fumili2
// Fumili
// GSLMultiMin ConjugateFR, ConjugatePR, BFGS,
// BFGS2, SteepestDescent
// GSLMultiFit
// GSLSimAn
// Genetic
ROOT::Math::Minimizer* min =
ROOT::Math::Factory::CreateMinimizer(minName_, algoName_);
if(! min) {
std::cerr << "ERROR: failed to create minimizer " << minName_ << ":" << algoName_ << '\n';
return;
}
// set tolerance , etc...
min->SetMaxFunctionCalls(100* nIter_); // for Minuit/Minuit2
min->SetMaxIterations(nIter_); // for GSL
min->SetTolerance(eps_);
min->SetPrintLevel(3);
int npar = par_->numberOfParameters();
for( unsigned int loop = 0; loop < residualScalingScheme_.size() ; ++loop ) {
cout<<"Updating Di-Jet Errors"<<endl;
for(DataIter it = data_.begin() ; it < data_.end() ; ++it) {
(*it)->updateError();
}
if( par_->needsUpdate() ) par_->update();
// Setting function to scale residuals in chi2 calculation
cout << loop+1 << flush;
if( loop+1 == 1 ) cout << "st" << flush;
else if( loop+1 == 2 ) cout << "nd" << flush;
else if( loop+1 == 3 ) cout << "rd" << flush;
else cout << "th" << flush;
cout << " of " << residualScalingScheme_.size() <<" iteration(s)" << flush;
if( mode_ == 0 ) {
if( residualScalingScheme_.at(loop) == 0 ) {
Event::scaleResidual = &Event::scaleNone;
cout << ": no scaling of residuals." << endl;
cout << "Rejecting outliers " << flush;
DataIter beg = partition(data_.begin(), data_.end(), OutlierRejection(outlierChi2Cut_));
for(DataIter i = beg ; i != data_.end() ; ++i) {
delete *i;
}
data_.erase(beg,data_.end());
cout << "and using " << data_.size() << " events." << endl;
}
else if( residualScalingScheme_.at(loop) == 1 ) {
Event::scaleResidual = &Event::scaleCauchy;
cout << ": scaling of residuals with Cauchy-Function." << endl;
}
else if( residualScalingScheme_.at(loop) == 2 ) {
Event::scaleResidual = &Event::scaleHuber;
cout << ": scaling of residuals with Huber-Function." << endl;
}
else if( residualScalingScheme_.at(loop) == 3 ) {
Event::scaleResidual = &Event::scaleTukey;
cout << ": scaling of residuals a la Tukey." << endl;
}
else {
cerr << "ERROR: " << residualScalingScheme_.at(loop) << " is not a valid scheme for resdiual scaling! Breaking iteration!" << endl;
break;
}
} else {
std::cout << std::endl;
}
//ROOT::Math::Functor f(this,&Kalibri::eval,npar);
/* Initialize the parameters*/
Funct f(this);
min->SetFunction(f);
// Set the free variables to be minimized!
for(int i = 0 ; i < npar ; ++i) {
TString spar("par");
spar += i;
min->SetVariable(i,spar.Data(),par_->parameters()[i], 0.1);
}
for( std::vector<int>::const_iterator iter = fixedJetPars_.begin();
iter != fixedJetPars_.end() ; ++ iter) {
TString spar("par");
spar += *iter;
min->SetFixedVariable(*iter,spar.Data(),par_->parameters()[*iter]);
}
for( std::vector<int>::const_iterator iter = fixedGlobalJetPars_.begin();
iter != fixedGlobalJetPars_.end() ; ++ iter) {
TString spar("par");
spar += *iter;
min->SetFixedVariable(*iter,spar.Data(),par_->parameters()[*iter]);
}
int n = 0;
for(DataIter it = data_.begin() ; it < data_.end() ; ++it) {
threads_[n]->addData(*it);
n++;
if(n == nThreads_) n = 0;
}
min->Minimize();
const double *xs = min->X();
for(int i = 0 ; i < npar ; ++i) {
par_->parameters()[i] = xs[i];
if((i > 1) && (i%3 == 0)) std::cout << '\n';
std::cout << std::setw(10) << i << std::setw(15) << xs[i];
}
std::cout << '\n';
for (int ithreads=0; ithreads<nThreads_; ++ithreads){
threads_[ithreads]->clearData();
}
}
}
void Kalibri::run_lbfgs()
{
//please see http://www.chokkan.org/software/liblbfgs/
int npar = par_->numberOfParameters();
lbfgsfloatval_t fx;
lbfgsfloatval_t *x = lbfgs_malloc(npar);
lbfgs_parameter_t param;
if (x == NULL) {
std::cerr << "ERROR: Failed to allocate a memory block for variables.\n";
return;
}
/*
Start the L-BFGS optimization; this will invoke the callback functions
evaluate() and progress() when necessary.
*/
for( unsigned int loop = 0; loop < residualScalingScheme_.size() ; ++loop ) {
cout<<"Updating Di-Jet Errors"<<endl;
for(DataIter it = data_.begin() ; it < data_.end() ; ++it) {
(*it)->updateError();
}
if( par_->needsUpdate() ) par_->update();
// Setting function to scale residuals in chi2 calculation
cout << loop+1 << flush;
if( loop+1 == 1 ) cout << "st" << flush;
else if( loop+1 == 2 ) cout << "nd" << flush;
else if( loop+1 == 3 ) cout << "rd" << flush;
else cout << "th" << flush;
cout << " of " << residualScalingScheme_.size() <<" iteration(s)" << flush;
if( mode_ == 0 ) {
if( residualScalingScheme_.at(loop) == 0 ) {
Event::scaleResidual = &Event::scaleNone;
cout << ": no scaling of residuals." << endl;
cout << "Rejecting outliers " << flush;
DataIter beg = partition(data_.begin(), data_.end(), OutlierRejection(outlierChi2Cut_));
for(DataIter i = beg ; i != data_.end() ; ++i) {
delete *i;
}
data_.erase(beg,data_.end());
cout << "and using " << data_.size() << " events." << endl;
}
else if( residualScalingScheme_.at(loop) == 1 ) {
Event::scaleResidual = &Event::scaleCauchy;
cout << ": scaling of residuals with Cauchy-Function." << endl;
}
else if( residualScalingScheme_.at(loop) == 2 ) {
Event::scaleResidual = &Event::scaleHuber;
cout << ": scaling of residuals with Huber-Function." << endl;
}
else if( residualScalingScheme_.at(loop) == 3 ) {
Event::scaleResidual = &Event::scaleTukey;
cout << ": scaling of residuals a la Tukey." << endl;
}
else {
cerr << "ERROR: " << residualScalingScheme_.at(loop) << " is not a valid scheme for resdiual scaling! Breaking iteration!" << endl;
break;
}
} else {
std::cout << std::endl;
}
param.linesearch = LBFGS_LINESEARCH_BACKTRACKING_STRONG_WOLFE;
param.max_iterations = nIter_;//The maximum number of iterations.
param.m = mvec_;//The number of corrections to approximate the inverse hessian matrix.
param.epsilon = eps_;//Epsilon for convergence test.
param.wolfe = wlf1_;//A coefficient for the Wolfe condition.
param.max_linesearch = 7;//The maximum number of trials for the line search.
/* Initialize the parameters for the L-BFGS optimization. */
for(int i = 0 ; i < npar ; ++i) {
x[i] = par_->parameters()[i];
}
lbfgs_parameter_init(¶m);
int n = 0;
for(DataIter it = data_.begin() ; it < data_.end() ; ++it) {
threads_[n]->addData(*it);
n++;
if(n == nThreads_) n = 0;
}
std::cout << std::setw(5) << "i" << std::setw(15) << "fx"
<< std::setw(15) << "xnorm" << std::setw(15) << "gnorm"
<< std::setw(20) << "step" << '\n';
int ret = lbfgs(npar, x, &fx, lbfgs_evaluate, lbfgs_progress, this, ¶m);
/* Report the result. */
std::cout << "L-BFGS optimization terminated with status code = " << ret
<< " and fx = " << fx << '\n';
std::cout << "paramters:\n";
for(int i = 0 ; i < npar ; ++i) {
par_->parameters()[i] = x[i];
if((i > 1) && (i%3 == 0)) std::cout << '\n';
std::cout << std::setw(10) << i << std::setw(15) << x[i];
}
std::cout << '\n';
for (int ithreads=0; ithreads<nThreads_; ++ithreads){
threads_[ithreads]->clearData();
}
}
lbfgs_free(x);
}
// -----------------------------------------------------------------
void Kalibri::run_Lvmini()
{
int naux = 3000000, iret=0;
int npar = par_->numberOfParameters();
int mvec = mvec_;
if( calcCov_ ) mvec = -mvec_;
naux = lvmdim_(npar,mvec);
cout<<"array of size "<<naux<<" needed."<<endl;
double* aux = new double[naux], fsum = 0;
//lvmeps_(data_.size()*eps_,wlf1_,wlf2_);
lvmeps_(eps_,wlf1_,wlf2_);
//Set errors per default to 0 //@@ doesn't seem to work...
int error_index=2;
error_index = lvmind_(error_index);
par_->fillErrors(aux+error_index);
for( unsigned int loop = 0; loop < residualScalingScheme_.size() ; ++loop ) {
cout<<"Updating Di-Jet Errors"<<endl;
for(DataIter it = data_.begin() ; it < data_.end() ; ++it) {
(*it)->updateError();
}
if( par_->needsUpdate() ) par_->update();
// Setting function to scale residuals in chi2 calculation
cout << loop+1 << flush;
if( loop+1 == 1 ) cout << "st" << flush;
else if( loop+1 == 2 ) cout << "nd" << flush;
else if( loop+1 == 3 ) cout << "rd" << flush;
else cout << "th" << flush;
cout << " of " << residualScalingScheme_.size() <<" iteration(s)" << flush;
if( mode_ == 0 ) {
if( residualScalingScheme_.at(loop) == 0 ) {
Event::scaleResidual = &Event::scaleNone;
cout << ": no scaling of residuals." << endl;
cout << "Rejecting outliers " << flush;
DataIter beg = partition(data_.begin(), data_.end(), OutlierRejection(outlierChi2Cut_));
for(DataIter i = beg ; i != data_.end() ; ++i) {
delete *i;
}
data_.erase(beg,data_.end());
cout << "and using " << data_.size() << " events." << endl;
}
else if( residualScalingScheme_.at(loop) == 1 ) {
Event::scaleResidual = &Event::scaleCauchy;
cout << ": scaling of residuals with Cauchy-Function." << endl;
}
else if( residualScalingScheme_.at(loop) == 2 ) {
Event::scaleResidual = &Event::scaleHuber;
cout << ": scaling of residuals with Huber-Function." << endl;
}
else if( residualScalingScheme_.at(loop) == 3 ) {
Event::scaleResidual = &Event::scaleTukey;
cout << ": scaling of residuals a la Tukey." << endl;
}
else {
cerr << "ERROR: " << residualScalingScheme_.at(loop) << " is not a valid scheme for resdiual scaling! Breaking iteration!" << endl;
break;
}
} else {
std::cout << std::endl;
}
if(lvmdim_(npar,mvec) > naux)
cout<<"Aux field too small. "<<lvmdim_(npar,mvec)<<" enntires needed."<<endl;
//initialization
int nparm = -npar; //Show output
lvmini_(nparm, mvec, nIter_, aux);
int n = 0;
for(DataIter it = data_.begin() ; it < data_.end() ; ++it) {
threads_[n]->addData(*it);
n++;
if(n == nThreads_) n = 0;
}
do {
fsum = eval(par_->parameters(),aux,aux+npar);
lvmfun_(par_->parameters(),fsum,iret,aux);
//lvmout_(npar,mvec_,aux);
} while (iret<0);
for (int ithreads=0; ithreads<nThreads_; ++ithreads){
threads_[ithreads]->clearData();
}
int par_index = 1;
par_index = lvmind_(par_index);
par_->setParameters(aux + par_index);
}
//Copy Parameter errors from aux array to the TParameter::e array
if( !calcCov_ ) {
error_index=2;
error_index = lvmind_(error_index);
par_->setErrors(aux+error_index);
} else {
// Retrieve parameter errors
error_index = 3;
error_index = lvmind_(error_index);
par_->setErrors(aux+error_index);
// Retrieve global parameter correlation coefficients
error_index = 4;
error_index = lvmind_(error_index);
bool nanOccured = false;
for(int i = 0; i < par_->numberOfParameters(); i++) {
if( aux[error_index+i] != aux[error_index+i] ) { // Check for NAN
if( !nanOccured ) {
nanOccured = true;
std::cout << "The following global correlation coefficients are NAN and set to 0:\n";
}
std::cout << i << std::endl;
aux[error_index+i] = 0.;
}
}
par_->setGlobalCorrCoeff(aux+error_index);
// Retrieve parameter covariances
error_index = 5;
error_index = lvmind_(error_index);
// Set cov = 0 for fixed parameters
nanOccured = false;
for(int i = 0; i < par_->numberOfCovCoeffs(); i++) {
if( aux[error_index+i] != aux[error_index+i] ) { // Check for NAN
if( !nanOccured ) {
nanOccured = true;
std::cout << "The following covariance elements are NAN and set to 0:\n";
}
std::cout << i << std::endl;
aux[error_index+i] = 0.;
}
}
par_->setCovCoeff(aux+error_index);
}
delete [] aux;
}
//--------------------------------------------------------------------------------------------
void Kalibri::done()
{
std::cout << "****Kalibri::done()****\n";
if( par_->needsUpdate() ) par_->update();
ConfigFile config( configFile_.c_str() );
bool txt=false;
bool tex=false;
std::string fileName(getOutputFile());
// write calibration to txt output file if ending is txt
if( fileName.find(".txt")!=std::string::npos ){
if( fileName.substr(fileName.find(".txt")).compare(".txt")==0 ){
par_->writeCalibrationTxt( fileName.c_str() );
txt=true; // file has a real .txt ending
}
}
// write calibration to tex output file if ending is tex
if( fileName.find(".tex")!=std::string::npos ){
if( fileName.substr(fileName.find(".tex")).compare(".tex")==0 ){
par_->writeCalibrationTex( fileName.c_str(), config );
tex=true; // file has a real .txt ending
}
}
// write calibration to txt and tex output file if w/o ending
if( !txt && !tex ){
par_->writeCalibrationTxt( (fileName+".txt").c_str() );
par_->writeCalibrationTex( (fileName+".tex").c_str(), config );
}
// Make control plots
if( config.read<bool>("create plots",0) ) {
std::cout << "****Plotting:****\n";
if( mode_ == 0 ) { // Control plots for calibration
std::vector<std::vector<Event*>* > samples;
samples.push_back(&data_);
samples.push_back(&control_[0]);
samples.push_back(&control_[1]);
ControlPlots * plots = new ControlPlots(&config,samples);
plots->makePlots();
delete plots;
} else if( mode_ == 1 ) { // Control plots for jetsmearing
ControlPlotsResolution * plotsjs = new ControlPlotsResolution(configFile_,&data_,par_);
plotsjs->makePlots();
delete plotsjs;
}
}
// Clean-up
cout << endl << "****Cleaning up..." << flush;
for(DataIter i = data_.begin() ; i != data_.end() ; ++i) {
delete *i;
}
data_.clear();
for(DataIter i = control_[0].begin() ; i != control_[0].end() ; ++i) {
delete *i;
}
control_[0].clear();
for(DataIter i = control_[1].begin() ; i != control_[1].end() ; ++i) {
delete *i;
}
control_[1].clear();
cout << "Done****" << endl;
}
//--------------------------------------------------------------------------------------------
void Kalibri::init()
{
ConfigFile config(configFile_.c_str() );
par_ = Parameters::createParameters(configFile_);
//--------------------------------------------------------------------------
//read config file
mode_ = config.read<int>("Mode",0);
fitMethod_ = config.read<int>("Fit method",1);
std::vector<std::string> strvec = bag_of_string(config.read<std::string>("Minimizer","Minuit2"));
minName_ = strvec.at(0);
if(strvec.size()>1) {
algoName_ = strvec[1];
}
nThreads_ = config.read<int>("Number of Threads",1);
// Residual scaling
const char* resScheme = ( config.read<string>("Residual Scaling Scheme","221").c_str() );
while( *resScheme != 0 )
{
int scheme = static_cast<int>(*resScheme - '0');
if( scheme < 0 || scheme > 3 )
{