source: trunk/MagicSoft/Mars/mjobs/MJOptimize.cc@ 7071

Last change on this file since 7071 was 7071, checked in by tbretz, 19 years ago
*** empty log message ***
File size: 29.1 KB
Line 
1/* ======================================================================== *\
2!
3! *
4! * This file is part of MARS, the MAGIC Analysis and Reconstruction
5! * Software. It is distributed to you in the hope that it can be a useful
6! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
7! * It is distributed WITHOUT ANY WARRANTY.
8! *
9! * Permission to use, copy, modify and distribute this software and its
10! * documentation for any purpose is hereby granted without fee,
11! * provided that the above copyright notice appear in all copies and
12! * that both that copyright notice and this permission notice appear
13! * in supporting documentation. It is provided "as is" without express
14! * or implied warranty.
15! *
16!
17!
18! Author(s): Thomas Bretz, 9/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
19!
20! Copyright: MAGIC Software Development, 2000-2004
21!
22!
23\* ======================================================================== */
24
25/////////////////////////////////////////////////////////////////////////////
26//
27// MJOptimize
28//
29// Class for otimizing the parameters of the supercuts
30//
31// Minimization Control
32// ====================
33//
34// To choose the minimization algorithm use:
35// void SetOptimizer(Optimizer_t o);
36//
37// Allowed options are:
38// enum Optimizer_t
39// {
40// kMigrad, // Minimize by the method of Migrad
41// kSimplex, // Minimize by the method of Simplex
42// kMinimize, // Migrad + Simplex (if Migrad fails)
43// kMinos, // Minos error determination
44// kImprove, // Local minimum search
45// kSeek, // Minimize by the method of Monte Carlo
46// kNone // Skip optimization
47// };
48//
49// For more details on the methods see TMinuit.
50//
51//
52// You can change the behaviour of the minimization using
53//
54// void SetNumMaxCalls(UInt_t num=0);
55// void SetTolerance(Float_t tol=0);
56//
57// While NumMaxCalls is the first, Tolerance the second arguement.
58// For more details start root and type
59//
60// gMinuit->mnhelp("command")
61//
62// while command can be
63// * MIGRAD
64// * SIMPLEX
65// * MINIMIZE
66// * MINOS
67// * IMPROVE
68// * SEEK
69//
70// The default (num==0 and tol==0) should always give you the
71// corresponding defaults used in Minuit.
72//
73//
74// FIXME: Implement changing cut in hadronness...
75// FIXME: Show MHSignificance on MStatusDisplay during filling...
76// FIXME: Choose step-size percentage as static data membewr
77// FIXME: Choose minimization method
78//
79/////////////////////////////////////////////////////////////////////////////
80#include "MJOptimize.h"
81
82#include <TMinuit.h>
83#include <TVirtualFitter.h>
84
85#include <TStopwatch.h>
86
87#include <TCanvas.h>
88
89#include <TGraph.h>
90#include <TMultiGraph.h>
91
92#include "MParList.h"
93#include "MTaskList.h"
94#include "MGeomCamCT1.h"
95#include "MFEventSelector.h"
96#include "MFDataMember.h"
97#include "MReadTree.h"
98#include "MHMatrix.h"
99#include "MEnergyEstimate.h"
100#include "MMatrixLoop.h"
101#include "MChisqEval.h"
102#include "MEvtLoop.h"
103#include "MDataElement.h"
104#include "MDataMember.h"
105#include "MLog.h"
106#include "MLogManip.h"
107#include "MParameters.h"
108#include "MFillH.h"
109#include "MF.h"
110#include "MFilterList.h"
111#include "../mfilter/MFMagicCuts.h"
112#include "MContinue.h"
113#include "MGeomCamMagic.h"
114#include "MHillasSrcCalc.h"
115#include "MHMatrix.h"
116#include "MMatrixLoop.h"
117#include "../mhflux/MHAlpha.h"
118#include "MStatusDisplay.h"
119#include "../mhflux/MHEnergyEst.h"
120#include "MDirIter.h"
121#include "MSequence.h"
122
123using namespace std;
124
125//------------------------------------------------------------------------
126//
127// fcn calculates the function to be minimized (using TMinuit::Migrad)
128//
129void MJOptimize::fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag)
130{
131 MJOptimize *optim = (MJOptimize*)gMinuit->GetObjectFit();
132
133 // WORKAROUND --- FOR WHAT?
134 if (gMinuit->fEpsi<1e-2)
135 {
136 *optim->fLog << warn << "WARNING - For unknown reasons: fEspi<1e-100... resetting to 0.01." << endl;
137 gMinuit->fEpsi = 0.01;
138 }
139
140 TMinuit *minuit = gMinuit;
141 f = optim->Fcn(TArrayD(TMath::Min(gMinuit->fMaxpar, optim->fParameters.GetSize()), par), minuit);
142 gMinuit = minuit;
143
144}
145
146Double_t MJOptimize::Fcn(const TArrayD &par, TMinuit *minuit)
147{
148 if (fEvtLoop->GetDisplay()!=fDisplay)
149 return 0;
150 /*
151 switch(iflag)
152 {
153 case 1: // first call
154 case 2: // calc derivative
155 break;
156 case 3:
157 // last call
158 MStatusDisplay *d = new MStatusDisplay;
159 fEvtLoop->SetDisplay(d);
160 break;
161 }
162 */
163 MParList *plist = fEvtLoop->GetParList();
164
165 MParameterD *eval = (MParameterD*)plist->FindObject("MinimizationValue", "MParameterD");
166 MParContainer *pars = (MParContainer*)plist->FindObject("MParameters", "MParContainer");
167
168 MRead *read = (MRead*)plist->FindObject("MTaskList")->FindObject("MRead");
169 if (read)
170 read->Rewind();
171
172 if (fDebug>=0)
173 {
174 *fLog << inf << "New Set: ";
175 for (Int_t i=0; i<fParameters.GetSize(); i++)
176 *fLog << par[i] << " ";
177 *fLog << endl;
178 }
179
180 pars->SetVariables(par);
181 eval->SetVal(0);
182
183 const Bool_t isnull = gLog.IsNullOutput();
184 if (fDebug<3)
185 gLog.SetNullOutput(kTRUE);
186
187 TStopwatch clock;
188 clock.Start();
189 fEvtLoop->Eventloop(fNumEvents, MEvtLoop::kNoStatistics);
190 clock.Stop();
191
192 if (fDebug<3)
193 gLog.SetNullOutput(isnull);
194
195 const Double_t f = eval->GetVal();
196
197 if (fDebug>=0)
198 *fLog << inf << "Result F=" << f << endl;
199
200 if (fDebug>=1 && minuit)
201 {
202 Double_t fmin, fedm, errdef;
203 Int_t n1, n2, istat;
204 minuit->mnstat(fmin, fedm, errdef, n1, n2, istat);
205 *fLog << inf << underline << "Minimization Status so far:" << endl;
206 *fLog << " Calls: " << minuit->fNfcn << " (max=" << gMinuit->fMaxIterations << ")" << endl;
207 *fLog << " Parameters: fixed=" << gMinuit->fNpfix << ", free=" << gMinuit->fNpar << endl;
208 *fLog << " Func min: " << fmin << " (Epsi=" << gMinuit->fEpsi << ", Apsi=" << gMinuit->fApsi << ")" << endl;
209 *fLog << " Found edm: " << fedm << endl;
210 *fLog << " ErrDef: " << errdef << endl;
211 *fLog << " Status: ";
212
213 switch (istat)
214 {
215 case 0: *fLog << "n/a" << endl; break;
216 case 1: *fLog << "approximation only, not accurate" << endl; break;
217 case 2: *fLog << "full matrix, but forced positive-definite" << endl; break;
218 case 3: *fLog << "full accurate covariance matrix" << endl; break;
219 default: *fLog << "undefined" << endl; break;
220 }
221 }
222
223 if (fDebug>=1)
224 {
225 clock.Print();
226 fEvtLoop->GetTaskList()->PrintStatistics();
227 }
228
229 return f;
230}
231
232MJOptimize::MJOptimize() : fDebug(-1), fNumEvents(0), fType(kSimplex), fNumMaxCalls(0), fTolerance(0), fTestTrain(0)
233{
234 fRules.SetOwner();
235 fFilter.SetOwner();
236
237 fNamesOn.SetOwner();
238 fNamesOff.SetOwner();
239}
240
241//------------------------------------------------------------------------
242//
243// Add seqeunces from list to reader
244//
245Bool_t MJOptimize::AddSequences(MRead &read, TList &list) const
246{
247 MDirIter files;
248
249 TIter Next(&list);
250 TObject *o=0;
251 while ((o=Next()))
252 {
253 MSequence seq(o->GetName());
254 if (!seq.IsValid())
255 return kFALSE;
256
257 seq.SetupDatRuns(files, o->GetTitle(), "I");
258 }
259
260 return read.AddFiles(files)>0;
261}
262
263//------------------------------------------------------------------------
264//
265// Add on-sequences:
266// - fname: sequence file name (with path)
267// - dir: directory were image files are stored
268//
269void MJOptimize::AddSequenceOn(const char *fname, const char *dir)
270{
271 fNamesOn.Add(new TNamed(fname, dir));
272}
273
274//------------------------------------------------------------------------
275//
276// Add off-sequences:
277// - fname: sequence file name (with path)
278// - dir: directory were image files are stored
279//
280void MJOptimize::AddSequenceOff(const char *fname, const char *dir)
281{
282 fNamesOff.Add(new TNamed(fname, dir));
283}
284
285//------------------------------------------------------------------------
286//
287// Empty list of on- and off-sequences
288//
289void MJOptimize::ResetSequences()
290{
291 fNamesOn.Delete();
292 fNamesOff.Delete();
293}
294
295//------------------------------------------------------------------------
296//
297// Add a parameter used in your filters (see AddFilter) The parameter
298// index is returned,
299//
300// Int_t idx = AddParameter("log10(MHillas.fSize)");
301//
302// The indices area starting with 0 always.
303//
304Int_t MJOptimize::AddParameter(const char *rule)
305{
306 fRules.Add(new TNamed(rule, ""));
307 return fRules.GetSize()-1;
308}
309
310//------------------------------------------------------------------------
311//
312// Add a filter which can be applied in the optimization (for deatils
313// see correspodning Run function) You can use the indices you got by
314// AddParameter, eg
315//
316// AddFilter("M[0] < 3.2");
317//
318// if used in optimization you can do
319//
320// AddFilter("M[0] < [0]");
321//
322// for more details, see SetParameter and FixParameter
323//
324void MJOptimize::AddFilter(const char *rule)
325{
326 fFilter.Add(new MF(rule));
327}
328
329//------------------------------------------------------------------------
330//
331// Add a cut which is used to fill the matrix, eg "MMcEvt.fOartId<1.5"
332// (The rule is applied, nit inverted: The matrix is filled with
333// the events fullfilling the condition)
334//
335void MJOptimize::AddPreCut(const char *rule)
336{
337 MFilter *f = new MF(rule);
338 f->SetBit(kCanDelete);
339 AddPreCut(f);
340}
341
342//------------------------------------------------------------------------
343//
344// Add a cut which is used to fill the matrix. If kCanDelete is set
345// MJOptimize takes the ownership.
346//
347void MJOptimize::AddPreCut(MFilter *f)
348{
349 fPreCuts.Add(f);
350}
351
352//------------------------------------------------------------------------
353//
354// Set the fParameters Array accoring to par.
355//
356void MJOptimize::SetParameters(const TArrayD &par)
357{
358 fParameters = par;
359}
360
361//------------------------------------------------------------------------
362//
363// Set the number of events processed by the eventloop. (Be carfull,
364// if you are doing on-off analysis and you only process the first
365// 1000 events which are on-events only the optimization may not work)
366//
367void MJOptimize::SetNumEvents(UInt_t n)
368{
369 fNumEvents=n;
370}
371
372//------------------------------------------------------------------------
373//
374// Set a debug level, which tells the optimization how much information
375// is displayed about and in the running eventloop.
376//
377void MJOptimize::SetDebug(UInt_t n)
378{
379 fDebug=n;
380}
381
382//------------------------------------------------------------------------
383//
384// Set a optimization algorithm to be used. For more information see
385// TMinuit.
386//
387// Available Algorithms are:
388// kMigrad, // Minimize by the method of Migrad
389// kSimplex, // Minimize by the method of Simplex
390// kSeek // Minimize by the method of Monte Carlo
391//
392void MJOptimize::SetOptimizer(Optimizer_t o)
393{
394 fType = o;
395}
396
397//------------------------------------------------------------------------
398//
399// If a status didplay is set, search for tab "Optimizer".
400// If not found, create it.
401// In the tab search for TMultiGraph "Parameters".
402// If not found create it.
403// If empty create TGraphs.
404// Check number of graphs vs. number of parameters.
405// return TList with graphs.
406//
407TList *MJOptimize::GetPlots() const
408{
409 if (!fDisplay)
410 return NULL;
411
412 TCanvas *c=fDisplay->GetCanvas("Optimizer");
413 if (!c)
414 c = &fDisplay->AddTab("Optimizer");
415
416 TMultiGraph *mg = dynamic_cast<TMultiGraph*>(c->FindObject("Parameters"));
417 if (!mg)
418 mg = new TMultiGraph("Parameters", "Parameters of optimization");
419
420 TList *l = mg->GetListOfGraphs();
421 if (!l)
422 {
423 const Int_t n = fParameters.GetSize();
424 for (int i=0; i<n+1; i++)
425 {
426 TGraph *g = new TGraph;
427 if (i==n)
428 g->SetLineColor(kBlue);
429 mg->Add(g, "");
430 AddPoint(mg->GetListOfGraphs(), i, i==n?1:fParameters[i]);
431 }
432 mg->SetBit(kCanDelete);
433 mg->Draw("al*");
434
435 l = mg->GetListOfGraphs();
436 }
437
438 return l->GetSize() == fParameters.GetSize()+1 ? l : NULL;
439}
440
441//------------------------------------------------------------------------
442//
443// Add a point with y=val as last point in idx-th Tgraph of list l.
444//
445void MJOptimize::AddPoint(TList *l, Int_t idx, Float_t val) const
446{
447 if (!l)
448 return;
449
450 TGraph *gr = (TGraph*)l->At(idx);
451 gr->SetPoint(gr->GetN(), gr->GetN(), val);
452}
453
454Int_t MJOptimize::Minuit(TMinuit &minuit, const char *cmd) const
455{
456 Int_t err;
457 Double_t tmp[2] = { fNumMaxCalls, fTolerance };
458 minuit.mnexcm(cmd, tmp, 2, err);
459
460 switch (err)
461 {
462 case 0:
463 *fLog << inf << GetDescriptor() << " TMinuit::mnexcm excuted normally." << endl;
464 break;
465 case 1:
466 *fLog << warn << GetDescriptor() << " TMinuit::mnexcm command is blank... ignored." << endl;
467 break;
468 case 2:
469 *fLog << warn << GetDescriptor() << " TMinuit::mnexcm command-line syntax error... ignored." << endl;
470 break;
471 case 3:
472 *fLog << warn << GetDescriptor() << " TMinuit::mnexcm unknown command... ignored." << endl;
473 break;
474 case 4:
475 *fLog << warn << GetDescriptor() << " TMinuit::mnexcm - Abnormal termination (eg Migrad not converged)" << endl;
476 break;
477 /*
478 case 5:
479 *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - Parameters requested." << endl;
480 break;
481 case 6:
482 *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - SET INPUT returned." << endl;
483 break;
484 case 7:
485 *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - SET TITLE returned." << endl;
486 break;
487 case 8:
488 *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - SET COVAR returned." << endl;
489 break;
490 case 9:
491 *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - reserved." << endl;
492 break;
493 case 10:
494 *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - END returned." << endl;
495 break;
496 case 11:
497 *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - EXIT or STOP returned." << endl;
498 break;
499 case 12:
500 *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - RETURN returned." << endl;
501 break;*/
502 }
503
504 return err;
505}
506
507Bool_t MJOptimize::Optimize(MEvtLoop &evtloop)
508{
509 if (fType==kNone)
510 return kTRUE;
511
512 gMinuit = new TMinuit(fParameters.GetSize());
513
514 gMinuit->SetFCN(fcn);
515 gMinuit->SetObjectFit(this);
516 gMinuit->SetPrintLevel(-1); // Don't print when DefineParameter
517
518 //
519 // Set starting values and step sizes for parameters
520 //
521 for (Int_t i=0; i<fParameters.GetSize(); i++)
522 {
523 TString name = "par[";
524 name += i;
525 name += "]";
526 Double_t vinit = fParameters[i];
527 Double_t step = fStep[i];
528
529 Double_t limlo = fLimLo[i];
530 Double_t limup = fLimUp[i];
531
532 Bool_t rc = gMinuit->DefineParameter(i, name, vinit, step, limlo, limup);
533 if (rc)
534 {
535 *fLog << err << dbginf << "Error in defining parameter #" << i << endl;
536 return kFALSE;
537 }
538
539 if (step==0)
540 gMinuit->FixParameter(i);
541 }
542
543 gMinuit->SetPrintLevel(1); // Switch on pritning again
544 gMinuit->mnprin(1,0); // Print all parameters
545
546 fEvtLoop = &evtloop;
547
548 TList *g=GetPlots();
549
550 // Now ready for minimization step:
551 TStopwatch clock;
552 clock.Start();
553 switch (fType)
554 {
555 case kSimplex:
556 Simplex(*gMinuit);
557 break;
558 case kMigrad:
559 Migrad(*gMinuit);
560 break;
561 case kMinimize:
562 Minimize(*gMinuit);
563 break;
564 case kMinos:
565 Minos(*gMinuit);
566 break;
567 case kImprove:
568 Improve(*gMinuit);
569 break;
570 case kSeek:
571 Seek(*gMinuit);
572 break;
573 case kNone: // Should never happen
574 return kFALSE;
575 }
576 clock.Stop();
577 clock.Print();
578
579 if (evtloop.GetDisplay()!=fDisplay)
580 {
581 *fLog << inf << "Optimization aborted by user." << endl;
582 fDisplay = 0;
583 return kFALSE;
584 }
585
586 *fLog << inf << "Resulting Chisq: " << gMinuit->fAmin << endl;
587
588 //
589 // Update values of fA, fB:
590 //
591 for (Int_t i=0; i<fParameters.GetSize(); i++)
592 {
593 Double_t x1, x2;
594 gMinuit->GetParameter(i,x1,x2);
595 fParameters[i] = x1;
596 cout << i << ": " << fParameters[i] << endl;
597
598 AddPoint(g, i, x1);
599 }
600 AddPoint(g, fParameters.GetSize(), gMinuit->fAmin);
601
602 delete gMinuit;
603
604 return kTRUE;
605}
606
607//------------------------------------------------------------------------
608//
609// Optimize allows to use the optimizing by an eventloop based on
610// some requirements.
611//
612// 1) The tasklist to be executed must have the name MTaskList and
613// be an entry in the parameterlist.
614//
615// 2) The reading task (MReadMarsFile, MMatrixLoop) must have the name
616// "MRead". If it derives from MRead Rewind() must be implemented,
617// otherwise it must start reading from scratch each time its
618// PreProcess is called.
619//
620// 3) The parameters to be optimized must be accessed through (currently)
621// a single parameter container (MParContainer) called MParameters.
622// The parameters are set through SetVariables.
623//
624// 4) The result of a single function call for minimization (eg. chisquare)
625// must be available after the eventloop in a container of type
626// MParameterD with the name "MinimizationResult".
627//
628// 5) The parameters to start with must have been set using
629// MJOptimize::SetParameter or MJOptimize::SetParameters and
630// MJOptimize::FixParameter
631//
632// The behaviour of the optimization can be changed using:
633// void SetNumEvents(UInt_t n);
634// void SetDebug(UInt_t n);
635// void SetOptimizer(Optimizer_t o);
636//
637// After optimization the resulting parameters are set and another eventloop
638// with a MStatusDisplay is set is called. The resulting parameters can be
639// accessed using: GetParameters()
640//
641// To be fixed:
642// - MStatusDisplay should show status while optimization is running
643// - write result into MStatusDisplay
644// - save result
645//
646Bool_t MJOptimize::Optimize(MParList &parlist)
647{
648 // Checks to make sure, that fcn doesn't crash
649 if (!parlist.FindCreateObj("MParameterD", "MinimizationValue"))
650 return kFALSE;
651
652 if (!parlist.FindObject("MParameters", "MParContainer"))
653 {
654 *fLog << err << "MParameters [MParContainer] not found... abort." << endl;
655 return kFALSE;
656 }
657
658 MMatrixLoop *loop = dynamic_cast<MMatrixLoop*>(parlist.FindTask("MRead"));
659
660 TString txt("Starting ");
661 switch (fType)
662 {
663 case kMigrad: txt += "Migrad"; break;
664 case kMinimize: txt += "Minimize"; break;
665 case kMinos: txt += "Minos"; break;
666 case kImprove: txt += "Improve"; break;
667 case kSimplex: txt += "Simplex"; break;
668 case kSeek: txt += "Seek"; break;
669 case kNone: txt += "no"; break;
670 }
671 txt += " optimization";
672
673 fLog->Separator(txt);
674
675 // Setup eventloop
676 MEvtLoop evtloop;
677 evtloop.SetParList(&parlist);
678 evtloop.SetDisplay(fDisplay); // set display for evtloop and all childs
679 parlist.SetDisplay(0); // reset display for all contents of parlist and tasklist
680 evtloop.SetPrivateDisplay(); // prevent display from being cascaded again in PreProcess
681
682 *fLog << inf << "Number of Parameters: " << fParameters.GetSize() << endl;
683
684 // In case the reader is the matrix loop and testrain is enabled
685 // switch on even mode...
686 if (loop && TMath::Abs(fTestTrain)>0)
687 loop->SetOperationMode(fTestTrain>0?MMatrixLoop::kEven:MMatrixLoop::kOdd);
688
689 if (!Optimize(evtloop))
690 return kFALSE;
691
692 gMinuit = 0;
693
694 fEvtLoop->SetDisplay(fDisplay);
695 if (!Fcn(fParameters))
696 return kFALSE;
697
698 // In case the reader is the matrix loop and testrain is enabled
699 // switch on odd mode...
700 if (!loop || fTestTrain==0)
701 return kTRUE;
702
703 loop->SetOperationMode(fTestTrain<0?MMatrixLoop::kEven:MMatrixLoop::kOdd);
704
705 // Done already in Fcn
706 // list.SetVariables(fParameters);
707 return Fcn(fParameters);
708}
709
710void MJOptimize::AddRulesToMatrix(MHMatrix &m) const
711{
712 TIter Next1(&fRules);
713 TObject *o1=0;
714 while ((o1=Next1()))
715 m.AddColumn(o1->GetName());
716}
717
718//------------------------------------------------------------------------
719//
720// Fill matrix m by using read. Use rules as a filter if userules.
721//
722Bool_t MJOptimize::FillMatrix(MReadTree &read, MParList &parlist, Bool_t userules)
723{
724 MHMatrix *m = (MHMatrix*)parlist.FindObject("M", "MHMatrix");
725 if (!m)
726 {
727 *fLog << err << "MJOptimize::FillMatrix - ERROR: M [MHMatrix] not found in parlist... abort." << endl;
728 return kFALSE;
729 }
730
731 m->Print("cols");
732
733 //MParList parlist;
734
735 // MGeomCamMagic cam;
736 // parlist.AddToList(&cam);
737
738 MTaskList tlist;
739 parlist.Replace(&tlist);
740
741 MFillH fillh(m);
742
743 tlist.AddToList(&read);
744
745 MFilterList list;
746 if (!list.AddToList(fPreCuts))
747 *fLog << err << "ERROR - Calling MFilterList::AddToList for fPreCuts failed!" << endl;
748 if (userules)
749 SetupFilters(list);
750 list.SetName("PreCuts"); // reset Name set by SetupFilters
751 list.SetInverted(kFALSE); // reset inversion set by SetupFilters
752 fillh.SetFilter(&list);
753 tlist.AddToList(&list);
754
755 tlist.AddToList(&fillh);
756
757 MEvtLoop fillloop;
758 fillloop.SetParList(&parlist);
759 fillloop.SetDisplay(fDisplay);
760 if (!fillloop.Eventloop(fNumEvents))
761 {
762 *fLog << err << "Filling matrix failed..." << endl;
763 return kFALSE;
764 }
765
766 *fLog << inf << "Read events from file '" << read.GetFileName() << "'" << endl;
767
768 if (fillloop.GetDisplay()!=fDisplay)
769 {
770 fDisplay = 0;
771 *fLog << inf << "Optimization aborted by user." << endl;
772 return kFALSE;
773 }
774
775 m->Print("size");
776
777 return kTRUE;
778}
779
780//------------------------------------------------------------------------
781//
782// Adds all filters to MFilterList
783//
784void MJOptimize::SetupFilters(MFilterList &list, MFilter *filter) const
785{
786 list.SetName("MParameters");
787 list.SetInverted();
788
789 if (filter)
790 {
791 if (fFilter.GetSize()>0)
792 {
793 *fLog << inf;
794 *fLog << "INFORMATION - You are using an external filter and internal filters." << endl;
795 *fLog << " Please make sure that all parameters '[i]' are starting" << endl;
796 *fLog << " behind the number of parameters of the external filter." << endl;
797 }
798 list.AddToList(filter);
799 }
800
801 if (!list.AddToList(fFilter))
802 *fLog << err << "ERROR - Calling MFilterList::AddToList fFilter failed!" << endl;
803
804 *fLog << inf << "Filter: ";
805 list.Print();
806 *fLog << endl;
807}
808
809//------------------------------------------------------------------------
810//
811Bool_t MJOptimize::Run(const char *fname, MFilter *filter, MAlphaFitter *fit)
812{
813 if (fParameters.GetSize()==0)
814 {
815 *fLog << err << "Sorry, no parameters defined." << endl;
816 return kFALSE;
817 }
818
819 fLog->Separator("Preparing On-only-optimization");
820
821 MParList parlist;
822
823 MGeomCamMagic geom; // For GetConvMm2Deg
824 parlist.AddToList(&geom);
825
826 MHMatrix m("M");
827 AddRulesToMatrix(m);
828 parlist.AddToList(&m);
829
830 MHAlpha hist;
831 hist.SkipHistTime();
832 hist.SkipHistTheta();
833 hist.SkipHistEnergy();
834 hist.InitMapping(&m);
835
836 if (filter && filter->InheritsFrom(MFMagicCuts::Class()))
837 ((MFMagicCuts*)filter)->InitMapping(&m);
838
839 MReadTree read("Events");
840 read.DisableAutoScheme(); // AutoScheme doesn't seem to be faster!
841 if (fname)
842 read.AddFile(fname);
843 else
844 AddSequences(read, fNamesOn);
845 if (!FillMatrix(read, parlist))
846 return kFALSE;
847
848 MTaskList tasklist;
849 parlist.Replace(&tasklist);
850 if (fit)
851 parlist.AddToList(fit);
852
853 MFilterList list;
854 SetupFilters(list, filter);
855
856 MContinue contin(&list);
857 parlist.AddToList(&list);
858
859 MFillH fill(&hist);
860
861 MMatrixLoop loop(&m);
862
863 tasklist.AddToList(&loop);
864 tasklist.AddToList(&list);
865 tasklist.AddToList(&contin);
866 tasklist.AddToList(&fill);
867
868 // Optimize with the tasklist in this parameterlist
869 if (!Optimize(parlist))
870 return kFALSE;
871
872 // Copy the result back to be accessible by the user
873 if (fit)
874 hist.GetAlphaFitter().Copy(*fit);
875 // Print the result
876 hist.GetAlphaFitter().Print("result");
877
878 // Store result if requested
879 TObjArray cont;
880 cont.Add(&contin);
881 return WriteContainer(cont, fNameOut);
882}
883
884//------------------------------------------------------------------------
885//
886// Make sure, that filter->GetDataMember is correctly implemented!!!!
887//
888Bool_t MJOptimize::RunOnOff(const char *fname, MFilter *filter, MAlphaFitter *fit, const char *tree)
889{
890 if (fParameters.GetSize()==0)
891 {
892 *fLog << err << "Sorry, no parameters defined." << endl;
893 return kFALSE;
894 }
895
896 fLog->Separator("Preparing On/Off-optimization");
897
898 MParList parlist;
899
900 MGeomCamMagic geom; // For GetConvMm2Deg
901 parlist.AddToList(&geom);
902
903 MHMatrix m("M");
904 AddRulesToMatrix(m);
905 parlist.AddToList(&m);
906
907 const Int_t idxdatatype = m.AddColumn("DataType.fVal");
908
909 MHAlpha histon, histof("MHAlphaOff");
910 histon.SkipHistTime();
911 histon.SkipHistTheta();
912 //histon.SkipHistEnergy();
913 histof.SkipHistTime();
914 histof.SkipHistTheta();
915 //histof.SkipHistEnergy();
916 histon.ForceUsingSize();
917 histof.ForceUsingSize();
918 histon.InitMapping(&m, 1);
919 histof.InitMapping(&m, 1);
920
921 if (filter && filter->InheritsFrom(MFMagicCuts::Class()))
922 ((MFMagicCuts*)filter)->InitMapping(&m);
923
924 parlist.AddToList(&histon);
925 parlist.AddToList(&histof);
926
927 if (fname)
928 {
929 MReadTree read(tree);
930 read.DisableAutoScheme(); // AutoScheme doesn't seem to be faster!
931 read.AddFile(fname);
932 if (!FillMatrix(read, parlist))
933 return kFALSE;
934 }
935 else
936 {
937 MParameterI par("DataType");
938 parlist.AddToList(&par);
939
940 gLog.Separator("Reading On-Data");
941 par.SetVal(1);
942 MReadTree readon(tree);
943 readon.DisableAutoScheme(); // AutoScheme doesn't seem to be faster!
944 AddSequences(readon, fNamesOn);
945 if (!FillMatrix(readon, parlist))
946 return kFALSE;
947
948 gLog.Separator("Reading Off-Data");
949 par.SetVal(0);
950 MReadTree readoff(tree);
951 readoff.DisableAutoScheme(); // AutoScheme doesn't seem to be faster!
952 AddSequences(readoff, fNamesOff);
953 if (!FillMatrix(readoff, parlist))
954 return kFALSE;
955 }
956
957 MTaskList tasklist;
958 parlist.Replace(&tasklist);
959 if (fit)
960 parlist.AddToList(fit);
961
962 MFilterList list;
963 SetupFilters(list, filter);
964
965 MContinue contin(&list);
966 parlist.AddToList(&list);
967
968 MFillH fillof(&histof, "", "FillHistOff");
969 MFillH fillon(&histon, "", "FillHistOn");
970
971 MF f0(Form("M[%d]<0.5", idxdatatype), "FilterOffData");
972 MF f1(Form("M[%d]>0.5", idxdatatype), "FilterOnData");
973
974 fillof.SetFilter(&f0);
975 fillon.SetFilter(&f1);
976
977 MMatrixLoop loop(&m);
978
979 tasklist.AddToList(&loop);
980 tasklist.AddToList(&list);
981 tasklist.AddToList(&contin);
982 tasklist.AddToList(&f0);
983 tasklist.AddToList(&f1);
984 tasklist.AddToList(&fillof);
985 tasklist.AddToList(&fillon);
986
987 // Optimize with the tasklist in this parameterlist
988 if (!Optimize(parlist))
989 return kFALSE;
990
991 // Copy the result back to be accessible by the user
992 if (fit)
993 histon.GetAlphaFitter().Copy(*fit);
994 // Print the result
995 histon.GetAlphaFitter().Print("result");
996
997 // Store result if requested
998 TObjArray cont;
999 cont.Add(&contin);
1000 return WriteContainer(cont, fNameOut);
1001}
1002
1003//------------------------------------------------------------------------
1004//
1005// Read all events from file which do match rules and optimize
1006// energy estimator.
1007//
1008Bool_t MJOptimize::RunEnergy(const char *fname, const char *rule)
1009{
1010 if (fParameters.GetSize()==0)
1011 {
1012 *fLog << err << "Sorry, no parameters defined." << endl;
1013 return kFALSE;
1014 }
1015
1016 fLog->Separator("Preparing Energy optimization");
1017
1018 MParList parlist;
1019
1020 MParameterI par("DataType");
1021 par.SetVal(1);
1022 parlist.AddToList(&par);
1023
1024 MFDataMember filter("DataType.fVal", '>', 0.5);
1025 fPreCuts.Add(&filter);
1026
1027 MGeomCamMagic geom; // For GetConvMm2Deg
1028 parlist.AddToList(&geom);
1029
1030 MHMatrix m("M");
1031 AddRulesToMatrix(m);
1032 parlist.AddToList(&m);
1033
1034 MHEnergyEst hist;
1035 hist.InitMapping(&m);
1036
1037 MEnergyEstimate est("MParameters");
1038 est.SetRule(rule);
1039 parlist.AddToList(&est);
1040
1041 MReadTree read("Events");
1042 // NECESSARY BECAUSE OF MDataFormula GetRules missing
1043 read.DisableAutoScheme();
1044 if (fname)
1045 read.AddFile(fname);
1046 else
1047 AddSequences(read, fNamesOn);
1048 if (!FillMatrix(read, parlist, kTRUE))
1049 return kFALSE;
1050
1051 fPreCuts.Remove(&filter);
1052
1053 MTaskList tasklist;
1054 parlist.Replace(&tasklist);
1055
1056 MFillH fill(&hist);
1057
1058 MMatrixLoop loop(&m);
1059
1060 tasklist.AddToList(&loop);
1061 tasklist.AddToList(&est);
1062 tasklist.AddToList(&fill);
1063
1064 // Optimize with the tasklist in this parameterlist
1065 if (!Optimize(parlist))
1066 return kFALSE;
1067
1068 // Print the result
1069 hist.Print();
1070
1071 // Store result if requested
1072 TObjArray cont;
1073 cont.Add(&est);
1074 return WriteContainer(cont, fNameOut);
1075}
Note: See TracBrowser for help on using the repository browser.