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

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