1 /**************************************************************************
2 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
4 * Author: The ALICE Off-line Project. *
5 * Contributors are mentioned in the code where appropriate. *
7 * Permission to use, copy, modify and distribute this software and its *
8 * documentation strictly for non-commercial purposes is hereby granted *
9 * without fee, provided that the above copyright notice appears in all *
10 * copies and that both the copyright notice and this permission notice *
11 * appear in the supporting documentation. The authors make no claims *
12 * about the suitability of this software for any purpose. It is *
13 * provided "as is" without express or implied warranty. *
14 **************************************************************************/
18 ///////////////////////////////////////////////////////////////////////////////
20 // Particles stack class //
21 // Implements the TMCVirtualStack of the Virtual Monte Carlo //
22 // Holds the particles transported during simulation //
23 // Is used to compare results of reconstruction with simulation //
26 ///////////////////////////////////////////////////////////////////////////////
29 #include <TObjArray.h>
30 #include <TParticle.h>
31 #include <TParticlePDG.h>
36 #include "AliModule.h"
39 #include "AliRunLoader.h"
44 //_______________________________________________________________________
57 fEventFolderName(AliConfig::GetDefaultEventFolderName())
60 // Default constructor
64 //_______________________________________________________________________
65 AliStack::AliStack(Int_t size, const char* evfoldname):
66 fParticles(new TClonesArray("TParticle",1000)),
67 fParticleMap(new TObjArray(size)),
77 fEventFolderName(evfoldname)
84 //_______________________________________________________________________
85 AliStack::AliStack(const AliStack& st):
105 //_______________________________________________________________________
106 void AliStack::Copy(TObject&) const
108 AliFatal("Not implemented!");
111 //_______________________________________________________________________
112 AliStack::~AliStack()
119 fParticles->Delete();
123 //PH??? delete fTreeK;
130 //_____________________________________________________________________________
131 void AliStack::PushTrack(Int_t done, Int_t parent, Int_t pdg, Float_t *pmom,
132 Float_t *vpos, Float_t *polar, Float_t tof,
133 TMCProcess mech, Int_t &ntr, Float_t weight, Int_t is)
136 // Load a track on the stack
138 // done 0 if the track has to be transported
140 // parent identifier of the parent track. -1 for a primary
142 // pmom momentum GeV/c
144 // polar polarisation
145 // tof time of flight in seconds
146 // mecha production mechanism
147 // ntr on output the number of the track stored
150 // const Float_t tlife=0;
153 // Here we get the static mass
154 // For MC is ok, but a more sophisticated method could be necessary
155 // if the calculated mass is required
156 // also, this method is potentially dangerous if the mass
157 // used in the MC is not the same of the PDG database
159 TParticlePDG* pmc = TDatabasePDG::Instance()->GetParticle(pdg);
161 Float_t mass = TDatabasePDG::Instance()->GetParticle(pdg)->Mass();
162 Float_t e=TMath::Sqrt(mass*mass+pmom[0]*pmom[0]+
163 pmom[1]*pmom[1]+pmom[2]*pmom[2]);
165 // printf("Loading mass %f ene %f No %d ip %d parent %d done %d pos %f %f %f mom %f %f %f kS %d m \n",
166 // mass,e,fNtrack,pdg,parent,done,vpos[0],vpos[1],vpos[2],pmom[0],pmom[1],pmom[2],kS);
169 PushTrack(done, parent, pdg, pmom[0], pmom[1], pmom[2], e,
170 vpos[0], vpos[1], vpos[2], tof, polar[0], polar[1], polar[2],
171 mech, ntr, weight, is);
173 AliWarning(Form("Particle type %d not defined in PDG Database !", pdg));
174 AliWarning("Particle skipped !");
178 //_____________________________________________________________________________
179 void AliStack::PushTrack(Int_t done, Int_t parent, Int_t pdg,
180 Double_t px, Double_t py, Double_t pz, Double_t e,
181 Double_t vx, Double_t vy, Double_t vz, Double_t tof,
182 Double_t polx, Double_t poly, Double_t polz,
183 TMCProcess mech, Int_t &ntr, Double_t weight, Int_t is)
186 // Load a track on the stack
188 // done 0 if the track has to be transported
190 // parent identifier of the parent track. -1 for a primary
192 // kS generation status code
193 // px, py, pz momentum GeV/c
194 // vx, vy, vz position
195 // polar polarisation
196 // tof time of flight in seconds
197 // mech production mechanism
198 // ntr on output the number of the track stored
200 // New method interface:
201 // arguments were changed to be in correspondence with TParticle
203 // Note: the energy is not calculated from the static mass but
204 // it is passed by argument e.
207 const Int_t kFirstDaughter=-1;
208 const Int_t kLastDaughter=-1;
211 TClonesArray &particles = *fParticles;
213 = new(particles[fLoadPoint++])
214 TParticle(pdg, is, parent, -1, kFirstDaughter, kLastDaughter,
215 px, py, pz, e, vx, vy, vz, tof);
217 particle->SetPolarisation(polx, poly, polz);
218 particle->SetWeight(weight);
219 particle->SetUniqueID(mech);
221 if(!done) particle->SetBit(kDoneBit);
223 // Declare that the daughter information is valid
224 particle->SetBit(kDaughtersBit);
225 // Add the particle to the stack
228 fParticleMap->AddAtAndExpand(particle, fNtrack);//CHECK!!
231 particle = dynamic_cast<TParticle*>(fParticleMap->At(parent));
233 particle->SetLastDaughter(fNtrack);
234 if(particle->GetFirstDaughter()<0) particle->SetFirstDaughter(fNtrack);
237 AliError(Form("Parent %d does not exist",parent));
242 // This is a primary track. Set high water mark for this event
245 // Set also number if primary tracks
246 fNprimary = fHgwmk+1;
252 //_____________________________________________________________________________
253 TParticle* AliStack::PopNextTrack(Int_t& itrack)
256 // Returns next track from stack of particles
260 TParticle* track = GetNextParticle();
264 track->SetBit(kDoneBit);
269 fCurrentTrack = track;
273 //_____________________________________________________________________________
274 TParticle* AliStack::PopPrimaryForTracking(Int_t i)
277 // Returns i-th primary particle if it is flagged to be tracked,
281 TParticle* particle = Particle(i);
283 if (!particle->TestBit(kDoneBit))
289 //_____________________________________________________________________________
290 void AliStack::PurifyKine()
293 // Compress kinematic tree keeping only flagged particles
294 // and renaming the particle id's in all the hits
297 TObjArray &particles = *fParticleMap;
298 int nkeep=fHgwmk+1, parent, i;
299 TParticle *part, *father;
300 TArrayI map(particles.GetLast()+1);
302 // Save in Header total number of tracks before compression
303 // If no tracks generated return now
304 if(fHgwmk+1 == fNtrack) return;
306 // First pass, invalid Daughter information
308 for(i=0; i<fNtrack; i++) {
309 // Preset map, to be removed later
310 if(i<=fHgwmk) map[i]=i ;
313 if((part=dynamic_cast<TParticle*>(particles.At(i)))) {
315 // Check of this track should be kept for physics reasons
316 if (KeepPhysics(part)) KeepTrack(i);
318 part->ResetBit(kDaughtersBit);
319 part->SetFirstDaughter(-1);
320 part->SetLastDaughter(-1);
324 // Invalid daughter information for the parent of the first particle
325 // generated. This may or may not be the current primary according to
326 // whether decays have been recorded among the primaries
327 part = dynamic_cast<TParticle*>(particles.At(fHgwmk+1));
328 particles.At(part->GetFirstMother())->ResetBit(kDaughtersBit);
329 // Second pass, build map between old and new numbering
330 for(i=fHgwmk+1; i<fNtrack; i++) {
331 if(particles.At(i)->TestBit(kKeepBit)) {
333 // This particle has to be kept
335 // If old and new are different, have to move the pointer
336 if(i!=nkeep) particles[nkeep]=particles.At(i);
337 part = dynamic_cast<TParticle*>(particles.At(nkeep));
339 // as the parent is always *before*, it must be already
340 // in place. This is what we are checking anyway!
341 if((parent=part->GetFirstMother())>fHgwmk)
342 if(map[parent]==-99) Fatal("PurifyKine","map[%d] = -99!\n",parent);
343 else part->SetFirstMother(map[parent]);
349 // Fix daughters information
350 for (i=fHgwmk+1; i<nkeep; i++) {
351 part = dynamic_cast<TParticle*>(particles.At(i));
352 parent = part->GetFirstMother();
354 father = dynamic_cast<TParticle*>(particles.At(parent));
355 if(father->TestBit(kDaughtersBit)) {
357 if(i<father->GetFirstDaughter()) father->SetFirstDaughter(i);
358 if(i>father->GetLastDaughter()) father->SetLastDaughter(i);
360 // Initialise daughters info for first pass
361 father->SetFirstDaughter(i);
362 father->SetLastDaughter(i);
363 father->SetBit(kDaughtersBit);
368 // Now loop on all registered hit lists
369 TList* hitLists = gAlice->GetMCApp()->GetHitLists();
370 TIter next(hitLists);
371 TCollection *hitList;
373 while((hitList = dynamic_cast<TCollection*>(next()))) {
374 TIter nexthit(hitList);
376 while((hit = dynamic_cast<AliHit*>(nexthit()))) {
377 hit->SetTrack(map[hit->GetTrack()]);
382 // This for detectors which have a special mapping mechanism
383 // for hits, such as TPC and TRD
386 TObjArray* modules = gAlice->Modules();
387 TIter nextmod(modules);
389 while((detector = dynamic_cast<AliModule*>(nextmod()))) {
390 detector->RemapTrackHitIDs(map.GetArray());
391 detector->RemapTrackReferencesIDs(map.GetArray());
394 gAlice->GetMCApp()->RemapTrackReferencesIDs(map.GetArray());
396 // Now the output bit, from fHgwmk to nkeep we write everything and we erase
397 if(nkeep>fParticleFileMap.GetSize()) fParticleFileMap.Set(Int_t (nkeep*1.5));
399 for (i=fHgwmk+1; i<nkeep; ++i) {
400 fParticleBuffer = dynamic_cast<TParticle*>(particles.At(i));
401 fParticleFileMap[i]=static_cast<Int_t>(TreeK()->GetEntries());
403 particles[i]=fParticleBuffer=0;
406 for (i=nkeep; i<fNtrack; ++i) particles[i]=0;
408 Int_t toshrink = fNtrack-fHgwmk-1;
409 fLoadPoint-=toshrink;
412 for(i=fLoadPoint; i<fLoadPoint+toshrink; ++i) fParticles->RemoveAt(i);
418 void AliStack::ReorderKine()
421 // In some transport code children might not come in a continuous sequence.
422 // In this case the stack has to be reordered in order to establish the
423 // mother daughter relation using index ranges.
425 if(fHgwmk+1 == fNtrack) return;
428 // Howmany secondaries have been produced ?
429 Int_t nNew = fNtrack - fHgwmk - 1;
433 TObjArray &particles = *fParticleMap;
436 // Copy pointers to temporary array
437 TParticle** tmp = new TParticle*[nNew];
439 for (i = 0; i < nNew; i++) {
440 if (particles.At(fHgwmk + 1 + i)) {
441 // tmp[i] = (TParticle*) (particles.At(fHgwmk + 1 + i))->Clone();
442 tmp[i] = (TParticle*) (particles.At(fHgwmk + 1 + i));
444 // if (((TParticle*) (particles.At(fHgwmk + 1 + i)))->TestBit(kKeepBit))
445 // tmp[i]->SetBit(kKeepBit);
446 // if (((TParticle*) (particles.At(fHgwmk + 1 + i)))->TestBit(kDoneBit))
447 // tmp[i]->SetBit(kDoneBit);
458 fLoadPoint = fHgwmk + 1;
460 // Re-Push particles into stack
461 // The outer loop is over parents, the inner over children.
462 // -1 refers to the primary particle
464 for (i = -1; i < nNew - 1; i++) {
468 ipa = tmp[0]->GetFirstMother();
469 parP =dynamic_cast<TParticle*>(particles.At(ipa));
471 ipa = (fHgwmk + 1 + i);
472 // Skip deleted particles
473 if (!tmp[i]) continue;
474 // Skip particles without children
475 if (tmp[i]->GetFirstDaughter() == -1) continue;
478 // Reset daughter information
479 parP->SetFirstDaughter(-1);
480 parP->SetLastDaughter(-1);
481 for (j = i + 1; j < nNew; j++) {
482 // Skip deleted particles
483 if (!tmp[j]) continue;
484 // Skip particles already handled
485 if (map1[j] != -99) continue;
486 Int_t jpa = tmp[j]->GetFirstMother();
487 // Check if daughter of current parent
489 particles[fLoadPoint] = tmp[j];
490 // Re-establish daughter information
491 parP->SetLastDaughter(fLoadPoint);
492 if (parP->GetFirstDaughter() == -1) parP->SetFirstDaughter(fLoadPoint);
493 // Set Mother information
495 tmp[j]->SetFirstMother(map1[i]);
498 map1[j] = fLoadPoint;
499 // Increase load point
508 // Build map for remapping of hits
510 TArrayI map(fNtrack);
511 for (i = 0; i < fNtrack; i ++) {
515 map[i] = map1[i - fHgwmk -1];
519 // Now loop on all registered hit lists
521 TList* hitLists = gAlice->GetMCApp()->GetHitLists();
522 TIter next(hitLists);
523 TCollection *hitList;
525 while((hitList = dynamic_cast<TCollection*>(next()))) {
526 TIter nexthit(hitList);
528 while((hit = dynamic_cast<AliHit*>(nexthit()))) {
529 hit->SetTrack(map[hit->GetTrack()]);
534 // This for detectors which have a special mapping mechanism
535 // for hits, such as TPC and TRD
538 TObjArray* modules = gAlice->Modules();
539 TIter nextmod(modules);
541 while((detector = dynamic_cast<AliModule*>(nextmod()))) {
542 detector->RemapTrackHitIDs(map.GetArray());
543 detector->RemapTrackReferencesIDs(map.GetArray());
545 gAlice->GetMCApp()->RemapTrackReferencesIDs(map.GetArray());
546 } // new particles poduced
549 Bool_t AliStack::KeepPhysics(TParticle* part)
552 // Some particles have to kept on the stack for reasons motivated
553 // by physics analysis. Decision is put here.
555 Bool_t keep = kFALSE;
557 // Keep first-generation daughter from primaries with heavy flavor
559 Int_t parent = part->GetFirstMother();
560 if (parent >= 0 && parent <= fHgwmk) {
561 TParticle* father = dynamic_cast<TParticle*>(Particles()->At(parent));
562 Int_t kf = father->GetPdgCode();
566 if (kfl > 10) kfl/=100;
568 if (kfl > 10) kfl/=10;
569 if (kfl > 10) kfl/=10;
577 //_____________________________________________________________________________
578 void AliStack::FinishEvent()
581 // Write out the kinematics that was not yet filled
584 // Update event header
588 // Fatal("FinishEvent", "No kinematics tree is defined.");
589 // Don't panic this is a probably a lego run
594 if(TreeK()->GetEntries() ==0) {
595 // set the fParticleFileMap size for the first time
596 fParticleFileMap.Set(fHgwmk+1);
599 Bool_t allFilled = kFALSE;
601 for(Int_t i=0; i<fHgwmk+1; ++i)
602 if((part=fParticleMap->At(i))) {
603 fParticleBuffer = dynamic_cast<TParticle*>(part);
604 fParticleFileMap[i]= static_cast<Int_t>(TreeK()->GetEntries());
606 //PH (*fParticleMap)[i]=fParticleBuffer=0;
608 fParticleMap->AddAt(0,i);
610 // When all primaries were filled no particle!=0
611 // should be left => to be removed later.
612 if (allFilled) AliWarning(Form("Why != 0 part # %d?\n",i));
616 // // printf("Why = 0 part # %d?\n",i); => We know.
618 // we don't break now in order to be sure there is no
619 // particle !=0 left.
620 // To be removed later and replaced with break.
621 if(!allFilled) allFilled = kTRUE;
624 //_____________________________________________________________________________
626 void AliStack::FlagTrack(Int_t track)
629 // Flags a track and all its family tree to be kept
636 particle=dynamic_cast<TParticle*>(fParticleMap->At(curr));
638 // If the particle is flagged the three from here upward is saved already
639 if(particle->TestBit(kKeepBit)) return;
641 // Save this particle
642 particle->SetBit(kKeepBit);
644 // Move to father if any
645 if((curr=particle->GetFirstMother())==-1) return;
649 //_____________________________________________________________________________
650 void AliStack::KeepTrack(Int_t track)
653 // Flags a track to be kept
656 fParticleMap->At(track)->SetBit(kKeepBit);
659 //_____________________________________________________________________________
660 void AliStack::Reset(Int_t size)
675 //_____________________________________________________________________________
676 void AliStack::ResetArrays(Int_t size)
679 // Resets stack arrays
685 fParticles = new TClonesArray("TParticle",1000);
687 fParticleMap->Clear();
688 if (size>0) fParticleMap->Expand(size);}
690 fParticleMap = new TObjArray(size);
693 //_____________________________________________________________________________
694 void AliStack::SetHighWaterMark(Int_t)
697 // Set high water mark for last track in event
702 fCurrentPrimary=fHgwmk;
703 // Set also number of primary tracks
704 fNprimary = fHgwmk+1;
708 //_____________________________________________________________________________
709 TParticle* AliStack::Particle(Int_t i)
712 // Return particle with specified ID
714 //PH if(!(*fParticleMap)[i]) {
715 if(!fParticleMap->At(i)) {
716 Int_t nentries = fParticles->GetEntriesFast();
717 // algorithmic way of getting entry index
718 // (primary particles are filled after secondaries)
719 Int_t entry = TreeKEntry(i);
720 // check whether algorithmic way and
721 // and the fParticleFileMap[i] give the same;
722 // give the fatal error if not
723 if (entry != fParticleFileMap[i]) {
725 "!! The algorithmic way and map are different: !!\n entry: %d map: %d",
726 entry, fParticleFileMap[i]));
729 TreeK()->GetEntry(entry);
730 new ((*fParticles)[nentries]) TParticle(*fParticleBuffer);
731 fParticleMap->AddAt((*fParticles)[nentries],i);
733 //PH return dynamic_cast<TParticle *>((*fParticleMap)[i]);
734 return dynamic_cast<TParticle*>(fParticleMap->At(i));
737 //_____________________________________________________________________________
738 TParticle* AliStack::ParticleFromTreeK(Int_t id) const
741 // return pointer to TParticle with label id
744 if ((entry = TreeKEntry(id)) < 0) return 0;
745 if (fTreeK->GetEntry(entry)<=0) return 0;
746 return fParticleBuffer;
749 //_____________________________________________________________________________
750 Int_t AliStack::TreeKEntry(Int_t id) const
753 // return entry number in the TreeK for particle with label id
754 // return negative number if label>fNtrack
758 entry = id+fNtrack-fNprimary;
760 entry = id-fNprimary;
764 //_____________________________________________________________________________
765 Int_t AliStack::GetCurrentParentTrackNumber() const
768 // Return number of the parent of the current track
771 TParticle* current = (TParticle*)fParticleMap->At(fCurrent);
774 return current->GetFirstMother();
776 AliWarning("Current track not found in the stack");
781 //_____________________________________________________________________________
782 Int_t AliStack::GetPrimary(Int_t id)
785 // Return number of primary that has generated track
793 parent=Particle(current)->GetFirstMother();
794 if(parent<0) return current;
798 //_____________________________________________________________________________
799 void AliStack::DumpPart (Int_t i) const
802 // Dumps particle i in the stack
805 //PH dynamic_cast<TParticle*>((*fParticleMap)[i])->Print();
806 dynamic_cast<TParticle*>(fParticleMap->At(i))->Print();
809 //_____________________________________________________________________________
810 void AliStack::DumpPStack ()
813 // Dumps the particle stack
818 printf("\n\n=======================================================================\n");
819 for (i=0;i<fNtrack;i++)
821 TParticle* particle = Particle(i);
823 printf("-> %d ",i); particle->Print();
824 printf("--------------------------------------------------------------\n");
827 Warning("DumpPStack", "No particle with id %d.", i);
830 printf("\n=======================================================================\n\n");
832 // print particle file map
833 printf("\nParticle file map: \n");
834 for (i=0; i<fNtrack; i++)
835 printf(" %d th entry: %d \n",i,fParticleFileMap[i]);
839 //_____________________________________________________________________________
840 void AliStack::DumpLoadedStack() const
843 // Dumps the particle in the stack
844 // that are loaded in memory.
847 TObjArray &particles = *fParticleMap;
849 "\n\n=======================================================================\n");
850 for (Int_t i=0;i<fNtrack;i++)
852 TParticle* particle = dynamic_cast<TParticle*>(particles[i]);
854 printf("-> %d ",i); particle->Print();
855 printf("--------------------------------------------------------------\n");
858 printf("-> %d Particle not loaded.\n",i);
859 printf("--------------------------------------------------------------\n");
863 "\n=======================================================================\n\n");
870 //_____________________________________________________________________________
871 void AliStack::CleanParents()
874 // Clean particles stack
875 // Set parent/daughter relations
878 TObjArray &particles = *fParticleMap;
881 for(i=0; i<fHgwmk+1; i++) {
882 part = dynamic_cast<TParticle*>(particles.At(i));
883 if(part) if(!part->TestBit(kDaughtersBit)) {
884 part->SetFirstDaughter(-1);
885 part->SetLastDaughter(-1);
890 //_____________________________________________________________________________
891 TParticle* AliStack::GetNextParticle()
894 // Return next particle from stack of particles
897 TParticle* particle = 0;
899 // search secondaries
900 //for(Int_t i=fNtrack-1; i>=0; i--) {
901 for(Int_t i=fNtrack-1; i>fHgwmk; i--) {
902 particle = dynamic_cast<TParticle*>(fParticleMap->At(i));
903 if ((particle) && (!particle->TestBit(kDoneBit))) {
909 // take next primary if all secondaries were done
910 while (fCurrentPrimary>=0) {
911 fCurrent = fCurrentPrimary;
912 particle = dynamic_cast<TParticle*>(fParticleMap->At(fCurrentPrimary--));
913 if ((particle) && (!particle->TestBit(kDoneBit))) {
918 // nothing to be tracked
924 //__________________________________________________________________________________________
926 TTree* AliStack::TreeK()
935 AliRunLoader *rl = AliRunLoader::GetRunLoader(fEventFolderName);
938 AliFatal(Form("Can not get RunLoader from event folder named %s",fEventFolderName.Data()));
939 return 0x0;//pro forma
941 fTreeK = rl->TreeK();
948 //don't panic - could be Lego
949 AliWarning(Form("Can not get TreeK from RL. Ev. Folder is %s",fEventFolderName.Data()));
952 return fTreeK;//never reached
954 //__________________________________________________________________________________________
956 void AliStack::ConnectTree()
959 // Creates branch for writing particles
961 AliDebug(1, "Connecting TreeK");
966 AliFatal("Parameter is NULL");//we don't like such a jokes
969 return;//in this case TreeK() calls back this method (ConnectTree)
970 //tree after setting fTreeK, the rest was already executed
971 //it is safe to return now
974 // Create a branch for particles
976 AliDebug(2, Form("Tree name is %s",fTreeK->GetName()));
978 if (fTreeK->GetDirectory())
980 AliDebug(2, Form("and dir is %s",fTreeK->GetDirectory()->GetName()));
983 AliWarning("DIR IS NOT SET !!!");
985 TBranch *branch=fTreeK->GetBranch(AliRunLoader::GetKineBranchName());
988 branch = fTreeK->Branch(AliRunLoader::GetKineBranchName(), "TParticle", &fParticleBuffer, 4000);
989 AliDebug(2, "Creating Branch in Tree");
993 AliDebug(2, "Branch Found in Tree");
994 branch->SetAddress(&fParticleBuffer);
996 if (branch->GetDirectory())
998 AliDebug(1, Form("Branch Dir Name is %s",branch->GetDirectory()->GetName()));
1001 AliWarning("Branch Dir is NOT SET");
1003 //__________________________________________________________________________________________
1006 void AliStack::BeginEvent()
1008 // start a new event
1012 //_____________________________________________________________________________
1013 void AliStack::FinishRun()
1015 // Clean TreeK information
1017 //_____________________________________________________________________________
1019 Bool_t AliStack::GetEvent()
1022 // Get new event from TreeK
1024 // Reset/Create the particle stack
1027 if (TreeK() == 0x0) //forces connecting
1029 AliError("cannot find Kine Tree for current event");
1033 Int_t size = (Int_t)TreeK()->GetEntries();
1037 //_____________________________________________________________________________
1039 void AliStack::SetEventFolderName(const char* foldname)
1041 //Sets event folder name
1042 fEventFolderName = foldname;