source: trunk/MagicSoft/Mars/mhbase/MHMatrix.cc@ 8923

Last change on this file since 8923 was 8907, checked in by tbretz, 17 years ago
*** empty log message ***
File size: 33.6 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 2002 <mailto:tbretz@astro.uni-wuerzburg.de>
19! Rudy Boeck 2003 <mailto:
20! Wolfgang Wittek2003 <mailto:wittek@mppmu.mpg.de>
21!
22! Copyright: MAGIC Software Development, 2000-2003
23!
24!
25\* ======================================================================== */
26
27/////////////////////////////////////////////////////////////////////////////
28//
29// MHMatrix
30//
31// This is a histogram container which holds a matrix with one column per
32// data variable. The data variable can be a complex rule (MDataPhrase).
33// Each event for wich Fill is called (by MFillH) is added as a new
34// row to the matrix.
35//
36// For example:
37// MHMatrix m;
38// m.AddColumn("MHillas.fSize");
39// m.AddColumn("MMcEvt.fImpact/100");
40// m.AddColumn("HillasSource.fDist*MGeomCam.fConvMm2Deg");
41// MFillH fillm(&m);
42// taskliost.AddToList(&fillm);
43// [...]
44// m.Print();
45//
46/////////////////////////////////////////////////////////////////////////////
47#include "MHMatrix.h"
48
49#include <fstream>
50
51#include <TMath.h>
52
53#include <TList.h>
54#include <TArrayF.h>
55#include <TArrayD.h>
56#include <TArrayI.h>
57
58#include <TH1.h>
59#include <TCanvas.h>
60#include <TRandom3.h>
61
62#include "MLog.h"
63#include "MLogManip.h"
64
65#include "MFillH.h"
66#include "MEvtLoop.h"
67#include "MParList.h"
68#include "MTaskList.h"
69#include "MProgressBar.h"
70
71#include "MData.h"
72#include "MDataArray.h"
73#include "MFilter.h"
74
75ClassImp(MHMatrix);
76
77using namespace std;
78
79const TString MHMatrix::gsDefName = "MHMatrix";
80const TString MHMatrix::gsDefTitle = "Multidimensional Matrix";
81
82// --------------------------------------------------------------------------
83//
84// Default Constructor
85//
86MHMatrix::MHMatrix(const char *name, const char *title)
87 : fNumRows(0), fData(NULL)
88{
89 fName = name ? name : gsDefName.Data();
90 fTitle = title ? title : gsDefTitle.Data();
91}
92
93// --------------------------------------------------------------------------
94//
95// Default Constructor
96//
97MHMatrix::MHMatrix(const TMatrix &m, const char *name, const char *title)
98 : fNumRows(m.GetNrows()), fM(m), fData(NULL)
99{
100 fName = name ? name : gsDefName.Data();
101 fTitle = title ? title : gsDefTitle.Data();
102}
103
104// --------------------------------------------------------------------------
105//
106// Constructor. Initializes the columns of the matrix with the entries
107// from a MDataArray
108//
109MHMatrix::MHMatrix(MDataArray *mat, const char *name, const char *title)
110 : fNumRows(0), fData(mat)
111{
112 fName = name ? name : gsDefName.Data();
113 fTitle = title ? title : gsDefTitle.Data();
114}
115
116// --------------------------------------------------------------------------
117//
118// Constructor. Initializes the columns of the matrix with the entries
119// from a MDataArray
120//
121MHMatrix::MHMatrix(const TMatrix &m, MDataArray *mat, const char *name, const char *title)
122 : fNumRows(m.GetNrows()), fM(m), fData(mat)
123{
124 fName = name ? name : gsDefName.Data();
125 fTitle = title ? title : gsDefTitle.Data();
126}
127
128// --------------------------------------------------------------------------
129//
130// Destructor. Does not deleted a user given MDataArray, except IsOwner
131// was called.
132//
133MHMatrix::~MHMatrix()
134{
135 if (TestBit(kIsOwner) && fData)
136 delete fData;
137}
138
139// --------------------------------------------------------------------------
140//
141Bool_t MHMatrix::SetNumRow(Int_t row)
142{
143 if (row>=fM.GetNrows() || row<0) return kFALSE;
144 fRow = row;
145 return kTRUE;
146}
147
148// --------------------------------------------------------------------------
149//
150// Add a new column to the matrix. This can only be done before the first
151// event (row) was filled into the matrix. For the syntax of the rule
152// see MDataPhrase.
153// Returns the index of the new column, -1 in case of failure.
154// (0, 1, 2, ... for the 1st, 2nd, 3rd, ...)
155//
156Int_t MHMatrix::AddColumn(const char *rule)
157{
158 const Int_t idx = fData ? fData->FindRule(rule) : -1;
159 if (idx>=0)
160 return idx;
161
162 if (IsValid(fM))
163 {
164 *fLog << warn << "Warning - matrix is already in use. Can't add a new column... skipped." << endl;
165 return -1;
166 }
167
168 if (TestBit(kIsLocked))
169 {
170 *fLog << warn << "Warning - matrix is locked. Can't add new column... skipped." << endl;
171 return -1;
172 }
173
174 if (!fData)
175 {
176 fData = new MDataArray;
177 SetBit(kIsOwner);
178 }
179
180 fData->AddEntry(rule);
181 return fData->GetNumEntries()-1;
182}
183
184// --------------------------------------------------------------------------
185//
186void MHMatrix::AddColumns(MDataArray *matrix)
187{
188 if (IsValid(fM))
189 {
190 *fLog << warn << "Warning - matrix is already in use. Can't add new columns... skipped." << endl;
191 return;
192 }
193
194 if (TestBit(kIsLocked))
195 {
196 *fLog << warn << "Warning - matrix is locked. Can't add new columns... skipped." << endl;
197 return;
198 }
199
200 if (fData)
201 *fLog << warn << "Warning - columns already added... replacing." << endl;
202
203 if (fData && TestBit(kIsOwner))
204 {
205 delete fData;
206 ResetBit(kIsOwner);
207 }
208
209 fData = matrix;
210}
211
212void MHMatrix::AddColumns(const TCollection &list)
213{
214 TIter Next(&list);
215 TObject *obj = 0;
216 while ((obj=Next()))
217 AddColumn(obj->GetName());
218}
219
220
221// --------------------------------------------------------------------------
222//
223// Checks whether at least one column is available and PreProcesses all
224// data chains.
225//
226Bool_t MHMatrix::SetupFill(const MParList *plist)
227{
228 if (!fData)
229 {
230 *fLog << err << "Error - No Columns initialized... aborting." << endl;
231 return kFALSE;
232 }
233
234 return fData->PreProcess(plist);
235}
236
237// --------------------------------------------------------------------------
238//
239// If the matrix has not enough rows double the number of available rows.
240//
241void MHMatrix::AddRow()
242{
243 fNumRows++;
244
245 if (fM.GetNrows() > fNumRows)
246 return;
247
248 if (!IsValid(fM))
249 {
250 fM.ResizeTo(1, fData->GetNumEntries());
251 return;
252 }
253
254#if ROOT_VERSION_CODE < ROOT_VERSION(3,05,07)
255 TMatrix m(fM);
256#endif
257 fM.ResizeTo(fM.GetNrows()*2, fData->GetNumEntries());
258
259#if ROOT_VERSION_CODE < ROOT_VERSION(3,05,07)
260 TVector vold(fM.GetNcols());
261 for (int x=0; x<m.GetNrows(); x++)
262 TMatrixRow(fM, x) = vold = TMatrixRow(m, x);
263#endif
264}
265
266// --------------------------------------------------------------------------
267//
268// Add the values correspoding to the columns to the new row
269//
270Bool_t MHMatrix::Fill(const MParContainer *par, const Stat_t w)
271{
272 AddRow();
273
274 for (int col=0; col<fData->GetNumEntries(); col++)
275 fM(fNumRows-1, col) = (*fData)(col);
276
277 return kTRUE;
278}
279
280// --------------------------------------------------------------------------
281//
282// Resize the matrix to a number of rows which corresponds to the number of
283// rows which have really been filled with values.
284//
285Bool_t MHMatrix::Finalize()
286{
287 //
288 // It's not a fatal error so we don't need to stop PostProcessing...
289 //
290 if (fData->GetNumEntries()==0 || fNumRows<1)
291 return kTRUE;
292
293 if (fNumRows != fM.GetNrows())
294 {
295 TMatrix m(fM);
296 CopyCrop(fM, m, fNumRows);
297 }
298
299 return kTRUE;
300}
301
302/*
303// --------------------------------------------------------------------------
304//
305// Draw clone of histogram. So that the object can be deleted
306// and the histogram is still visible in the canvas.
307// The cloned object are deleted together with the canvas if the canvas is
308// destroyed. If you want to handle destroying the canvas you can get a
309// pointer to it from this function
310//
311TObject *MHMatrix::DrawClone(Option_t *opt) const
312{
313 TCanvas &c = *MH::MakeDefCanvas(fHist);
314
315 //
316 // This is necessary to get the expected bahviour of DrawClone
317 //
318 gROOT->SetSelectedPad(NULL);
319
320 fHist->DrawCopy(opt);
321
322 TString str(opt);
323 if (str.Contains("PROFX", TString::kIgnoreCase) && fDimension==2)
324 {
325 TProfile *p = ((TH2*)fHist)->ProfileX();
326 p->Draw("same");
327 p->SetBit(kCanDelete);
328 }
329 if (str.Contains("PROFY", TString::kIgnoreCase) && fDimension==2)
330 {
331 TProfile *p = ((TH2*)fHist)->ProfileY();
332 p->Draw("same");
333 p->SetBit(kCanDelete);
334 }
335
336 c.Modified();
337 c.Update();
338
339 return &c;
340}
341
342// --------------------------------------------------------------------------
343//
344// Creates a new canvas and draws the histogram into it.
345// Be careful: The histogram belongs to this object and won't get deleted
346// together with the canvas.
347//
348void MHMatrix::Draw(Option_t *opt)
349{
350 if (!gPad)
351 MH::MakeDefCanvas(fHist);
352
353 fHist->Draw(opt);
354
355 TString str(opt);
356 if (str.Contains("PROFX", TString::kIgnoreCase) && fDimension==2)
357 {
358 TProfile *p = ((TH2*)fHist)->ProfileX();
359 p->Draw("same");
360 p->SetBit(kCanDelete);
361 }
362 if (str.Contains("PROFY", TString::kIgnoreCase) && fDimension==2)
363 {
364 TProfile *p = ((TH2*)fHist)->ProfileY();
365 p->Draw("same");
366 p->SetBit(kCanDelete);
367 }
368
369 gPad->Modified();
370 gPad->Update();
371}
372*/
373
374// --------------------------------------------------------------------------
375//
376// Prints the meaning of the columns and the contents of the matrix.
377// Becareful, this can take a long time for matrices with many rows.
378// Use the option 'size' to print the size of the matrix.
379// Use the option 'cols' to print the culumns
380// Use the option 'data' to print the contents
381//
382void MHMatrix::Print(Option_t *o) const
383{
384 TString str(o);
385
386 *fLog << all << flush;
387
388 if (str.Contains("size", TString::kIgnoreCase))
389 {
390 *fLog << GetDescriptor() << ": NumColumns=" << fM.GetNcols();
391 *fLog << " NumRows=" << fM.GetNrows() << endl;
392 }
393
394 if (!fData && str.Contains("cols", TString::kIgnoreCase))
395 *fLog << "Sorry, no column information available." << endl;
396
397 if (fData && str.Contains("cols", TString::kIgnoreCase))
398 {
399 fData->SetName(fName);
400 fData->Print();
401 }
402
403 if (str.Contains("data", TString::kIgnoreCase))
404 fM.Print();
405}
406
407// --------------------------------------------------------------------------
408//
409const TMatrix *MHMatrix::InvertPosDef()
410{
411 TMatrix m(fM);
412
413 const Int_t rows = m.GetNrows();
414 const Int_t cols = m.GetNcols();
415
416 for (int x=0; x<cols; x++)
417 {
418 Double_t avg = 0;
419 for (int y=0; y<rows; y++)
420 avg += fM(y, x);
421
422 avg /= rows;
423
424#if ROOT_VERSION_CODE > ROOT_VERSION(5,00,00)
425 TMatrixFColumn(m, x) += -avg;
426#else
427 TMatrixColumn(m, x) += -avg;
428#endif
429 }
430
431 TMatrix *m2 = new TMatrix(m, TMatrix::kTransposeMult, m);
432
433 Double_t det;
434 m2->Invert(&det);
435 if (det==0)
436 {
437 *fLog << err << "ERROR - MHMatrix::InvertPosDef failed (Matrix is singular)." << endl;
438 delete m2;
439 return NULL;
440 }
441
442 // m2->Print();
443
444 return m2;
445}
446
447// --------------------------------------------------------------------------
448//
449// Calculated the distance of vector evt from the reference sample
450// represented by the covariance metrix m.
451// - If n<0 the kernel method is applied and
452// -log(sum(epx(-d/h))/n) is returned.
453// - For n>0 the n nearest neighbors are summed and
454// sqrt(sum(d)/n) is returned.
455// - if n==0 all distances are summed
456//
457Double_t MHMatrix::CalcDist(const TMatrix &m, const TVector &evt, Int_t num) const
458{
459 if (num==0) // may later be used for another method
460 {
461 TVector d = evt;
462 d *= m;
463 return TMath::Sqrt(d*evt);
464 }
465
466 const Int_t rows = fM.GetNrows();
467 const Int_t cols = fM.GetNcols();
468
469 TArrayD dists(rows);
470
471 //
472 // Calculate: v^T * M * v
473 //
474 for (int i=0; i<rows; i++)
475 {
476 TVector col(cols);
477#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
478 col = TMatrixRow(fM, i);
479#else
480 col = TMatrixFRow_const(fM, i);
481#endif
482 TVector d = evt;
483 d -= col;
484
485 TVector d2 = d;
486 d2 *= m;
487
488 dists[i] = d2*d; // square of distance
489
490 //
491 // This corrects for numerical uncertanties in cases of very
492 // small distances...
493 //
494 if (dists[i]<0)
495 dists[i]=0;
496 }
497
498 TArrayI idx(rows);
499 TMath::Sort(dists.GetSize(), dists.GetArray(), idx.GetArray(), kFALSE);
500
501 Int_t from = 0;
502 Int_t to = TMath::Abs(num)<rows ? TMath::Abs(num) : rows;
503 //
504 // This is a zero-suppression for the case a test- and trainings
505 // sample is identical. This would result in an unwanted leading
506 // zero in the array. To suppress also numerical uncertanties of
507 // zero we cut at 1e-5. Due to Rudy this should be enough. If
508 // you encounter problems we can also use (eg) 1e-25
509 //
510 if (dists[idx[0]]<1e-5)
511 {
512 from++;
513 to ++;
514 if (to>rows)
515 to = rows;
516 }
517
518 if (num<0)
519 {
520 //
521 // Kernel function sum (window size h set according to literature)
522 //
523 const Double_t h = TMath::Power(rows, -1./(cols+4));
524 const Double_t hwin = h*h*2;
525
526 Double_t res = 0;
527 for (int i=from; i<to; i++)
528 res += TMath::Exp(-dists[idx[i]]/hwin);
529
530 return -TMath::Log(res/(to-from));
531 }
532 else
533 {
534 //
535 // Nearest Neighbor sum
536 //
537 Double_t res = 0;
538 for (int i=from; i<to; i++)
539 res += dists[idx[i]];
540
541 return TMath::Sqrt(res/(to-from));
542 }
543}
544
545// --------------------------------------------------------------------------
546//
547// Calls calc dist. In the case of the first call the covariance matrix
548// fM2 is calculated.
549// - If n<0 it is divided by (nrows-1)/h while h is the kernel factor.
550//
551Double_t MHMatrix::CalcDist(const TVector &evt, Int_t num)
552{
553 if (!IsValid(fM2))
554 {
555 if (!IsValid(fM))
556 {
557 *fLog << err << "MHMatrix::CalcDist - ERROR: fM not valid." << endl;
558 return -1;
559 }
560
561 const TMatrix *m = InvertPosDef();
562 if (!m)
563 return -1;
564
565 fM2.ResizeTo(*m);
566 fM2 = *m;
567 fM2 *= fM.GetNrows()-1;
568 delete m;
569 }
570
571 return CalcDist(fM2, evt, num);
572}
573
574// --------------------------------------------------------------------------
575//
576void MHMatrix::Reassign()
577{
578 TMatrix m = fM;
579 fM.ResizeTo(1,1);
580 fM.ResizeTo(m);
581 fM = m;
582}
583
584// --------------------------------------------------------------------------
585//
586// Implementation of SavePrimitive. Used to write the call to a constructor
587// to a macro. In the original root implementation it is used to write
588// gui elements to a macro-file.
589//
590void MHMatrix::StreamPrimitive(ostream &out) const
591{
592 Bool_t data = fData && !TestBit(kIsOwner);
593
594 if (data)
595 {
596 fData->SavePrimitive(out);
597 out << endl;
598 }
599
600 out << " MHMatrix " << GetUniqueName();
601
602 if (data || fName!=gsDefName || fTitle!=gsDefTitle)
603 {
604 out << "(";
605 if (data)
606 out << "&" << fData->GetUniqueName();
607 if (fName!=gsDefName || fTitle!=gsDefTitle)
608 {
609 if (data)
610 out << ", ";
611 out << "\"" << fName << "\"";
612 if (fTitle!=gsDefTitle)
613 out << ", \"" << fTitle << "\"";
614 }
615 }
616 out << ");" << endl;
617
618 if (fData && TestBit(kIsOwner))
619 for (int i=0; i<fData->GetNumEntries(); i++)
620 out << " " << GetUniqueName() << ".AddColumn(\"" << (*fData)[i].GetRule() << "\");" << endl;
621}
622
623// --------------------------------------------------------------------------
624//
625const TArrayI MHMatrix::GetIndexOfSortedColumn(Int_t ncol, Bool_t desc) const
626{
627#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
628 TMatrixColumn col(fM, ncol);
629#else
630 TMatrixFColumn_const col(fM, ncol);
631#endif
632
633 const Int_t n = fM.GetNrows();
634
635 TArrayF array(n);
636
637 for (int i=0; i<n; i++)
638 array[i] = col(i);
639
640 TArrayI idx(n);
641 TMath::Sort(n, array.GetArray(), idx.GetArray(), desc);
642
643 return idx;
644}
645
646// --------------------------------------------------------------------------
647//
648void MHMatrix::SortMatrixByColumn(Int_t ncol, Bool_t desc)
649{
650 TArrayI idx = GetIndexOfSortedColumn(ncol, desc);
651
652 const Int_t n = fM.GetNrows();
653
654#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
655 TVector vold(fM.GetNcols());
656#endif
657
658 TMatrix m(n, fM.GetNcols());
659 for (int i=0; i<n; i++)
660#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
661 TMatrixRow(m, i) = vold = TMatrixRow(fM, idx[i]);
662#else
663 TMatrixFRow(m, i) = TMatrixFRow_const(fM, idx[i]);
664#endif
665 fM = m;
666}
667
668// --------------------------------------------------------------------------
669//
670Bool_t MHMatrix::Fill(MParList *plist, MTask *read, MFilter *filter)
671{
672 //
673 // Read data into Matrix
674 //
675 const Bool_t is = plist->IsOwner();
676 plist->SetOwner(kFALSE);
677
678 MTaskList tlist;
679 plist->Replace(&tlist);
680
681 MFillH fillh(this);
682
683 tlist.AddToList(read);
684
685 if (filter)
686 {
687 tlist.AddToList(filter);
688 fillh.SetFilter(filter);
689 }
690
691 tlist.AddToList(&fillh);
692
693 //MProgressBar bar;
694 MEvtLoop evtloop("MHMatrix::Fill-EvtLoop");
695 evtloop.SetParList(plist);
696 //evtloop.SetProgressBar(&bar);
697
698 if (!evtloop.Eventloop())
699 return kFALSE;
700
701 tlist.PrintStatistics();
702
703 plist->Remove(&tlist);
704 plist->SetOwner(is);
705
706 return kTRUE;
707}
708
709// --------------------------------------------------------------------------
710//
711// Return a comma seperated list of all data members used in the matrix.
712// This is mainly used in MTask::AddToBranchList
713//
714TString MHMatrix::GetDataMember() const
715{
716 return fData ? fData->GetDataMember() : TString("");
717}
718
719// --------------------------------------------------------------------------
720//
721//
722void MHMatrix::ReduceNumberOfRows(UInt_t numrows, const TString opt)
723{
724 UInt_t rows = fM.GetNrows();
725
726 if (rows==numrows)
727 {
728 *fLog << warn << "Matrix has already the correct number of rows..." << endl;
729 return;
730 }
731
732 Float_t ratio = (Float_t)numrows/fM.GetNrows();
733
734 if (ratio>=1)
735 {
736 *fLog << warn << "Matrix cannot be enlarged..." << endl;
737 return;
738 }
739
740 Double_t sum = 0;
741
742 UInt_t oldrow = 0;
743 UInt_t newrow = 0;
744
745#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
746 TVector vold(fM.GetNcols());
747#endif
748 while (oldrow<rows)
749 {
750 sum += ratio;
751
752 if (newrow<=(unsigned int)sum)
753#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
754 TMatrixRow(fM, newrow++) = vold = TMatrixRow(fM, oldrow);
755#else
756 TMatrixFRow(fM, newrow++) = TMatrixFRow_const(fM, oldrow);
757#endif
758
759 oldrow++;
760 }
761}
762
763// ------------------------------------------------------------------------
764//
765// Used in DefRefMatrix to display the result graphically
766//
767void MHMatrix::DrawDefRefInfo(const TH1 &hth, const TH1 &hthd, const TH1 &thsh, Int_t refcolumn)
768{
769 //
770 // Fill a histogram with the distribution after raduction
771 //
772 TH1F hta;
773 hta.SetDirectory(NULL);
774 hta.SetName("hta");
775 hta.SetTitle("Distribution after reduction");
776 SetBinning(&hta, &hth);
777
778 for (Int_t i=0; i<fM.GetNrows(); i++)
779 hta.Fill(fM(i, refcolumn));
780
781 TCanvas *th1 = MakeDefCanvas(this);
782 th1->Divide(2,2);
783
784 th1->cd(1);
785 ((TH1&)hth).DrawCopy(); // real histogram before
786
787 th1->cd(2);
788 ((TH1&)hta).DrawCopy(); // histogram after
789
790 th1->cd(3);
791 ((TH1&)hthd).DrawCopy(); // correction factors
792
793 th1->cd(4);
794 ((TH1&)thsh).DrawCopy(); // target
795}
796
797// ------------------------------------------------------------------------
798//
799// Resizes th etarget matrix to rows*source.GetNcol() and copies
800// the data from the first (n)rows or the source into the target matrix.
801//
802void MHMatrix::CopyCrop(TMatrix &target, const TMatrix &source, Int_t rows)
803{
804#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
805 TVector v(source.GetNcols());
806#endif
807 target.ResizeTo(rows, source.GetNcols());
808 for (Int_t ir=0; ir<rows; ir++)
809#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
810 TMatrixRow(target, ir) = v = TMatrixRow(source, ir);
811#else
812 TMatrixFRow(target, ir) = TMatrixFRow_const(source, ir);
813#endif
814}
815
816// ------------------------------------------------------------------------
817//
818// Define the reference matrix
819// refcolumn number of the column (starting at 0) containing the variable,
820// for which a target distribution may be given;
821// thsh histogram containing the target distribution of the variable
822// nmaxevts the number of events the reference matrix should have after
823// the renormalization
824// rest a TMatrix conatining the resulting (not choosen)
825// columns of the primary matrix. Maybe NULL if you
826// are not interested in this
827//
828Bool_t MHMatrix::DefRefMatrix(const UInt_t refcolumn, const TH1F &thsh,
829 Int_t nmaxevts, TMatrix *rest)
830{
831 if (!IsValid(fM))
832 {
833 *fLog << err << dbginf << "Matrix not initialized" << endl;
834 return kFALSE;
835 }
836
837 if (thsh.GetMinimum()<0)
838 {
839 *fLog << err << dbginf << "Renormalization not possible: ";
840 *fLog << "Target Distribution has values < 0" << endl;
841 return kFALSE;
842 }
843
844
845 if (nmaxevts>fM.GetNrows())
846 {
847 *fLog << warn << dbginf << "No.requested (" << nmaxevts;
848 *fLog << ") > available events (" << fM.GetNrows() << ")... ";
849 *fLog << "setting equal." << endl;
850 nmaxevts = fM.GetNrows();
851 }
852
853
854 if (nmaxevts<0)
855 {
856 *fLog << err << dbginf << "Number of requested events < 0" << endl;
857 return kFALSE;
858 }
859
860 if (nmaxevts==0)
861 nmaxevts = fM.GetNrows();
862
863 //
864 // refcol is the column number starting at 0; it is >= 0
865 //
866 // number of the column (count from 0) containing
867 // the variable for which the target distribution is given
868 //
869
870 //
871 // Calculate normalization factors
872 //
873 //const int nbins = thsh.GetNbinsX();
874 //const double frombin = thsh.GetBinLowEdge(1);
875 //const double tobin = thsh.GetBinLowEdge(nbins+1);
876 //const double dbin = thsh.GetBinWidth(1);
877
878 const Int_t nrows = fM.GetNrows();
879 const Int_t ncols = fM.GetNcols();
880
881 //
882 // set up the real histogram (distribution before)
883 //
884 //TH1F hth("th", "Distribution before reduction", nbins, frombin, tobin);
885 TH1F hth;
886 hth.SetNameTitle("th", "Distribution before reduction");
887 SetBinning(&hth, &thsh);
888 hth.SetDirectory(NULL);
889 for (Int_t j=0; j<nrows; j++)
890 hth.Fill(fM(j, refcolumn));
891
892 //TH1F hthd("thd", "Correction factors", nbins, frombin, tobin);
893 TH1F hthd;
894 hthd.SetNameTitle("thd", "Correction factors");
895 SetBinning(&hthd, &thsh);
896 hthd.SetDirectory(NULL);
897 hthd.Divide((TH1F*)&thsh, &hth, 1, 1);
898
899 if (hthd.GetMaximum() <= 0)
900 {
901 *fLog << err << dbginf << "Maximum correction factor <= 0... abort." << endl;
902 return kFALSE;
903 }
904
905 //
906 // ===== obtain correction factors (normalization factors)
907 //
908 hthd.Scale(1/hthd.GetMaximum());
909
910 //
911 // get random access
912 //
913 TArrayI ind(nrows);
914 GetRandomArrayI(ind);
915
916 //
917 // define new matrix
918 //
919 Int_t evtcount1 = -1;
920 Int_t evtcount2 = 0;
921
922 TMatrix mnewtmp(nrows, ncols);
923 TMatrix mrest(nrows, ncols);
924
925 TArrayF cumulweight(nrows); // keep track for each bin how many events
926
927 //
928 // Project values in reference column into [0,1]
929 //
930 TVector v(fM.GetNrows());
931#if ROOT_VERSION_CODE > ROOT_VERSION(5,00,00)
932 v = TMatrixFColumn_const(fM, refcolumn);
933#else
934 v = TMatrixColumn(fM, refcolumn);
935#endif
936 //v += -frombin;
937 //v *= 1/dbin;
938
939 //
940 // select events (distribution after renormalization)
941 //
942 Int_t ir;
943#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
944 TVector vold(fM.GetNcols());
945#endif
946 for (ir=0; ir<nrows; ir++)
947 {
948 // const Int_t indref = (Int_t)v(ind[ir]);
949 const Int_t indref = hthd.FindBin(v(ind[ir])) - 1;
950 cumulweight[indref] += hthd.GetBinContent(indref+1);
951 if (cumulweight[indref]<=0.5)
952 {
953#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
954 TMatrixRow(mrest, evtcount2++) = vold = TMatrixRow(fM, ind[ir]);
955#else
956 TMatrixFRow(mrest, evtcount2++) = TMatrixFRow_const(fM, ind[ir]);
957#endif
958 continue;
959 }
960
961 cumulweight[indref] -= 1.;
962 if (++evtcount1 >= nmaxevts)
963 break;
964
965#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
966 TMatrixRow(mnewtmp, evtcount1) = vold = TMatrixRow(fM, ind[ir]);
967#else
968 TMatrixFRow(mnewtmp, evtcount1) = TMatrixFRow_const(fM, ind[ir]);
969#endif
970 }
971
972 for (/*empty*/; ir<nrows; ir++)
973#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
974 TMatrixRow(mrest, evtcount2++) = vold = TMatrixRow(fM, ind[ir]);
975#else
976 TMatrixFRow(mrest, evtcount2++) = TMatrixFRow_const(fM, ind[ir]);
977#endif
978
979 //
980 // reduce size
981 //
982 // matrix fM having the requested distribution
983 // and the requested number of rows;
984 // this is the matrix to be used in the g/h separation
985 //
986 CopyCrop(fM, mnewtmp, evtcount1);
987 fNumRows = evtcount1;
988
989 if (evtcount1 < nmaxevts)
990 *fLog << warn << "Reference sample contains less events (" << evtcount1 << ") than requested (" << nmaxevts << ")" << endl;
991
992 if (TestBit(kEnableGraphicalOutput))
993 DrawDefRefInfo(hth, hthd, thsh, refcolumn);
994
995 if (rest)
996 CopyCrop(*rest, mrest, evtcount2);
997
998 return kTRUE;
999}
1000
1001// ------------------------------------------------------------------------
1002//
1003// Returns a array containing randomly sorted indices
1004//
1005void MHMatrix::GetRandomArrayI(TArrayI &ind) const
1006{
1007 const Int_t rows = ind.GetSize();
1008
1009 TArrayF ranx(rows);
1010
1011 TRandom3 rnd(0);
1012 for (Int_t i=0; i<rows; i++)
1013 ranx[i] = rnd.Rndm(i);
1014
1015 TMath::Sort(rows, ranx.GetArray(), ind.GetArray(), kTRUE);
1016}
1017
1018// ------------------------------------------------------------------------
1019//
1020// Define the reference matrix
1021// nmaxevts maximum number of events in the reference matrix
1022// rest a TMatrix conatining the resulting (not choosen)
1023// columns of the primary matrix. Maybe NULL if you
1024// are not interested in this
1025//
1026// the target distribution will be set
1027// equal to the real distribution; the events in the reference
1028// matrix will then be simply a random selection of the events
1029// in the original matrix.
1030//
1031Bool_t MHMatrix::DefRefMatrix(Int_t nmaxevts, TMatrix *rest)
1032{
1033 if (!IsValid(fM))
1034 {
1035 *fLog << err << dbginf << "Matrix not initialized" << endl;
1036 return kFALSE;
1037 }
1038
1039 if (nmaxevts>fM.GetNrows())
1040 {
1041 *fLog << dbginf << "No.of requested events (" << nmaxevts
1042 << ") exceeds no.of available events (" << fM.GetNrows()
1043 << ")" << endl;
1044 *fLog << dbginf
1045 << " set no.of requested events = no.of available events"
1046 << endl;
1047 nmaxevts = fM.GetNrows();
1048 }
1049
1050 if (nmaxevts<0)
1051 {
1052 *fLog << err << dbginf << "Number of requested events < 0" << endl;
1053 return kFALSE;
1054 }
1055
1056 if (nmaxevts==0)
1057 nmaxevts = fM.GetNrows();
1058
1059 const Int_t nrows = fM.GetNrows();
1060 const Int_t ncols = fM.GetNcols();
1061
1062 //
1063 // get random access
1064 //
1065 TArrayI ind(nrows);
1066 GetRandomArrayI(ind);
1067
1068 //
1069 // define new matrix
1070 //
1071 Int_t evtcount1 = 0;
1072 Int_t evtcount2 = 0;
1073
1074 TMatrix mnewtmp(nrows, ncols);
1075 TMatrix mrest(nrows, ncols);
1076
1077 //
1078 // select events (distribution after renormalization)
1079 //
1080#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
1081 TVector vold(fM.GetNcols());
1082#endif
1083 for (Int_t ir=0; ir<nmaxevts; ir++)
1084#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
1085 TMatrixRow(mnewtmp, evtcount1++) = vold = TMatrixRow(fM, ind[ir]);
1086#else
1087 TMatrixFRow(mnewtmp, evtcount1++) = TMatrixFRow_const(fM, ind[ir]);
1088#endif
1089
1090 for (Int_t ir=nmaxevts; ir<nrows; ir++)
1091#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
1092 TMatrixRow(mrest, evtcount2++) = vold = TMatrixRow(fM, ind[ir]);
1093#else
1094 TMatrixFRow(mrest, evtcount2++) = TMatrixFRow_const(fM, ind[ir]);
1095#endif
1096
1097 //
1098 // reduce size
1099 //
1100 // matrix fM having the requested distribution
1101 // and the requested number of rows;
1102 // this is the matrix to be used in the g/h separation
1103 //
1104 CopyCrop(fM, mnewtmp, evtcount1);
1105 fNumRows = evtcount1;
1106
1107 if (evtcount1 < nmaxevts)
1108 *fLog << warn << "The reference sample contains less events (" << evtcount1 << ") than requested (" << nmaxevts << ")" << endl;
1109
1110 if (!rest)
1111 return kTRUE;
1112
1113 CopyCrop(*rest, mrest, evtcount2);
1114
1115 return kTRUE;
1116}
1117
1118// --------------------------------------------------------------------------
1119//
1120// overload TOject member function read
1121// in order to reset the name of the object read
1122//
1123Int_t MHMatrix::Read(const char *name)
1124{
1125 Int_t ret = TObject::Read(name);
1126 SetName(name);
1127
1128 return ret;
1129}
1130
1131// --------------------------------------------------------------------------
1132//
1133// Read the setup from a TEnv:
1134// Column0, Column1, Column2, ..., Column10, ..., Column100, ...
1135//
1136// Searching stops if the first key isn't found in the TEnv. Empty
1137// columns are not allowed
1138//
1139// eg.
1140// MHMatrix.Column0: cos(MMcEvt.fTelescopeTheta)
1141// MHMatrix.Column1: MHillasSrc.fAlpha
1142//
1143Int_t MHMatrix::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
1144{
1145 if (IsValid(fM))
1146 {
1147 *fLog << err << "ERROR - matrix is already in use. Can't add a new column from TEnv... skipped." << endl;
1148 return kERROR;
1149 }
1150
1151 if (TestBit(kIsLocked))
1152 {
1153 *fLog << err << "ERROR - matrix is locked. Can't add new column from TEnv... skipped." << endl;
1154 return kERROR;
1155 }
1156
1157 //
1158 // Search (beginning with 0) all keys
1159 //
1160 int i=0;
1161 while (1)
1162 {
1163 TString idx = "Column";
1164 idx += i;
1165
1166 // Output if print set to kTRUE
1167 if (!IsEnvDefined(env, prefix, idx, print))
1168 break;
1169
1170 // Try to get the file name
1171 TString name = GetEnvValue(env, prefix, idx, "");
1172 if (name.IsNull())
1173 {
1174 *fLog << warn << prefix+"."+idx << " empty." << endl;
1175 continue;
1176 }
1177
1178 if (i==0)
1179 if (fData)
1180 {
1181 *fLog << inf << "Removing all existing columns in " << GetDescriptor() << endl;
1182 fData->Delete();
1183 }
1184 else
1185 {
1186 fData = new MDataArray;
1187 SetBit(kIsOwner);
1188 }
1189
1190 fData->AddEntry(name);
1191 i++;
1192 }
1193
1194 return i!=0;
1195}
1196
1197// --------------------------------------------------------------------------
1198//
1199// ShuffleEvents. Shuffles the order of the matrix rows.
1200//
1201//
1202void MHMatrix::ShuffleRows(UInt_t seed)
1203{
1204 TRandom rnd(seed);
1205
1206 TVector v(fM.GetNcols());
1207#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
1208 TVector tmp(fM.GetNcols());
1209#endif
1210 for (Int_t irow = 0; irow<fNumRows; irow++)
1211 {
1212 const Int_t jrow = rnd.Integer(fNumRows);
1213
1214#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
1215 v = TMatrixRow(fM, irow);
1216 TMatrixRow(fM, irow) = tmp = TMatrixRow(fM, jrow);
1217 TMatrixRow(fM, jrow) = v;
1218#else
1219 v = TMatrixFRow_const(fM, irow);
1220 TMatrixFRow(fM, irow) = TMatrixFRow_const(fM, jrow);
1221 TMatrixFRow(fM, jrow) = v;
1222#endif
1223 }
1224
1225 *fLog << warn << GetDescriptor() << ": Attention! Matrix rows have been shuffled." << endl;
1226}
1227
1228// --------------------------------------------------------------------------
1229//
1230// Reduces the number of rows to the given number num by cutting out the
1231// last rows.
1232//
1233void MHMatrix::ReduceRows(UInt_t num)
1234{
1235 if ((Int_t)num>=fM.GetNrows())
1236 {
1237 *fLog << warn << GetDescriptor() << ": Warning - " << num << " >= rows=" << fM.GetNrows() << endl;
1238 return;
1239 }
1240
1241#if ROOT_VERSION_CODE < ROOT_VERSION(3,05,07)
1242 const TMatrix m(fM);
1243#endif
1244 fM.ResizeTo(num, fM.GetNcols());
1245
1246#if ROOT_VERSION_CODE < ROOT_VERSION(3,05,07)
1247 TVector tmp(fM.GetNcols());
1248 for (UInt_t irow=0; irow<num; irow++)
1249 TMatrixRow(fM, irow) = tmp = TMatrixRow(m, irow);
1250#endif
1251}
1252
1253// --------------------------------------------------------------------------
1254//
1255// Remove rows which contains numbers not fullfilling TMath::Finite
1256//
1257Bool_t MHMatrix::RemoveInvalidRows()
1258{
1259 TMatrix m(fM);
1260
1261 const Int_t ncol=fM.GetNcols();
1262
1263#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
1264 TVector vold(ncol);
1265#endif
1266
1267 int irow=0;
1268
1269 for (int i=0; i<m.GetNrows(); i++)
1270 {
1271#if ROOT_VERSION_CODE > ROOT_VERSION(5,00,00)
1272 const TMatrixFRow_const &row = TMatrixFRow_const(m, i);
1273#else
1274 const TMatrixRow &row = TMatrixRow(m, i);
1275#endif
1276 // finite (-> math.h) checks for NaN as well as inf
1277 int jcol;
1278 for (jcol=0; jcol<ncol; jcol++)
1279 if (!TMath::Finite(row(jcol)))
1280 break;
1281
1282 if (jcol==ncol)
1283#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
1284 TMatrixRow(fM, irow++) = vold = row;
1285#else
1286 TMatrixFRow(fM, irow++) = row;
1287#endif
1288 else
1289 *fLog << warn << "Warning - MHMatrix::RemoveInvalidRows: row #" << i<< " removed." << endl;
1290 }
1291
1292 // Do not use ResizeTo (in older root versions this doesn't save the contents
1293 ReduceRows(irow);
1294
1295 return kTRUE;
1296}
1297
1298// --------------------------------------------------------------------------
1299//
1300// Returns the row pointed to by fNumRow into TVector v
1301//
1302void MHMatrix::GetRow(TVector &v) const
1303{
1304 Int_t ncols = fM.GetNcols();
1305
1306 v.ResizeTo(ncols);
1307
1308 while (ncols--)
1309 v(ncols) = fM(fRow, ncols);
1310}
Note: See TracBrowser for help on using the repository browser.