source: trunk/MagicSoft/Mars/mhist/MHMatrix.cc@ 2412

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