88 if (!IsEnabled() || IsCreated())
return kTRUE;
90 Log() <<
kINFO <<
"Preparing the Principle Component (PCA) transformation..." <<
Endl;
92 UInt_t inputSize = fGet.size();
94 SetNVariables(inputSize);
98 Log() <<
kFATAL <<
"Cannot perform PCA transformation for " << inputSize <<
" variable only" <<
Endl;
102 if (inputSize > 200) {
103 Log() <<
kINFO <<
"----------------------------------------------------------------------------"
106 <<
": More than 200 variables, will not calculate PCA!" <<
Endl;
107 Log() <<
kINFO <<
"----------------------------------------------------------------------------"
112 CalculatePrincipalComponents( events );
124 if (!IsCreated())
return 0;
135 if (cls < 0 || cls >= (
int) fMeanValues.size()) cls = fMeanValues.size()-1;
140 if (fTransformedEvent==0 ) {
141 fTransformedEvent =
new Event();
144 std::vector<Float_t> input;
145 std::vector<Char_t> mask;
146 std::vector<Float_t> principalComponents;
148 Bool_t hasMaskedEntries = GetInput( ev, input, mask );
150 if( hasMaskedEntries ){
153 if( numMasked>0 && numOK>0 ){
154 Log() <<
kFATAL <<
"You mixed variables and targets in the decorrelation transformation. This is not possible." <<
Endl;
156 SetOutput( fTransformedEvent, input, mask, ev );
157 return fTransformedEvent;
160 X2P( principalComponents, input, cls );
161 SetOutput( fTransformedEvent, principalComponents, mask, ev );
163 return fTransformedEvent;
173 if (!IsCreated())
return 0;
175 const UInt_t nCls = GetNClasses();
181 if (cls < 0 ||
UInt_t(cls) > nCls) cls = (fMeanValues.size()==1?0:2);
184 if (fBackTransformedEvent==0 ) fBackTransformedEvent =
new Event();
186 std::vector<Float_t> principalComponents;
187 std::vector<Char_t> mask;
188 std::vector<Float_t>
output;
190 GetInput( ev, principalComponents, mask,
kTRUE );
191 P2X( output, principalComponents, cls );
192 SetOutput( fBackTransformedEvent, output, mask, ev,
kTRUE );
194 return fBackTransformedEvent;
203 UInt_t nvars = 0, ntgts = 0, nspcts = 0;
204 CountVariableTypes( nvars, ntgts, nspcts );
205 if( nvars>0 && ntgts>0 )
206 Log() <<
kFATAL <<
"Variables and targets cannot be mixed in PCA transformation." <<
Endl;
208 const Int_t inputSize = fGet.size();
211 const UInt_t nCls = GetNClasses();
212 const UInt_t maxPCA = (nCls<=1) ? nCls : nCls+1;
215 std::vector<TPrincipal*> pca(maxPCA);
221 Long64_t ievt, entries = events.size();
224 std::vector<Float_t> input;
225 std::vector<Char_t> mask;
226 for (ievt=0; ievt<entries; ievt++) {
227 const Event* ev = events[ievt];
230 Bool_t hasMaskedEntries = GetInput( ev, input, mask );
231 if (hasMaskedEntries){
233 std::ostringstream oss;
236 Log() <<
kFATAL <<
"Masked entries found in event read in when calculating the principal components for the PCA transformation." <<
Endl;
240 for( std::vector<Float_t>::iterator itInp = input.begin(), itInpEnd = input.end(); itInp != itInpEnd; ++itInp )
247 pca.at(cls)->AddRow( dvec );
248 if (nCls > 1) pca.at(maxPCA-1)->AddRow( dvec );
252 for (
UInt_t i=0; i<fMeanValues.size(); i++)
if (fMeanValues[i] != 0)
delete fMeanValues[i];
253 for (
UInt_t i=0; i<fEigenVectors.size(); i++)
if (fEigenVectors[i] != 0)
delete fEigenVectors[i];
254 fMeanValues.resize(maxPCA,0);
255 fEigenVectors.resize(maxPCA,0);
257 for (
UInt_t i=0; i<maxPCA; i++ ) {
258 pca.at(i)->MakePrincipals();
261 fMeanValues[i] =
new TVectorD( *(pca.at(i)->GetMeanValues()) );
262 fEigenVectors[i] =
new TMatrixD( *(pca.at(i)->GetEigenVectors()) );
265 for (
UInt_t i=0; i<maxPCA; i++)
delete pca.at(i);
277 const Int_t nInput = x.size();
280 for (
Int_t i = 0; i < nInput; i++) {
282 for (
Int_t j = 0; j < nInput; j++)
283 pv += (((
Double_t)x.at(j)) - (*fMeanValues.at(cls))(j)) * (*fEigenVectors.at(cls))(j,i);
296 const Int_t nInput = pc.size();
299 for (
Int_t i = 0; i < nInput; i++) {
301 for (
Int_t j = 0; j < nInput; j++)
302 xv += (((
Double_t)pc.at(j)) * (*fEigenVectors.at(cls))(i,j) ) + (*fMeanValues.at(cls))(j);
312 for (
Int_t sbType=0; sbType<2; sbType++) {
313 o <<
"# PCA mean values " << std::endl;
314 const TVectorD* means = fMeanValues[sbType];
315 o << (sbType==0 ?
"Signal" :
"Background") <<
" " << means->
GetNrows() << std::endl;
317 o << std::setprecision(12) << std::setw(20) << (*means)[row];
321 o <<
"##" << std::endl;
324 for (
Int_t sbType=0; sbType<2; sbType++) {
325 o <<
"# PCA eigenvectors " << std::endl;
326 const TMatrixD* mat = fEigenVectors[sbType];
327 o << (sbType==0 ?
"Signal" :
"Background") <<
" " << mat->
GetNrows() <<
" x " << mat->
GetNcols() << std::endl;
330 o << std::setprecision(12) << std::setw(20) << (*mat)[row][col] <<
" ";
335 o <<
"##" << std::endl;
348 for (
UInt_t sbType=0; sbType<fMeanValues.size(); sbType++) {
350 const TVectorD* means = fMeanValues[sbType];
351 gTools().
AddAttr( meanxml,
"Class", (sbType==0 ?
"Signal" :(sbType==1 ?
"Background":
"Combined")) );
361 for (
UInt_t sbType=0; sbType<fEigenVectors.size(); sbType++) {
363 const TMatrixD* mat = fEigenVectors[sbType];
364 gTools().
AddAttr( evxml,
"Class", (sbType==0 ?
"Signal" :(sbType==1 ?
"Background":
"Combined") ) );
388 void* inpnode =
NULL;
404 if (nodeName ==
"Statistics") {
411 if (fMeanValues.size()<=clsIdx) fMeanValues.resize(clsIdx+1,0);
412 if (fMeanValues[clsIdx]==0) fMeanValues[clsIdx] =
new TVectorD( nrows );
413 fMeanValues[clsIdx]->ResizeTo( nrows );
416 std::stringstream s(
gTools().GetContent(ch));
417 for (
Int_t row = 0; row<nrows; row++) s >> (*fMeanValues[clsIdx])(row);
419 else if ( nodeName ==
"Eigenvectors" ) {
426 if (fEigenVectors.size()<=clsIdx) fEigenVectors.resize(clsIdx+1,0);
427 if (fEigenVectors[clsIdx]==0) fEigenVectors[clsIdx] =
new TMatrixD( nrows, ncols );
428 fEigenVectors[clsIdx]->ResizeTo( nrows, ncols );
431 std::stringstream s(
gTools().GetContent(ch));
432 for (
Int_t row = 0; row<nrows; row++)
433 for (
Int_t col = 0; col<ncols; col++)
434 s >> (*fEigenVectors[clsIdx])[row][col];
448 istr.getline(buf,512);
450 Int_t nrows(0), ncols(0);
451 UInt_t classIdx=(classname==
"signal"?0:1);
453 for (
UInt_t i=0; i<fMeanValues.size(); i++) {
454 if (fMeanValues.at(i) != 0)
delete fMeanValues.at(i);
455 if (fEigenVectors.at(i) != 0)
delete fEigenVectors.at(i);
457 fMeanValues.resize(3);
458 fEigenVectors.resize(3);
460 Log() <<
kINFO <<
"VariablePCATransform::ReadTransformationFromStream(): " <<
Endl;
462 while (!(buf[0]==
'#'&& buf[1]==
'#')) {
464 while (*p==
' ' || *p==
'\t') p++;
465 if (*p==
'#' || *p==
'\0') {
466 istr.getline(buf,512);
469 std::stringstream sstr(buf);
471 if (strvar==
"signal" || strvar==
"background") {
474 Int_t sbType = (strvar==
"signal" ? 0 : 1);
476 if (fMeanValues[sbType] == 0) fMeanValues[sbType] =
new TVectorD( nrows );
477 else fMeanValues[sbType]->ResizeTo( nrows );
480 for (
Int_t row = 0; row<nrows; row++) istr >> (*fMeanValues[sbType])(row);
484 istr.getline(buf,512);
488 istr.getline(buf,512);
489 while (!(buf[0]==
'#'&& buf[1]==
'#')) {
491 while(*p==
' ' || *p==
'\t') p++;
492 if (*p==
'#' || *p==
'\0') {
493 istr.getline(buf,512);
496 std::stringstream sstr(buf);
498 if (strvar==
"signal" || strvar==
"background") {
501 sstr >> nrows >> dummy >> ncols;
502 Int_t sbType = (strvar==
"signal" ? 0 : 1);
504 if (fEigenVectors[sbType] == 0) fEigenVectors[sbType] =
new TMatrixD( nrows, ncols );
505 else fEigenVectors[sbType]->ResizeTo( nrows, ncols );
508 for (
Int_t row = 0; row<fEigenVectors[sbType]->GetNrows(); row++) {
509 for (
Int_t col = 0; col<fEigenVectors[sbType]->GetNcols(); col++) {
510 istr >> (*fEigenVectors[sbType])[row][col];
515 istr.getline(buf,512);
517 fMeanValues[2] =
new TVectorD( *fMeanValues[classIdx] );
518 fEigenVectors[2] =
new TMatrixD( *fEigenVectors[classIdx] );
529 UInt_t nvar = fEigenVectors[0]->GetNrows();
532 UInt_t numC = fMeanValues.size();
535 fout <<
" void X2P_"<<trCounter<<
"( const double*, double*, int ) const;" << std::endl;
536 fout <<
" double fMeanValues_"<<trCounter<<
"["<<numC<<
"]["
537 << fMeanValues[0]->GetNrows() <<
"];" << std::endl;
538 fout <<
" double fEigenVectors_"<<trCounter<<
"["<<numC<<
"]["
539 << fEigenVectors[0]->GetNrows() <<
"]["
540 << fEigenVectors[0]->GetNcols() <<
"];" << std::endl;
546 if (fMeanValues[0]->GetNrows() != fMeanValues[1]->GetNrows() ||
547 fEigenVectors[0]->GetNrows() != fEigenVectors[1]->GetNrows() ||
548 fEigenVectors[0]->GetNcols() != fEigenVectors[1]->GetNcols()) {
549 Log() <<
kFATAL <<
"<MakeFunction> Mismatch in vector/matrix dimensions" <<
Endl;
556 fout <<
"//_______________________________________________________________________" << std::endl;
557 fout <<
"inline void " << fcncName <<
"::X2P_"<<trCounter<<
"( const double* x, double* p, int index ) const" << std::endl;
558 fout <<
"{" << std::endl;
559 fout <<
" // Calculate the principal components from the original data vector" << std::endl;
560 fout <<
" // x, and return it in p (function extracted from TPrincipal::X2P)" << std::endl;
561 fout <<
" // It's the users responsibility to make sure that both x and p are" << std::endl;
562 fout <<
" // of the right size (i.e., memory must be allocated for p)." << std::endl;
563 fout <<
" const int nVar = " << nvar <<
";" << std::endl;
565 fout <<
" for (int i = 0; i < nVar; i++) {" << std::endl;
566 fout <<
" p[i] = 0;" << std::endl;
567 fout <<
" for (int j = 0; j < nVar; j++) p[i] += (x[j] - fMeanValues_"<<trCounter<<
"[index][j]) * fEigenVectors_"<<trCounter<<
"[index][j][i];" << std::endl;
568 fout <<
" }" << std::endl;
569 fout <<
"}" << std::endl;
571 fout <<
"//_______________________________________________________________________" << std::endl;
572 fout <<
"inline void " << fcncName <<
"::InitTransform_"<<trCounter<<
"()" << std::endl;
573 fout <<
"{" << std::endl;
574 fout <<
" // PCA transformation, initialisation" << std::endl;
577 fout <<
" // initialise vector of mean values" << std::endl;
578 std::streamsize dp = fout.precision();
579 for (
UInt_t index=0; index<numC; index++) {
580 for (
int i=0; i<fMeanValues[index]->GetNrows(); i++) {
581 fout <<
" fMeanValues_"<<trCounter<<
"["<<index<<
"]["<<i<<
"] = " << std::setprecision(12)
582 << (*fMeanValues[index])(i) <<
";" << std::endl;
588 fout <<
" // initialise matrix of eigenvectors" << std::endl;
589 for (
UInt_t index=0; index<numC; index++) {
590 for (
int i=0; i<fEigenVectors[index]->GetNrows(); i++) {
591 for (
int j=0; j<fEigenVectors[index]->GetNcols(); j++) {
592 fout <<
" fEigenVectors_"<<trCounter<<
"["<<index<<
"]["<<i<<
"]["<<j<<
"] = " << std::setprecision(12)
593 << (*fEigenVectors[index])(i,j) <<
";" << std::endl;
597 fout << std::setprecision(dp);
598 fout <<
"}" << std::endl;
600 fout <<
"//_______________________________________________________________________" << std::endl;
601 fout <<
"inline void " << fcncName <<
"::Transform_"<<trCounter<<
"( std::vector<double>& iv, int cls ) const" << std::endl;
602 fout <<
"{" << std::endl;
603 fout <<
" // PCA transformation" << std::endl;
604 fout <<
" const int nVar = " << nvar <<
";" << std::endl;
605 fout <<
" double *dv = new double[nVar];" << std::endl;
606 fout <<
" double *rv = new double[nVar];" << std::endl;
607 fout <<
" if (cls < 0 || cls > "<<GetNClasses()<<
") {"<< std::endl;
608 fout <<
" if ("<<GetNClasses()<<
" > 1 ) cls = "<<GetNClasses()<<
";"<< std::endl;
609 fout <<
" else cls = "<<(numC==1?0:2)<<
";"<< std::endl;
610 fout <<
" }"<< std::endl;
614 fout <<
" for (int ivar=0; ivar<nVar; ivar++) dv[ivar] = iv[indicesGet.at(ivar)];" << std::endl;
617 fout <<
" // Perform PCA and put it into PCAed events tree" << std::endl;
618 fout <<
" this->X2P_"<<trCounter<<
"( dv, rv, cls );" << std::endl;
619 fout <<
" for (int ivar=0; ivar<nVar; ivar++) iv[indicesPut.at(ivar)] = rv[ivar];" << std::endl;
622 fout <<
" delete [] dv;" << std::endl;
623 fout <<
" delete [] rv;" << std::endl;
624 fout <<
"}" << std::endl;
Principal Components Analysis (PCA)
MsgLogger & Endl(MsgLogger &ml)
TVectorT< Double_t > TVectorD
TMatrixT< Double_t > TMatrixD
void Initialize(Bool_t useTMVAStyle=kTRUE)
void Print(std::ostream &o) const
print method
static RooMathCoreReg dummy