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

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