ITS-upgrade simulation/reconstruction code (C. Terrevoli, A. Mastroserio)
authormasera <masera@f7af4fe6-9843-0410-8265-dc069ae4e863>
Wed, 15 Dec 2010 19:05:10 +0000 (19:05 +0000)
committermasera <masera@f7af4fe6-9843-0410-8265-dc069ae4e863>
Wed, 15 Dec 2010 19:05:10 +0000 (19:05 +0000)
26 files changed:
ITS/ITSUpgradeBaseLinkDef.h [new file with mode: 0644]
ITS/ITSUpgradeRecLinkDef.h [new file with mode: 0644]
ITS/ITSUpgradeSimLinkDef.h [new file with mode: 0644]
ITS/UPGRADE/AliITSDigitUpgrade.cxx [new file with mode: 0644]
ITS/UPGRADE/AliITSDigitUpgrade.h [new file with mode: 0644]
ITS/UPGRADE/AliITSUpgradeClusterFinder.cxx [new file with mode: 0644]
ITS/UPGRADE/AliITSUpgradeClusterFinder.h [new file with mode: 0644]
ITS/UPGRADE/AliITSUpgradeClusterList.cxx [new file with mode: 0644]
ITS/UPGRADE/AliITSUpgradeClusterList.h [new file with mode: 0644]
ITS/UPGRADE/AliITSUpgradeClusterListNode.cxx [new file with mode: 0644]
ITS/UPGRADE/AliITSUpgradeClusterListNode.h [new file with mode: 0644]
ITS/UPGRADE/AliITSUpgradeReconstructor.cxx [new file with mode: 0644]
ITS/UPGRADE/AliITSUpgradeReconstructor.h [new file with mode: 0644]
ITS/UPGRADE/AliITSlayerUpgrade.cxx [new file with mode: 0644]
ITS/UPGRADE/AliITSlayerUpgrade.h [new file with mode: 0644]
ITS/UPGRADE/AliITSsegmentationUpgrade.cxx [new file with mode: 0644]
ITS/UPGRADE/AliITSsegmentationUpgrade.h [new file with mode: 0644]
ITS/UPGRADE/AliITStrackerUpgrade.cxx [new file with mode: 0644]
ITS/UPGRADE/AliITStrackerUpgrade.h [new file with mode: 0644]
ITS/UPGRADE/AliITSupgrade.cxx [new file with mode: 0644]
ITS/UPGRADE/AliITSupgrade.h [new file with mode: 0644]
ITS/UPGRADE/AliITSupgradeDigitizer.cxx [new file with mode: 0644]
ITS/UPGRADE/AliITSupgradeDigitizer.h [new file with mode: 0644]
ITS/libITSUpgradebase.pkg [new file with mode: 0644]
ITS/libITSUpgraderec.pkg [new file with mode: 0644]
ITS/libITSUpgradesim.pkg [new file with mode: 0644]

diff --git a/ITS/ITSUpgradeBaseLinkDef.h b/ITS/ITSUpgradeBaseLinkDef.h
new file mode 100644 (file)
index 0000000..8298551
--- /dev/null
@@ -0,0 +1,14 @@
+#ifdef __CINT__
+/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
+ * See cxx source for full Copyright notice                               */
+
+/* $Id: ITSbaseLinkDef.h 36856 2009-11-16 16:17:07Z masera $ */
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+// ITS upgrade classes 
+#pragma link C++ class  AliITSDigitUpgrade+;
+#pragma link C++ class  AliITSsegmentationUpgrade+;
+#endif
diff --git a/ITS/ITSUpgradeRecLinkDef.h b/ITS/ITSUpgradeRecLinkDef.h
new file mode 100644 (file)
index 0000000..7cec14d
--- /dev/null
@@ -0,0 +1,24 @@
+#ifdef __CINT__
+/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
+ * See cxx source for full Copyright notice                               */
+
+/* $Id: ITSrecLinkDef.h 38329 2010-01-17 19:17:24Z hristov $ */
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+//#pragma link C++ enum   Cluster_t;
+
+//#pragma link C++ global gITSdisplay;  // global used by AliITSdisplay
+
+// ITS upgrade classes 
+#pragma link C++ class AliITSlayerUpgrade+;
+#pragma link C++ class AliITStrackerUpgrade+;
+//#pragma link C++ class AliITSReconstructor+;
+#pragma link C++ class AliITSUpgradeReconstructor+;
+#pragma link C++ class AliITSUpgradeClusterList+;
+#pragma link C++ class AliITSUpgradeClusterListNode+;
+#pragma link C++ class AliITSUpgradeClusterFinder+;
+
+#endif
diff --git a/ITS/ITSUpgradeSimLinkDef.h b/ITS/ITSUpgradeSimLinkDef.h
new file mode 100644 (file)
index 0000000..2e360a2
--- /dev/null
@@ -0,0 +1,18 @@
+#ifdef __CINT__
+/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
+ * See cxx source for full Copyright notice                               */
+
+/* $Id: ITSsimLinkDef.h 36856 2009-11-16 16:17:07Z masera $ */
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+//#pragma link C++ enum   Cluster_t;
+
+//#pragma link C++ global gITSdisplay;  // global used by AliITSdisplay
+
+// ITS upgrade classes
+#pragma link C++ class  AliITSupgrade+;
+#pragma link C++ class  AliITSupgradeDigitizer+;
+
+#endif
diff --git a/ITS/UPGRADE/AliITSDigitUpgrade.cxx b/ITS/UPGRADE/AliITSDigitUpgrade.cxx
new file mode 100644 (file)
index 0000000..f088e47
--- /dev/null
@@ -0,0 +1,80 @@
+/**************************************************************************
+ * Copyright(c) 2004-2006, ALICE Experiment at CERN, All rights reserved. *
+ *                                                                        *
+ * Author: The ALICE Off-line Project.                                    *
+ * Contributors are mentioned in the code where appropriate.              *
+ *                                                                        *
+ * Permission to use, copy, modify and distribute this software and its   *
+ * documentation strictly for non-commercial purposes is hereby granted   *
+ * without fee, provided that the above copyright notice appears in all   *
+ * copies and that both the copyright notice and this permission notice   *
+ * appear in the supporting documentation. The authors make no claims     *
+ * about the suitability of this software for any purpose. It is          *
+ * provided "as is" without express or implied warranty.                  *
+ **************************************************************************/
+
+/* $Id$ */
+
+#include "AliITSDigitUpgrade.h"
+#include "AliITSsegmentationUpgrade.h"
+#include "AliLog.h"
+
+///////////////////////////////////////////////////////////////////
+//                                                               //
+// Class defining the digit object
+// for ITS upgrade
+// Inherits from AliDigit
+//                                                               //
+///////////////////////////////////////////////////////////////////
+
+ClassImp(AliITSDigitUpgrade)
+//______________________________________________________________________
+  AliITSDigitUpgrade::AliITSDigitUpgrade():AliDigit(),
+                                          fPixId(9999),
+                                          fSignal(0),
+                                          fNLayer(0),
+                                          fNelectrons(0)
+{for(Int_t i=0; i<3 ; i++) fSignalID[i]=-1;} //default creator
+//_______________________________________________________________________
+AliITSDigitUpgrade::AliITSDigitUpgrade(Int_t *digits): AliDigit(digits),
+                                                      fPixId(9999), 
+                                                      fSignal(0),
+                                                      fNLayer(0), 
+                                                      fNelectrons(0)
+{for(Int_t i=0; i<3 ; i++) fSignalID[i]=-1;} //standard creator digits only
+//____________________________________________________________________________________________________
+AliITSDigitUpgrade::AliITSDigitUpgrade(ULong_t pixid, Float_t eloss): AliDigit(),
+                                                                     fPixId(pixid), 
+                                                                     fSignal(eloss),
+                                                                     fNLayer(0), 
+                                                                     fNelectrons(0)
+{for(Int_t i=0; i<3 ; i++) fSignalID[i]=-1;} //standard creator digits only
+//____________________________________________________________________________________________________
+AliITSDigitUpgrade::AliITSDigitUpgrade(const AliITSDigitUpgrade &d):AliDigit(d),
+                                                                   fPixId(d.fPixId),
+                                                                   fSignal(d.fSignal),
+                                                                   fNLayer(d.fNLayer), 
+                                                                   fNelectrons(d.fNelectrons)
+{for(Int_t i=0; i<3 ; i++) fSignalID[i]=d.fSignalID[i];} //copy constructor
+//____________________________________________________________________________________________________
+void  AliITSDigitUpgrade::GetPosition(Int_t ilayer, Int_t nx, Int_t nz, Double_t &xloc, Double_t &zloc){
+  AliITSsegmentationUpgrade *s =new AliITSsegmentationUpgrade();
+  if(s->GetCellSizeX(ilayer)!=0) xloc= (nx)*(s->GetCellSizeX(ilayer))+0.5*(s->GetCellSizeX(ilayer));
+  else AliError("Upgrade segmentation not initalized");
+
+  if(s->GetCellSizeZ(ilayer)!=0)
+    zloc=(nz)*(s->GetCellSizeZ(ilayer))+0.5*(s->GetCellSizeZ(ilayer))-(s->GetHalfLength(ilayer));
+  else AliError("Upgrade segmentation not initalized");
+  delete s;
+}
+//____________________________________________________________________________________________________
+void AliITSDigitUpgrade::PrintInfo(){
+  //Standard output format for this class
+  Double_t xz[2]={-1,-1};
+  GetPosition(fNLayer,GetxPixelNumber(),GetzPixelNumber(),xz[0],xz[1]);
+   
+  AliDebug(10, Form("pixid  %10.0i (%6.3f,%6.3f) in layer %i ",(Int_t)fPixId,xz[0],xz[1],fNLayer));
+  AliDebug(10,Form(" Eloss %f  Nel %f   track ID %i   %i  %i ", fSignal, fNelectrons,fTracks[0],fTracks[1],fTracks[2]));
+  AliDebug(10,Form(" ElossID %f  %f %f  \n", fSignalID[0],fSignalID[1],fSignalID[2]));
+}
+
diff --git a/ITS/UPGRADE/AliITSDigitUpgrade.h b/ITS/UPGRADE/AliITSDigitUpgrade.h
new file mode 100644 (file)
index 0000000..00b1102
--- /dev/null
@@ -0,0 +1,83 @@
+#ifndef ALIITSDigitUpgrade_H
+#define ALIITSDigitUpgrade_H
+/* Copyright(c) 2004-2006, ALICE Experiment at CERN, All rights reserved. *
+ * See cxx source for full Copyright notice     */
+/////////////////////////////////////////////////////////////
+//              Authors A.Mastroserio                     //           
+//                     C.Terrevoli                        // 
+//                     annalisa.mastroserio@cern.ch       //
+//                     cristina.terrevoli@cern.ch         //
+//                                                        //
+//             Digit class for ITS upgrade                //
+//                                                        //
+/////////////////////////////////////////////////////////////
+
+/* $Id$ */
+
+#include <AliDigit.h>
+
+//______________________________________________________________________
+class AliITSDigitUpgrade: public AliDigit {
+
+ public:
+  AliITSDigitUpgrade();
+  AliITSDigitUpgrade(Int_t *digits);
+  AliITSDigitUpgrade(ULong_t pixid, Float_t eloss);
+  AliITSDigitUpgrade(const AliITSDigitUpgrade &d); //copy ctor
+
+  virtual ~AliITSDigitUpgrade(){/*destructor*/;}
+  //____________________________________________________________________________________________________
+    
+
+  void AddTidOffset(Int_t offset) {for(Int_t i=0; i<3; i++) if (fTracks[i]>0) fTracks[i]+=offset;} //needed for merging
+    
+  // setters
+       
+  void SetSignal(Float_t sig) {fSignal = sig;}
+  void SetLayer(Int_t layer) {fNLayer = layer;}
+  void SetNelectrons(Double_t nele) {fNelectrons = nele;}
+  void SetTrackID(Int_t tid) {fTracks[0]=tid;}
+  void SetPixId(ULong_t nx, ULong_t nz) {fPixId = 100000*nx + nz ;}
+  void SetPixId(ULong_t pixid){fPixId = pixid;}
+  void SetTids(Int_t tids[3]){ for(Int_t i=0; i<3; i++) fTracks[i]=tids[i];} // tracks participating to form the digit
+  void SetSignalID(Float_t eloss[3]){for(Int_t i=0; i< 3; i++) fSignalID[i]=eloss[i];}
+
+  // getters
+    
+  Float_t  GetSignal() const {return fSignal;}
+  Int_t    GetLayer() const {return fNLayer;}
+  Double_t GetNelectrons() const {return fNelectrons;}
+  ULong_t  GetPixId(){return fPixId;}
+  Int_t    GetxPixelNumber() const {return fPixId/100000;}
+  Int_t    GetzPixelNumber() const {return fPixId%100000;}
+    
+  void GetPosition(Int_t ilayer, Int_t nx, Int_t nz, Double_t &xloc, Double_t &zloc);
+  Float_t GetSignalID(Int_t ipart) {if(ipart<0 || ipart >2) return -1; else return fSignalID[ipart];}
+    
+  void PrintInfo(); 
+  inline Int_t   Compare     (const TObject *pObj)const;
+  Bool_t IsSortable() const {return kTRUE;}
+   
+ protected:
+    
+  ULong_t fPixId;
+  Float_t fSignal;   // Signal as Eloss in the medium
+  Int_t fNLayer;     
+  Double_t fNelectrons; 
+  Float_t fSignalID[3];
+
+    
+  ClassDef(AliITSDigitUpgrade,3)   // Simulated digit object for ITS upgrade
+
+    };
+#endif
+Int_t AliITSDigitUpgrade::Compare(const TObject *pObj) const
+{
+  // Arguments: pObj - pointer to object to compare with
+  //   Returns: -1 if AbsPad less then in pObj, 1 if more and 0 if they are the same      
+  if     (fPixId==((AliITSDigitUpgrade*)pObj)->GetPixId()) return  0;
+  else if(fPixId >((AliITSDigitUpgrade*)pObj)->GetPixId()) return  1;
+  else                                         return -1;
+}
+
+
diff --git a/ITS/UPGRADE/AliITSUpgradeClusterFinder.cxx b/ITS/UPGRADE/AliITSUpgradeClusterFinder.cxx
new file mode 100644 (file)
index 0000000..359b97d
--- /dev/null
@@ -0,0 +1,696 @@
+/**************************************************************************
+ * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
+ *                                                                        *
+ * Author: The ALICE Off-line Project.                                    *
+ * Contributors are mentioned in the code where appropriate.              *
+ *                                                                        *
+ * Permission to use, copy, modify and distribute this software and its   *
+ * documentation strictly for non-commercial purposes is hereby granted   *
+ * without fee, provided that the above copyright notice appears in all   *
+ * copies and that both the copyright notice and this permission notice   *
+ * appear in the supporting documentation. The authors make no claims     *
+ * about the suitability of this software for any purpose. It is          *
+ * provided "as is" without express or implied warranty.                  *
+ **************************************************************************/
+
+/* $Id$ */
+
+////////////////////////////////////////////////////////////////////////////
+//                                                                        //
+// Base Class used to find                                                //
+// the reconstructed points for ITS Upgrade                               // 
+//                                                                        //
+////////////////////////////////////////////////////////////////////////////
+
+#include "AliITSUpgradeClusterFinder.h"
+#include "AliITSRawStreamSPD.h"
+#include "AliLog.h"
+#include <string.h>
+#include <TObjString.h>
+
+
+AliITSUpgradeClusterFinder::AliITSUpgradeClusterFinder() : 
+  fNhitsLeft(0),
+  fOldModule(-1),
+  fClusterTypeFlag(kTRUE),
+  fFindClusterType(kFALSE),
+  fClusterTypeOrigCol(0),
+  fClusterTypeOrigRow(0),
+  fColSum(0),fRowSum(0),
+  fCharge(0),
+  fClusterWidthMaxCol(0),
+  fClusterWidthMinCol(0),
+  fClusterWidthMaxRow(0),
+  fClusterWidthMinRow(0),
+  fChargeArray(0x0)
+{ 
+  fChargeArray = new TObjArray();
+  fTmpLabel[0]=-5;
+  fTmpLabel[1]=-5;
+  fTmpLabel[2]=-5;
+   for(int il=0; il<10;il++) fLabels[il]=-5;
+}
+
+//___________________________________________________________________________________
+AliITSUpgradeClusterFinder::~AliITSUpgradeClusterFinder() {}
+//___________________________________________________________________________________
+void AliITSUpgradeClusterFinder::StartEvent() {
+  NewEvent();
+}
+//___________________________________________________________________________________
+Int_t AliITSUpgradeClusterFinder::ProcessHitOnline(Int_t layer,  UInt_t col, UInt_t row, UShort_t charge, Int_t label[3]) {
+  if(layer < 6 ) { 
+    return ProcessHit(layer,col,row, charge, label);
+  }
+  else {
+    printf("ERROR: UpgradeClusterFinder::ProcessHitOnline: Out of bounds: layer,col,row, charge = %d,%d,%d,%d\n",layer ,col,row,charge);
+    return 1;
+  }
+}
+//___________________________________________________________________________________
+Int_t AliITSUpgradeClusterFinder::ProcessHit(Int_t layer , UInt_t col, UInt_t row, UShort_t charge, Int_t label[3]) {
+  
+  if (layer>=6) {
+   printf("ERROR: UpgradeClusterFinder::ProcessHit: Out of bounds: layer ,col,row, charge, label(0,1,2)= %d,%d,%d,%d,(%d,%d,%d)\n",layer ,col,row,charge,label[0],label[1],label[2]); 
+   return 1;
+  }
+
+  // do we need to perform clustering on previous module?
+  if (fOldModule!=-1 && (Int_t)layer!=fOldModule) {
+    fChargeArray->AddLast(new TObjString(Form("%i %i %i %i %i %i",col,row,charge,label[0],label[1],label[2])));
+    DoModuleClustering(fOldModule,charge);
+    NewModule();
+  }
+  // add hit
+  fChargeArray->AddLast(new TObjString(Form("%i %i %i %i %i %i",col,row,charge,label[0],label[1],label[2])));
+
+  fOldModule=layer;
+  fHitCol[fNhitsLeft]=col;
+  fHitRow[fNhitsLeft]=row;
+  fHits[col][row]=kTRUE;
+  fTmpLabel[0]=label[0];
+  fTmpLabel[1]=label[1];
+  fTmpLabel[2]=label[2];
+  fNhitsLeft++;
+  return 0;
+}
+//___________________________________________________________________________________
+void AliITSUpgradeClusterFinder::FinishEvent() {
+  if (fNhitsLeft>0) {
+    DoModuleClustering(fOldModule,fCharge);
+  }
+}
+//___________________________________________________________________________________
+UInt_t AliITSUpgradeClusterFinder::GetClusterCount(Int_t layer) {
+  if (layer>=6) {
+    printf("ERROR: UpgradeClusterFinder::GetClusterCount: Module out of bounds: layer = %d\n",layer);
+    return 0;
+  }
+  return fClusterList[layer].GetNrEntries();
+}
+//___________________________________________________________________________________
+Float_t AliITSUpgradeClusterFinder::GetClusterMeanCol(Int_t layer, UInt_t index) {
+  if (layer>=6) {
+    printf("ERROR: UpgradeClusterFinder::GetClusterMeanCol: Module out of bounds: layer = %d\n",layer);
+    return 0;
+  }
+  return fClusterList[layer].GetColIndex(index);
+}
+//___________________________________________________________________________________
+Float_t AliITSUpgradeClusterFinder::GetClusterMeanRow(Int_t layer, UInt_t index) {
+  if (layer>=6) {
+    printf("ERROR: UpgradeClusterFinder::GetClusterMeanRow: Module out of bounds: layer = %d\n",layer);
+    return 0;
+  }
+  return fClusterList[layer].GetRowIndex(index);
+}
+//___________________________________________________________________________________
+UInt_t AliITSUpgradeClusterFinder::GetClusterSize(Int_t layer, UInt_t index) {
+  if (layer>=6) {
+    printf("ERROR: UpgradeClusterFinder::GetClusterSize: Module out of bounds: layer = %d\n",layer);
+    return 0;
+  }
+  return fClusterList[layer].GetSizeIndex(index);
+}
+//___________________________________________________________________________________
+UInt_t AliITSUpgradeClusterFinder::GetClusterWidthZ(Int_t layer, UInt_t index) {
+  if (layer>=6) {
+    printf("ERROR: UpgradeClusterFinder::GetClusterWidthZ: Module out of bounds: layer = %d\n",layer);
+    return 0;
+  }
+  return fClusterList[layer].GetWidthZIndex(index);
+}
+//___________________________________________________________________________________
+UInt_t AliITSUpgradeClusterFinder::GetClusterWidthPhi(Int_t layer, UInt_t index) {
+  if (layer>=6) {
+    printf("ERROR: UpgradeClusterFinder::GetClusterWidthPhi: Module out of bounds: layer = %d\n",layer);
+    return 0;
+  }
+  return fClusterList[layer].GetWidthPhiIndex(index);
+}
+//___________________________________________________________________________________
+UInt_t AliITSUpgradeClusterFinder::GetClusterType(Int_t layer, UInt_t index) {
+  if (layer>=6) {
+    printf("ERROR: UpgradeClusterFinder::GetClusterType: Module out of bounds: layer = %d\n",layer);
+    return 0;
+  }
+  return fClusterList[layer].GetTypeIndex(index);
+}
+//___________________________________________________________________________________
+void AliITSUpgradeClusterFinder::PrintAllClusters() {
+  for (Int_t layer=0; layer<6; layer++) {
+    PrintClusters(layer);
+  }
+}
+//___________________________________________________________________________________
+void AliITSUpgradeClusterFinder::PrintClusters(Int_t layer) {
+  if (layer>=6) {
+    printf("ERROR: UpgradeClusterFinder::PrintClusters: Out of bounds: layer = %d\n",layer);
+    return;
+  }
+  if(fClusterList[layer].GetNrEntries()==0) {
+    printf("no cluster list entries. Exiting... \n");
+    return;
+  }
+  for (UInt_t c=0; c<fClusterList[layer].GetNrEntries(); c++) {
+  printf("layer  %d , z,y=%f,%f , size=%d , type=%d labels=%d %d %d (label printout to be implemented...)\n",layer,fClusterList[layer].GetColIndex(c),fClusterList[layer].GetRowIndex(c),fClusterList[layer].GetSizeIndex(c),fClusterList[layer].GetTypeIndex(c),999,999,999);  
+}  
+}
+//___________________________________________________________________________________
+void AliITSUpgradeClusterFinder::NewEvent() {
+  for (Int_t i=0; i<6; i++) {
+    fClusterList[i].Clear();
+  }
+  NewModule();
+  fOldModule = -1;
+}
+//___________________________________________________________________________________
+void AliITSUpgradeClusterFinder::NewModule() {
+  fNhitsLeft=0;
+  memset(fHits,0,999*999*sizeof(Bool_t));
+}
+//___________________________________________________________________________________
+Int_t AliITSUpgradeClusterFinder::DoModuleClustering(Int_t Layer, UShort_t charge) {
+  UInt_t maxHits=fNhitsLeft;
+  for (UInt_t hit=0; hit<maxHits; hit++) {
+    if (fClusterTypeFlag) fFindClusterType = kTRUE;
+
+    fClusterWidthMinCol = fHitCol[hit];
+    fClusterWidthMinRow = fHitRow[hit];
+    fClusterWidthMaxCol = fHitCol[hit];
+    fClusterWidthMaxRow = fHitRow[hit];
+    
+    fClusterTypeOrigCol = fHitCol[hit];
+    fClusterTypeOrigRow = fHitRow[hit];
+    memset(fClusterTypeArea,0,kMAXCLUSTERTYPESIDEZ*kMAXCLUSTERTYPESIDEY*sizeof(Bool_t));
+    fColSum=0;
+    fRowSum=0;
+    UInt_t size = FindClusterRecu(fClusterTypeOrigCol,fClusterTypeOrigRow,charge);
+
+    if(size==1){
+      fCharge=GetPixelCharge(fColSum,fRowSum);
+      AddLabelIndex(fColSum,fRowSum);
+    }
+    if (size>0) {
+     if(size==2) printf("DoModuleClustering, size 2, labels :  %i  %i  %i \n",fLabels[0],fLabels[1],fLabels[2]);
+      fClusterList[Layer].Insert((Float_t)fColSum/size, (Float_t)fRowSum/size, size, GetClusterWidthZ(), GetClusterWidthPhi(), GetClusterType(size), fCharge,fLabels);
+      fCharge=0;
+      for(Int_t i=0; i<10; i++) fLabels[i]=-5;
+    }
+    if (fNhitsLeft==0) break;
+  }
+  return 0;
+}
+//___________________________________________________________________________________
+UInt_t AliITSUpgradeClusterFinder::FindClusterRecu(Int_t col, Int_t row, UShort_t charge) {
+  if (col<0 || !fHits[col][row]) {return 0;}
+  fHits[col][row]=kFALSE;
+  fColSum+=col;
+  fRowSum+=row;
+  fNhitsLeft--;
+  UInt_t size=1;
+
+  if (col>fClusterWidthMaxCol) fClusterWidthMaxCol = col;
+  if (col<fClusterWidthMinCol) fClusterWidthMinCol = col;
+  if (row>fClusterWidthMaxRow) fClusterWidthMaxRow = row;
+  if (row<fClusterWidthMaxRow) fClusterWidthMinRow = row;
+
+  if (fFindClusterType) {
+    Short_t diffz = fClusterTypeOrigCol - col;
+    Short_t diffy = row - fClusterTypeOrigRow;
+    if (diffz>=kMAXCLUSTERTYPESIDEZ || diffy>=kMAXCLUSTERTYPESIDEY) {
+      fFindClusterType=kFALSE;
+    }
+    else {
+      if (diffz==-1) {
+       ShiftClusterTypeArea(kSHIFTRIGHT);
+       diffz=0;
+      }
+      if (diffy==-1) {
+       ShiftClusterTypeArea(kSHIFTDOWN);
+       diffy=0;
+      }
+      fClusterTypeArea[diffz][diffy] = kTRUE;
+    }
+  }
+  // straight:
+  size+=FindClusterRecu(col  ,row-1,charge);
+  fCharge+=GetPixelCharge(col,row-1);
+  AddLabelIndex(col,row-1);
+
+  size+=FindClusterRecu(col-1,row  ,charge);
+  fCharge+=GetPixelCharge(col-1,row);
+  AddLabelIndex(col-1,row);
+
+  size+=FindClusterRecu(col  ,row+1,charge);
+  fCharge+=GetPixelCharge(col,row+1);
+  AddLabelIndex(col,row+1);
+
+  size+=FindClusterRecu(col+1,row ,charge );
+  fCharge+=GetPixelCharge(col+1,row);
+  AddLabelIndex(col+1,row);
+
+  // diagonal:
+  size+=FindClusterRecu(col-1,row-1,charge);
+  fCharge+=GetPixelCharge(col-1,row-1);
+  AddLabelIndex(col-1,row-1);
+
+  size+=FindClusterRecu(col-1,row+1,charge);
+  fCharge+=GetPixelCharge(col-1,row+1);
+  AddLabelIndex(col-1,row+1);
+
+  size+=FindClusterRecu(col+1,row-1,charge);
+  fCharge+=GetPixelCharge(col+1,row-1);
+  AddLabelIndex(col+1,row-1);
+
+  size+=FindClusterRecu(col+1,row+1,charge);
+  fCharge+=GetPixelCharge(col+1,row+1);
+  AddLabelIndex(col+1,row+1);
+
+  return size;
+}
+//___________________________________________________________________________________
+void AliITSUpgradeClusterFinder::ShiftClusterTypeArea(UInt_t direction) {
+  if (direction == kSHIFTRIGHT) {
+    fClusterTypeOrigCol++;
+    Bool_t tmpClusterTypeArea[kMAXCLUSTERTYPESIDEZ][kMAXCLUSTERTYPESIDEY];
+    memset(tmpClusterTypeArea,0,kMAXCLUSTERTYPESIDEZ*kMAXCLUSTERTYPESIDEY*sizeof(Bool_t));
+    for (UInt_t z=0; z<kMAXCLUSTERTYPESIDEZ; z++) {
+      for (UInt_t y=0; y<kMAXCLUSTERTYPESIDEY; y++) {
+       if (fClusterTypeArea[z][y]) {
+         if (z==kMAXCLUSTERTYPESIDEZ-1) {
+           fFindClusterType=kFALSE;
+           return;
+         }
+         else {
+           tmpClusterTypeArea[z+1][y] = kTRUE;
+         }
+       }
+      }
+    }
+    memcpy(fClusterTypeArea,tmpClusterTypeArea,kMAXCLUSTERTYPESIDEZ*kMAXCLUSTERTYPESIDEY*sizeof(Bool_t));
+  }
+  else if (direction == kSHIFTDOWN) {
+    fClusterTypeOrigRow--;
+    Bool_t tmpClusterTypeArea[kMAXCLUSTERTYPESIDEZ][kMAXCLUSTERTYPESIDEY];
+    memset(tmpClusterTypeArea,0,kMAXCLUSTERTYPESIDEZ*kMAXCLUSTERTYPESIDEY*sizeof(Bool_t));
+    for (UInt_t z=0; z<kMAXCLUSTERTYPESIDEZ; z++) {
+      for (UInt_t y=0; y<kMAXCLUSTERTYPESIDEY; y++) {
+       if (fClusterTypeArea[z][y]) {
+         if (y==kMAXCLUSTERTYPESIDEY-1) {
+           fFindClusterType=kFALSE;
+           return;
+         }
+         else {
+           tmpClusterTypeArea[z][y+1] = kTRUE;
+         }
+       }
+      }
+    }
+    memcpy(fClusterTypeArea,tmpClusterTypeArea,kMAXCLUSTERTYPESIDEZ*kMAXCLUSTERTYPESIDEY*sizeof(Bool_t));
+  }
+}
+
+
+
+//___________________________________________________________________________________
+UShort_t AliITSUpgradeClusterFinder::GetCharge(Int_t layer,UInt_t index ) {
+  return fClusterList[layer].GetCharge(index);
+}
+//___________________________________________________________________________________
+Int_t * AliITSUpgradeClusterFinder::GetLabels(Int_t layer,UInt_t index) {
+       return fClusterList[layer].GetLabels(index);
+}
+
+//___________________________________________________________________________________
+UInt_t AliITSUpgradeClusterFinder::GetClusterWidthZ() {
+  return fClusterWidthMaxCol-fClusterWidthMinCol+1;
+}
+//___________________________________________________________________________________
+UInt_t AliITSUpgradeClusterFinder::GetClusterWidthPhi() {
+  return fClusterWidthMaxRow-fClusterWidthMinRow+1;
+}
+//___________________________________________________________________________________
+UInt_t AliITSUpgradeClusterFinder::GetClusterType(UInt_t size) {
+  // category 'other':
+  if (!fFindClusterType || size>4) 
+    return 0;
+
+  // X
+  if (size==1) 
+    return 1;
+
+  // X
+  // X
+  if (size==2 && 
+      fClusterTypeArea[0][1] && 
+      fClusterTypeArea[0][0] ) 
+    return 2;
+
+  // XX
+  if (size==2 && 
+      fClusterTypeArea[1][0] &&
+      fClusterTypeArea[0][0] ) 
+    return 3;
+
+  // X
+  // X
+  // X
+  if (size==3 && 
+      fClusterTypeArea[0][2] && 
+      fClusterTypeArea[0][1] && 
+      fClusterTypeArea[0][0] ) 
+    return 4;
+  
+  // XX
+  // X      and equivalent...
+  if (size==3 && 
+      (
+       (
+       fClusterTypeArea[0][0] && 
+       fClusterTypeArea[0][1] && 
+       (fClusterTypeArea[1][1] || 
+        fClusterTypeArea[1][0])
+       )
+       ||
+       (
+       fClusterTypeArea[1][0] && 
+       fClusterTypeArea[1][1] && 
+       (fClusterTypeArea[0][1] || 
+        fClusterTypeArea[0][0])
+       )
+       )
+      ) 
+    return 5;
+  
+  // XXX
+  if (size==3 && 
+      fClusterTypeArea[2][0] && 
+      fClusterTypeArea[1][0] && 
+      fClusterTypeArea[0][0] )
+    return 6;
+  
+  // X
+  // X
+  // X
+  // X
+  if (size==4 &&
+      fClusterTypeArea[0][3] && 
+      fClusterTypeArea[0][2] &&
+      fClusterTypeArea[0][1] && 
+      fClusterTypeArea[0][0] ) 
+    return 7;
+  
+  // XX
+  // XX
+  if (size==4 && 
+      fClusterTypeArea[1][1] && 
+      fClusterTypeArea[1][0] && 
+      fClusterTypeArea[0][1] &&
+      fClusterTypeArea[0][0] ) 
+    return 8;
+
+  // XX
+  // X
+  // X     and equivalent...
+  if (size==4 &&
+      (
+       (
+       fClusterTypeArea[1][0] && 
+       fClusterTypeArea[1][1] && 
+       fClusterTypeArea[1][2] && 
+       fClusterTypeArea[0][0]
+       )
+       ||
+       (
+       fClusterTypeArea[1][0] && 
+       fClusterTypeArea[1][1] && 
+       fClusterTypeArea[1][2] && 
+       fClusterTypeArea[0][2]
+       )
+       ||
+       (
+       fClusterTypeArea[0][0] && 
+       fClusterTypeArea[0][1] && 
+       fClusterTypeArea[0][2] && 
+       fClusterTypeArea[1][0]
+       )
+       ||
+       (
+       fClusterTypeArea[0][0] && 
+       fClusterTypeArea[0][1] && 
+       fClusterTypeArea[0][2] && 
+       fClusterTypeArea[1][2]
+       )
+       )
+      )
+    return 9;
+
+  // X
+  // XX
+  // X     and equivalent...
+  if (size==4 &&
+      (
+       (
+       fClusterTypeArea[1][0] && 
+       fClusterTypeArea[1][1] && 
+       fClusterTypeArea[1][2] && 
+       fClusterTypeArea[0][1]
+       )
+       ||
+       (
+       fClusterTypeArea[0][0] && 
+       fClusterTypeArea[0][1] && 
+       fClusterTypeArea[0][2] && 
+       fClusterTypeArea[1][1]
+       )
+       )
+      )
+    return 10;
+
+  // X
+  // XXX    and equivalent...
+  if (size==4 &&
+      (
+       (
+       fClusterTypeArea[2][0] && 
+       fClusterTypeArea[2][1] && 
+       fClusterTypeArea[1][1] && 
+       fClusterTypeArea[0][1]
+       )
+       ||
+       (
+       fClusterTypeArea[0][0] && 
+       fClusterTypeArea[2][1] && 
+       fClusterTypeArea[1][1] && 
+       fClusterTypeArea[0][1]
+       )
+       ||
+       (
+       fClusterTypeArea[2][1] && 
+       fClusterTypeArea[2][0] && 
+       fClusterTypeArea[1][0] && 
+       fClusterTypeArea[0][0]
+       )
+       ||
+       (
+       fClusterTypeArea[0][1] && 
+       fClusterTypeArea[2][0] && 
+       fClusterTypeArea[1][0] && 
+       fClusterTypeArea[0][0]
+       )
+       )
+      )
+    return 11;
+
+  //  X
+  // XXX     and equivalent...
+  if (size==4 &&
+      (
+       (
+       fClusterTypeArea[1][0] && 
+       fClusterTypeArea[2][1] && 
+       fClusterTypeArea[1][1] && 
+       fClusterTypeArea[0][1]
+       )
+       ||
+       (
+       fClusterTypeArea[1][1] && 
+       fClusterTypeArea[2][0] && 
+       fClusterTypeArea[1][0] && 
+       fClusterTypeArea[0][0]
+       )
+       )
+      )
+    return 12;
+
+  //  X
+  // X      and equivalent...
+  if (size==2 &&
+      (
+       (
+       fClusterTypeArea[0][0] &&
+       fClusterTypeArea[1][1] 
+       )
+       ||
+       (
+       fClusterTypeArea[1][0] &&
+       fClusterTypeArea[0][1] 
+       )
+       )
+      )
+    return 13;
+
+  //  X
+  //  X
+  // X      and equivalent...
+  if (size==3 &&
+      (
+       (
+       fClusterTypeArea[0][0] &&
+       fClusterTypeArea[0][1] && 
+       fClusterTypeArea[1][2] 
+       )
+       ||
+       (
+       fClusterTypeArea[1][0] &&
+       fClusterTypeArea[1][1] && 
+       fClusterTypeArea[0][2] 
+       )
+       ||
+       (
+       fClusterTypeArea[1][0] &&
+       fClusterTypeArea[0][1] && 
+       fClusterTypeArea[0][2] 
+       )
+       ||
+       (
+       fClusterTypeArea[0][0] &&
+       fClusterTypeArea[1][1] && 
+       fClusterTypeArea[1][2] 
+       )
+       )
+      )
+    return 14;
+
+  //  XX
+  // X      and equivalent...
+  if (size==3 &&
+      (
+       (
+       fClusterTypeArea[0][0] &&
+       fClusterTypeArea[1][0] && 
+       fClusterTypeArea[2][1] 
+       )
+       ||
+       (
+       fClusterTypeArea[0][1] &&
+       fClusterTypeArea[1][1] && 
+       fClusterTypeArea[2][0] 
+       )
+       ||
+       (
+       fClusterTypeArea[0][0] &&
+       fClusterTypeArea[1][1] && 
+       fClusterTypeArea[2][1] 
+       )
+       ||
+       (
+       fClusterTypeArea[0][1] &&
+       fClusterTypeArea[1][0] && 
+       fClusterTypeArea[2][0] 
+       )
+       )
+      )
+    return 15;
+
+
+
+  return 0;
+}
+
+//___________________________________________________________________________________________________
+
+UInt_t AliITSUpgradeClusterFinder::GetPixelCharge(UInt_t col, UInt_t row){
+  Int_t q=0;
+  for(Int_t entry =0; entry < fChargeArray->GetEntries(); entry++){
+    TObjString *s = (TObjString*)fChargeArray->At(entry);
+    TString name = s->GetString();
+    if(!name.Contains(Form("%i %i",col,row)))
+      continue;
+    TObjArray *array = name.Tokenize(" ");
+    TString charge = ((TObjString*)array->At(2))->String();
+    TString rowS, colS;
+    rowS = ((TObjString*)array->At(0))->String();
+    colS = ((TObjString*)array->At(1))->String();
+    delete array;
+    q=charge.Atoi();
+    return q;
+
+  }
+  return q;
+}
+//____________________________________________________
+
+void AliITSUpgradeClusterFinder::AddLabelIndex(UInt_t col, UInt_t row){
+
+ for(Int_t entry =0; entry < fChargeArray->GetEntries(); entry++){
+    TObjString *s = (TObjString*)fChargeArray->At(entry);
+    TString name = s->GetString();
+ if(!name.Contains(Form("%i %i",col,row)))
+  continue;
+ TObjArray *array = name.Tokenize(" ");
+ TString index[3];
+ Int_t label[3];
+  for(Int_t i=0; i<3; i++){
+  index[i]=((TObjString*)array->At(3+i))->String();
+  label[i]=index[i].Atoi();
+
+  }
+ SetLabels(label);
+ delete array;
+ }
+}
+//____________________________________________________
+
+void AliITSUpgradeClusterFinder::SetLabels(Int_t label[3]){
+
+
+ Bool_t isAssigned[3]={kFALSE,kFALSE,kFALSE};
+
+ for(Int_t i=0; i<10; i++){
+  for(Int_t k=0; k<3; k++){
+   //printf(" fLabels[%i]=%i  label[%i]=%i \n",i,fLabels[i],k,label[k]);
+    if(fLabels[i]!=label[k] && label[k]>-1 && fLabels[i]<0) {
+      if(!isAssigned[k]) {
+     //  printf("assignign...\n.");
+    printf("Assignign  fLabels[%i]=%i  label[%i]=%i \n",i,fLabels[i],k,label[k]);
+        fLabels[i+k]=label[k];
+        isAssigned[k]=kTRUE;
+      }
+     }
+   }
+ }
+}
+
diff --git a/ITS/UPGRADE/AliITSUpgradeClusterFinder.h b/ITS/UPGRADE/AliITSUpgradeClusterFinder.h
new file mode 100644 (file)
index 0000000..ec4961a
--- /dev/null
@@ -0,0 +1,109 @@
+/* Copyright(c) 2004-2006, ALICE Experiment at CERN, All rights reserved. *
+ * See cxx source for full Copyright notice     */
+/////////////////////////////////////////////////////////////////////
+// Author: A.Mastroserio, C.Terrevoli                              //
+//         annalisa.mastroserio@cern.ch                            //
+//         cristina.terrevoli@ba.infn.it                           //
+// Alternative cluster finder. Usage instructions below.           //
+//                                                                 //
+//  For each event:                                                //
+//  1. Call StartEvent()                                           //
+//  2. For each pixel hit:                                         //
+//     Call ProcessHit(..) or ProcessHitOnline(..)                 //
+//  3. Call FinishEvent()                                          //
+//  4. Access cluster information for this event by methods:       //
+//     GetClusterCount(layer)                                      //
+//     GetClusterMeanCol(layer,index)                              //
+//     GetClusterMeanRow(layer,index)                              //
+//     GetClusterSize(layer,index)                                 //
+//     GetClusterType(layer,index)                                 //
+//                                                                 //
+/////////////////////////////////////////////////////////////////////
+
+/* $Id$ */
+
+#ifndef ALIITSUPGRADECLUSTERFINDER_H
+#define ALIITSUPGRADECLUSTERFINDER_H
+
+#include <Rtypes.h>
+#include "AliITSUpgradeClusterList.h"
+#include <TObjArray.h>
+
+class AliITSUpgradeClusterFinder :public TObject{
+
+ public:
+  AliITSUpgradeClusterFinder();
+  ~AliITSUpgradeClusterFinder();
+
+  void ActivateClusterTypeSearch(){fClusterTypeFlag=kTRUE;}
+  void DeActivateClusterTypeSearch(){fClusterTypeFlag=kFALSE;}
+
+  void  StartEvent();
+  Int_t ProcessHit(Int_t layer, UInt_t col, UInt_t row, UShort_t charge,Int_t label[3]);
+  Int_t ProcessHitOnline(Int_t layer, UInt_t col, UInt_t row, UShort_t charge, Int_t label[3]);
+  void  FinishEvent();
+
+  void AddLabelIndex(UInt_t col, UInt_t row);
+  void SetLabels(Int_t label[3]);
+
+  UInt_t  GetClusterCount(Int_t layer);
+  Float_t GetClusterMeanCol(Int_t layer, UInt_t index);
+  Float_t GetClusterMeanRow(Int_t layer, UInt_t index);
+  UInt_t  GetClusterSize(Int_t layer, UInt_t index);
+  UInt_t  GetClusterWidthZ(Int_t layer, UInt_t index);
+  UInt_t  GetClusterWidthPhi(Int_t layer, UInt_t index);
+  UInt_t  GetClusterType(Int_t layer, UInt_t index);
+  UShort_t GetCharge(Int_t layer, UInt_t index); 
+  UInt_t GetPixelCharge(UInt_t col, UInt_t row); 
+  Int_t* GetLabels(Int_t layer,UInt_t index) ;
+  void  PrintClusters(Int_t layer);
+  void  PrintAllClusters();
+
+ private:
+  
+  void   NewEvent();
+  void   NewModule();
+  Int_t  DoModuleClustering(Int_t Layer, UShort_t charge);
+  UInt_t FindClusterRecu(Int_t col, Int_t row, UShort_t charge);
+  void   ShiftClusterTypeArea(UInt_t direction);
+  UInt_t GetClusterType(UInt_t size);
+  UInt_t GetClusterWidthZ();
+  UInt_t GetClusterWidthPhi();
+
+  enum {kMAXCLUSTERTYPESIDEZ=3,kMAXCLUSTERTYPESIDEY=4}; // region of interest for cluster type pattern
+  enum {kSHIFTRIGHT,kSHIFTDOWN};  // used for shifting the region of interest for cluster type pattern
+  
+  UInt_t   fNhitsLeft;     // number of hits still left to process for this module
+  Bool_t   fHits[39530][39530];// hit map for this module
+  UShort_t fHitCol[999999]; // these two arrays remember which pixels are hit for this module
+  UShort_t fHitRow[999999]; // these two arrays remember which pixels are hit for this module
+  Short_t  fOldModule;     // remember previous module (-1 at start of event)
+  Bool_t   fClusterTypeFlag;   // should we classify the clusters at all
+  Bool_t   fFindClusterType;   // temporary, for classifying a cluster (pattern of pixels)
+  UShort_t fClusterTypeOrigCol;// temporary, for classifying a cluster (pattern of pixels)
+  UShort_t fClusterTypeOrigRow;// temporary, for classifying a cluster (pattern of pixels)
+  UInt_t   fColSum; // used to determine the center of a cluster
+  UInt_t   fRowSum; // used to determine the center of a cluster
+  UShort_t fCharge;        // cluster charge 
+  Int_t    fTmpLabel[3];   // label array to be kept temporarily during the clustering procedure
+  Int_t    fLabels[10];    // label array to be attached to the cluster
+
+  UShort_t fClusterWidthMaxCol;
+  UShort_t fClusterWidthMinCol;
+  UShort_t fClusterWidthMaxRow;
+  UShort_t fClusterWidthMinRow;
+  Bool_t   fClusterTypeArea[kMAXCLUSTERTYPESIDEZ][kMAXCLUSTERTYPESIDEY];// same as above comments
+  AliITSUpgradeClusterList fClusterList[8];
+  TObjArray *fChargeArray;
+
+  AliITSUpgradeClusterFinder(const AliITSUpgradeClusterFinder &source); // copy constructor
+  // assignment operator
+  AliITSUpgradeClusterFinder& operator=(const AliITSUpgradeClusterFinder &source);
+
+
+  ClassDef(AliITSUpgradeClusterFinder,1) 
+
+};
+
+
+#endif
diff --git a/ITS/UPGRADE/AliITSUpgradeClusterList.cxx b/ITS/UPGRADE/AliITSUpgradeClusterList.cxx
new file mode 100644 (file)
index 0000000..8f7e623
--- /dev/null
@@ -0,0 +1,252 @@
+/**************************************************************************
+ * Copyright(c) 2004-2006, ALICE Experiment at CERN, All rights reserved. *
+ *                                                                        *
+ * Author: The ALICE Off-line Project.                                    *
+ * Contributors are mentioned in the code where appropriate.              *
+ *                                                                        *
+ * Permission to use, copy, modify and distribute this software and its   *
+ * documentation strictly for non-commercial purposes is hereby granted   *
+ * without fee, provided that the above copyright notice appears in all   *
+ * copies and that both the copyright notice and this permission notice   *
+ * appear in the supporting documentation. The authors make no claims     *
+ * about the suitability of this software for any purpose. It is          *
+ * provided "as is" without express or implied warranty.                  *
+ **************************************************************************/
+
+//////////////////////////////////////////////////////////////////////
+// Author: A.Mastroserio, C.Terrevoli                               //
+//         annalisa.mastroserio@cern.ch                                    //
+//         cristina.terrevoli@ba.infn.it                           //
+// This class implements the use of a list of clusters.             //
+//////////////////////////////////////////////////////////////////////  
+
+/* $Id$ */
+
+#include "AliITSUpgradeClusterList.h"
+#include "AliITSUpgradeClusterListNode.h"
+
+//______________________________________________________________________________
+AliITSUpgradeClusterList::AliITSUpgradeClusterList():
+  fNrEntries(0),
+  fFirst(NULL),
+  fLast(NULL),
+  fFastAccess(kFALSE),
+  fFastAccessArray(NULL),
+  fDummyIndex(0)
+{}
+//______________________________________________________________________________
+AliITSUpgradeClusterList::AliITSUpgradeClusterList(AliITSUpgradeClusterListNode* first, UInt_t nrEntries):
+  fNrEntries(nrEntries),
+  fFirst(first),
+  fLast(NULL),
+  fFastAccess(kFALSE),
+  fFastAccessArray(NULL),
+  fDummyIndex(0)
+{
+  SetLastNode();
+}
+//______________________________________________________________________________
+AliITSUpgradeClusterList::AliITSUpgradeClusterList(const AliITSUpgradeClusterList& ilist):
+  fNrEntries(0),
+  fFirst(NULL),
+  fLast(NULL),
+  fFastAccess(kFALSE),
+  fFastAccessArray(NULL),
+  fDummyIndex(0)
+{
+  // copy constructor
+  *this = ilist;
+}
+//______________________________________________________________________________
+AliITSUpgradeClusterList::~AliITSUpgradeClusterList() {
+  Clear();
+}
+//______________________________________________________________________________
+AliITSUpgradeClusterList& AliITSUpgradeClusterList::operator=(const AliITSUpgradeClusterList& ilist) {
+  // assignment operator
+  if (this!=&ilist) {
+    this->Clear();
+    fFirst = CloneNode(ilist.fFirst);
+    SetLastNode();
+    fFastAccess=kFALSE;
+    fFastAccessArray=NULL;
+    fDummyIndex=0;
+  }
+  return *this;
+}
+//______________________________________________________________________________
+void AliITSUpgradeClusterList::Clear() {
+  // clear the whole list
+  ClearFastAccess();
+  ClearNode(fFirst);
+  fLast=fFirst;
+}
+//______________________________________________________________________________
+void AliITSUpgradeClusterList::ClearNode(AliITSUpgradeClusterListNode* &node) {
+  // clear this node and all children nodes
+  if (node==NULL) return;
+  ClearNode(node->Next());
+  delete node;
+  fNrEntries--;
+  node = NULL;
+  fFastAccess=kFALSE;
+}
+//______________________________________________________________________________
+AliITSUpgradeClusterList* AliITSUpgradeClusterList::Clone() const {
+  // returns a clone of the list
+ AliITSUpgradeClusterListNode *newFirst;
+  newFirst = CloneNode(fFirst);
+  AliITSUpgradeClusterList* newList = new AliITSUpgradeClusterList(newFirst,fNrEntries);
+  return newList;
+}
+//______________________________________________________________________________
+AliITSUpgradeClusterListNode* AliITSUpgradeClusterList::CloneNode(AliITSUpgradeClusterListNode* node) const {
+  if (node==NULL) return NULL;
+  else return new AliITSUpgradeClusterListNode(node->Col(),node->Row(),node->Size(),node->WidthZ(),node->WidthPhi(),node->Type(),node->Charge(),CloneNode(node->Next()));
+}
+//______________________________________________________________________________
+Bool_t AliITSUpgradeClusterList::Insert(Float_t col, Float_t row, UShort_t size, UShort_t widthZ, UShort_t widthPhi, UShort_t type, UShort_t charge, Int_t digLabels[10]) {
+  // insert a new node into the list (returns true if the node was not present before)
+  fNrEntries++;
+  AliITSUpgradeClusterListNode* node = new AliITSUpgradeClusterListNode(col,row,size,widthZ,widthPhi,type,charge,NULL);
+  for(Int_t i=0; i< size; i++) node->AddDigitLabel(digLabels[i]); // adding digit label to the cluster
+  if (fFirst==NULL) {
+    fFirst = node;
+  }
+  else {
+    fLast->Next() = node;
+  }
+  fLast = node;
+  return kTRUE;
+}
+//______________________________________________________________________________
+void AliITSUpgradeClusterList::SetLastNode() {
+  AliITSUpgradeClusterListNode* node = fFirst;
+  if (node==NULL) {
+    fLast = fFirst;
+  }
+  else {
+    while (1) {
+      if (node->Next()==NULL) {
+       fLast = node;
+       break;
+      }
+    }
+  }
+}
+//______________________________________________________________________________
+void AliITSUpgradeClusterList::ClearFastAccess(){
+  // clears the fast access array of pointers
+  if (fFastAccessArray!=NULL) {
+    delete [] fFastAccessArray;
+    fFastAccessArray=NULL;
+  }
+  fFastAccess=kFALSE;
+}
+//______________________________________________________________________________
+void AliITSUpgradeClusterList::InitFastAccess(){
+  // initializes the fast access array
+  if (fFastAccess) return;
+  ClearFastAccess();
+  if (fNrEntries>0) {
+    fFastAccessArray = new AliITSUpgradeClusterListNode*[fNrEntries];
+    fDummyIndex=0;
+    InitFastAccessNode(fFirst);
+    fFastAccess=kTRUE;
+  }
+}
+//______________________________________________________________________________
+void AliITSUpgradeClusterList::InitFastAccessNode(AliITSUpgradeClusterListNode* node) {
+  // initializes the fast access array starting from node (used recursively)
+  if (node==NULL) return;
+  fFastAccessArray[fDummyIndex++] = node;
+  InitFastAccessNode(node->Next());
+}
+//______________________________________________________________________________
+Float_t AliITSUpgradeClusterList::GetColIndex(UInt_t index) {
+  // returns the col of the node at position 'index' in the list
+  // returns -1 if out of bounds
+  if (index<fNrEntries) {
+    if (!fFastAccess) InitFastAccess();
+    return fFastAccessArray[index]->Col();
+  }
+  return -1;
+}
+//______________________________________________________________________________
+Float_t AliITSUpgradeClusterList::GetRowIndex(UInt_t index) {
+  // returns the row of the node at position 'index' in the list
+  // returns -1 if out of bounds
+  if (index<fNrEntries) {
+    if (!fFastAccess) InitFastAccess();
+    return fFastAccessArray[index]->Row();
+  }
+  return -1;
+}
+//______________________________________________________________________________
+UShort_t AliITSUpgradeClusterList::GetSizeIndex(UInt_t index) {
+  // returns the size of the node at position 'index' in the list
+  // returns 0 if out of bounds
+  if (index<fNrEntries) {
+    if (!fFastAccess) InitFastAccess();
+    return fFastAccessArray[index]->Size();
+  }
+  return 0;
+}
+//______________________________________________________________________________
+UShort_t AliITSUpgradeClusterList::GetWidthZIndex(UInt_t index) {
+  // returns the width z of the node at position 'index' in the list
+  // returns 0 if out of bounds
+  if (index<fNrEntries) {
+    if (!fFastAccess) InitFastAccess();
+    return fFastAccessArray[index]->WidthZ();
+  }
+  return 0;
+}
+//______________________________________________________________________________
+UShort_t AliITSUpgradeClusterList::GetWidthPhiIndex(UInt_t index) {
+  // returns the width phi of the node at position 'index' in the list
+  // returns 0 if out of bounds
+  if (index<fNrEntries) {
+    if (!fFastAccess) InitFastAccess();
+    return fFastAccessArray[index]->WidthPhi();
+  }
+  return 0;
+}
+//______________________________________________________________________________
+UShort_t AliITSUpgradeClusterList::GetTypeIndex(UInt_t index) {
+  // returns the type of the node at position 'index' in the list
+  // returns 99 if out of bounds
+  if (index<fNrEntries) {
+    if (!fFastAccess) InitFastAccess();
+    return fFastAccessArray[index]->Type();
+  }
+  return 99;
+}
+//______________________________________________________________________________
+UShort_t AliITSUpgradeClusterList::GetCharge(UInt_t index) {
+  // returns the charge of the node at position 'index' in the list
+  // returns 0 if out of bounds
+  if (index<fNrEntries) {
+  if (!fFastAccess) InitFastAccess();
+   return fFastAccessArray[index]->Charge();
+ }
+  return 0;
+}
+//______________________________________________________________________________
+Int_t * AliITSUpgradeClusterList::GetLabels(UInt_t index) {
+  // returns the charge of the node at position 'index' in the list
+  // returns 0 if out of bounds
+  if (index<fNrEntries) {
+  if (!fFastAccess) InitFastAccess();
+   return fFastAccessArray[index]->GetLabels();
+ }
+  return 0;
+}
+
+
+
+
+
+
+
+
diff --git a/ITS/UPGRADE/AliITSUpgradeClusterList.h b/ITS/UPGRADE/AliITSUpgradeClusterList.h
new file mode 100644 (file)
index 0000000..d3c1896
--- /dev/null
@@ -0,0 +1,62 @@
+#ifndef ITSUPGRADE_CLUSTER_LIST_H
+#define ITSUPGRADE_CLUSTER_LIST_H
+/* Copyright(c) 2004-2006, ALICE Experiment at CERN, All rights reserved. *
+ * See cxx source for full Copyright notice     */
+//////////////////////////////////////////////////////////////////////
+// Author: A.Mastroserio, C.Terrevoli                               //
+//         annalisa.mastroserio@cern.ch                                    //  
+//         cristina.terrevoli@ba.infn.it                            //     
+//                                                                 //                  
+//   This is class implements the use of a list of clusters.        //
+//                                                                  //
+//////////////////////////////////////////////////////////////////////  
+
+/* $Id$ */
+#include <Rtypes.h>
+
+class AliITSUpgradeClusterListNode;
+
+class AliITSUpgradeClusterList {
+
+ public:
+  AliITSUpgradeClusterList();
+ AliITSUpgradeClusterList(AliITSUpgradeClusterListNode* first,UInt_t nrEntries);
+  AliITSUpgradeClusterList(const AliITSUpgradeClusterList& ilist);
+  virtual ~AliITSUpgradeClusterList();
+  AliITSUpgradeClusterList& operator=(const AliITSUpgradeClusterList& ilist);
+
+  void                   Clear();
+  AliITSUpgradeClusterList*     Clone() const;
+ Bool_t                 Insert(Float_t col, Float_t row, UShort_t size, UShort_t widthZ, UShort_t widthPhi, UShort_t type, UShort_t charge, Int_t labels[10]);
+
+  UInt_t   GetNrEntries() const {return fNrEntries;}
+  Float_t  GetColIndex(UInt_t index);
+  Float_t  GetRowIndex(UInt_t index);
+  UShort_t GetSizeIndex(UInt_t index);
+  UShort_t GetWidthZIndex(UInt_t index);
+  UShort_t GetWidthPhiIndex(UInt_t index);
+  UShort_t GetTypeIndex(UInt_t index);
+  UShort_t GetCharge(UInt_t index);
+  Int_t *  GetLabels(UInt_t index);
+
+ private:
+  UInt_t                 fNrEntries;
+  AliITSUpgradeClusterListNode* fFirst;
+  AliITSUpgradeClusterListNode* fLast;
+
+  Bool_t                  fFastAccess;
+  AliITSUpgradeClusterListNode** fFastAccessArray;
+  UInt_t                  fDummyIndex;
+
+
+  void                   ClearNode(AliITSUpgradeClusterListNode* &node); // delete this node and all after
+  AliITSUpgradeClusterListNode* CloneNode(AliITSUpgradeClusterListNode* node) const;
+
+  void                   ClearFastAccess();
+  void                   InitFastAccess();
+  void                   InitFastAccessNode(AliITSUpgradeClusterListNode* node);
+  void                   SetLastNode();
+
+};
+
+#endif
diff --git a/ITS/UPGRADE/AliITSUpgradeClusterListNode.cxx b/ITS/UPGRADE/AliITSUpgradeClusterListNode.cxx
new file mode 100644 (file)
index 0000000..47979b6
--- /dev/null
@@ -0,0 +1,91 @@
+/**************************************************************************
+ * Copyright(c) 2004-2006, ALICE Experiment at CERN, All rights reserved. *
+ *                                                                        *
+ * Author: The ALICE Off-line Project.                                    *
+ * Contributors are mentioned in the code where appropriate.              *
+ *                                                                        *
+ * Permission to use, copy, modify and distribute this software and its   *
+ * documentation strictly for non-commercial purposes is hereby granted   *
+ * without fee, provided that the above copyright notice appears in all   *
+ * copies and that both the copyright notice and this permission notice   *
+ * appear in the supporting documentation. The authors make no claims     *
+ * about the suitability of this software for any purpose. It is          *
+ * provided "as is" without express or implied warranty.                  *
+ **************************************************************************/
+
+/* $Id$ */
+
+//////////////////////////////////////////////////////////////////////
+// Author:A.Mastroserio C.Terrevoli                                 //
+//        annalisa.mastroserio@cern.ch                              //
+//        cristina.terrevoli@ba.infn.it                             //
+//                                                                  //
+// Implementation of the nodes to put in the cluster list           //
+//                                                                 //
+//////////////////////////////////////////////////////////////////////   
+
+#include "AliITSUpgradeClusterListNode.h"
+
+AliITSUpgradeClusterListNode::AliITSUpgradeClusterListNode():
+  fCol(0),
+  fRow(0),
+  fSize(0),
+  fWidthZ(0),
+  fWidthPhi(0),
+  fType(0),
+  fCharge(0),
+  fLastDigitLabel(0),
+  fNext(NULL)
+{
+for(Int_t i=0; i < 10; i++) fDigitLabel[i]=-2;
+}
+
+AliITSUpgradeClusterListNode::AliITSUpgradeClusterListNode(Float_t col, Float_t row, UShort_t size, UShort_t widthZ, UShort_t widthPhi, UShort_t type, UShort_t charge, AliITSUpgradeClusterListNode* next):
+  fCol(col),
+  fRow(row),
+  fSize(size),
+  fWidthZ(widthZ),
+  fWidthPhi(widthPhi),
+  fType(type),
+  fCharge(charge),
+  fLastDigitLabel(0),
+  fNext(next)
+{
+for(Int_t i=0; i < 10; i++) fDigitLabel[i]=-2;
+
+}
+
+AliITSUpgradeClusterListNode::AliITSUpgradeClusterListNode(const AliITSUpgradeClusterListNode& obj):
+  fCol(obj.fCol),
+  fRow(obj.fRow),
+  fSize(obj.fSize),
+  fWidthZ(obj.fWidthZ),
+  fWidthPhi(obj.fWidthPhi),
+  fType(obj.fType),
+  fCharge(obj.fCharge),
+  fLastDigitLabel(obj.fLastDigitLabel),
+  fNext(obj.fNext)
+{
+  // copy constructor
+for(Int_t i=0; i> 1000; i++) fDigitLabel[i]=obj.fDigitLabel[i];
+}
+
+AliITSUpgradeClusterListNode::~AliITSUpgradeClusterListNode() 
+{}
+
+AliITSUpgradeClusterListNode& AliITSUpgradeClusterListNode::operator=(const AliITSUpgradeClusterListNode& obj) 
+{
+  // assignment operator
+  if (this!=&obj) {
+    fCol = obj.fCol;
+    fRow = obj.fRow;
+    fSize = obj.fSize;
+    fWidthZ = obj.fWidthZ;
+    fWidthPhi = obj.fWidthPhi;
+    fType = obj.fType;
+    fCharge = obj.fCharge;
+    fNext = obj.fNext;
+  }
+  return *this;
+}
+
diff --git a/ITS/UPGRADE/AliITSUpgradeClusterListNode.h b/ITS/UPGRADE/AliITSUpgradeClusterListNode.h
new file mode 100644 (file)
index 0000000..23641ae
--- /dev/null
@@ -0,0 +1,64 @@
+#ifndef ITSUPGRADE_CLUSTER_LISTNODE_H
+#define ITSUPGRADE_CLUSTER_LISTNODE_H
+/* Copyright(c) 2004-2006, ALICE Experiment at CERN, All rights reserved. *
+ * See cxx source for full Copyright notice     */
+////////////////////////////////////////////////////////////////////////
+// Author:A.Mastroserio C.Terrevoli                                  //        
+//        annalisa.mastroserio@cern.ch                               //        
+//        cristina.terrevoli@ba.infn.it                                      //
+//                                                                   //        
+//  Class for the nodes to put in the cluster list                   //
+//                                                                    //
+////////////////////////////////////////////////////////////////////////  
+
+/* $Id$ */
+
+#include <Rtypes.h>
+
+class AliITSUpgradeClusterListNode {
+
+ public:
+ AliITSUpgradeClusterListNode();
+  AliITSUpgradeClusterListNode(Float_t col, Float_t row, UShort_t size, UShort_t widthZ, UShort_t widthPhi, UShort_t type,UShort_t charge,AliITSUpgradeClusterListNode* next);
+  AliITSUpgradeClusterListNode(const AliITSUpgradeClusterListNode& obj);
+  virtual ~AliITSUpgradeClusterListNode();
+  AliITSUpgradeClusterListNode& operator=(const AliITSUpgradeClusterListNode& obj);
+
+  Float_t  Col() const {return fCol;}
+  Float_t  Row() const {return fRow;}
+  UShort_t Size() const {return fSize;}
+  UShort_t WidthZ() const {return fWidthZ;}
+  UShort_t WidthPhi() const {return fWidthPhi;}
+  UShort_t Type() const {return fType;}
+  UShort_t Charge() const {return fCharge;}
+  AliITSUpgradeClusterListNode*& Next() {return fNext;}
+
+  void       SetCol(Float_t val) {fCol=val;}
+  void       SetRow(Float_t val) {fRow=val;}
+  void       SetSize(UShort_t val) {fSize=val;}
+  void       SetWidthZ(UShort_t val) {fWidthZ=val;}
+  void       SetWidthPhi(UShort_t val) {fWidthPhi=val;}
+  void       SetType(UShort_t val) {fType=val;}
+  void       SetNext(AliITSUpgradeClusterListNode* obj) {fNext = obj;}
+  void       AddDigitLabel(Int_t label){fDigitLabel[fLastDigitLabel]=label; fLastDigitLabel++;}
+  Int_t      GetLastIndex() {return fLastDigitLabel;}
+  Int_t*     GetLabels() {return fDigitLabel;}
+
+
+
+ private:
+  Float_t  fCol;
+  Float_t  fRow;
+  UShort_t fSize;
+  UShort_t fWidthZ;
+  UShort_t fWidthPhi;
+  UShort_t fType;
+  UShort_t fCharge;
+  Int_t  fLastDigitLabel;   // last meaningful position in fDigitLabel
+  AliITSUpgradeClusterListNode* fNext;
+  Int_t  fDigitLabel[10]; // needed to attach MC truth to the cluster
+};
+
+#endif
+
diff --git a/ITS/UPGRADE/AliITSUpgradeReconstructor.cxx b/ITS/UPGRADE/AliITSUpgradeReconstructor.cxx
new file mode 100644 (file)
index 0000000..3d269df
--- /dev/null
@@ -0,0 +1,373 @@
+/**************************************************************************
+ * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
+ *                                                                        *
+ * Author: The ALICE Off-line Project.                                    *
+ * Contributors are mentioned in the code where appropriate.              *
+ *                                                                        *
+ * Permission to use, copy, modify and distribute this software and its   *
+ * documentation strictly for non-commercial purposes is hereby granted   *
+ * without fee, provided that the above copyright notice appears in all   *
+ * copies and that both the copyright notice and this permission notice   *
+ * appear in the supporting documentation. The authors make no claims     *
+ * about the suitability of this software for any purpose. It is          *
+ * provided "as is" without express or implied warranty.                  *
+ **************************************************************************/
+
+/* $Id$ */
+
+//.
+// ITSupgrade base class to reconstruct an event
+//.
+//.
+//.
+#include "TObjArray.h"
+#include "TTree.h"
+#include "AliITSRecPoint.h"
+#include "AliITSReconstructor.h"
+#include "AliITSupgrade.h"
+#include "AliITSUpgradeReconstructor.h" //class header
+#include "AliITSDetTypeRec.h"
+#include "AliITS.h"              //Reconstruct() 
+#include "AliCDBEntry.h"           //ctor
+#include "AliCDBManager.h"         //ctor
+#include "AliESDEvent.h"           //FillEsd()
+#include "AliRawReader.h"          //Reconstruct() for raw digits
+#include "AliRun.h"
+#include "AliLog.h"                //
+#include "AliITSRawStream.h"     //ConvertDigits()
+#include "AliRunLoader.h" 
+#include "AliDataLoader.h"
+#include "AliITSLoader.h"
+#include "AliITSsegmentationUpgrade.h"
+#include "AliITSUpgradeClusterFinder.h"
+#include "AliITStrackerUpgrade.h"
+#include "AliStack.h"
+#include "TFile.h"
+#include "TNtupleD.h"
+ClassImp(AliITSUpgradeReconstructor)
+
+//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+  AliITSUpgradeReconstructor::AliITSUpgradeReconstructor():
+    AliITSReconstructor(), 
+    fRecPoints(0),
+    fNRecPoints(0),
+    fDigits(0)
+
+{
+  //
+  //ctor
+  //
+  fRecPoints = new TClonesArray("AliITSRecPoint",3000);
+  fNRecPoints = 0;
+  fDigits = new TObjArray(6);
+
+
+
+
+}//AliITSReconstructor
+//-----------------------------------------------------------------------
+AliITSUpgradeReconstructor::~AliITSUpgradeReconstructor(){
+  //Destructor
+  if(fDigits){
+    fDigits->Delete();
+    delete fDigits;
+    fDigits=0;
+  }
+  if(fRecPoints){
+    fRecPoints->Delete();
+    delete fRecPoints;
+    fRecPoints=0;
+  }
+}
+
+//_________________________________________________________________
+void AliITSUpgradeReconstructor::Init() {
+  // Initalize this constructor bet getting/creating the objects
+  // nesseary for a proper ITS reconstruction.
+  // Inputs:
+  //   none.
+  // Output:
+  //   none.
+  // Return:
+  //   none.
+  return;
+}
+
+//___________________________________________________________________________
+void AliITSUpgradeReconstructor::SetTreeAddressD(TTree* const treeD){
+
+  // Set branch address for the tree of digits.
+
+  TBranch *branch;
+  Int_t i;
+  char branchname[30];
+  if(!treeD) return;
+  if (fDigits == 0x0) fDigits = new TObjArray(6);
+  for (i=0; i<6; i++) {
+    if(!(fDigits->At(i))) {
+      fDigits->AddAt(new TClonesArray("AliITSDigitUpgrade",1000),i);
+    }
+    else{
+      ResetDigits(i);
+    }
+    sprintf(branchname,"ITSDigits%d",i+1); 
+    if (fDigits) {
+      branch = treeD->GetBranch(branchname);
+      if (branch) branch->SetAddress(&((*fDigits)[i]));
+    }
+  }
+}
+//__________________________________________________________________
+void AliITSUpgradeReconstructor::SetTreeAddressR(TTree* const treeR){
+  // Set branch address for the Reconstructed points Trees.
+  // Inputs:
+  //      TTree *treeR   Tree containing the RecPoints.
+  // Outputs:
+  //      none.
+  // Return:
+  char branchname[30];
+  Char_t namedet[30]="ITS";
+       
+  if(!treeR) return;
+  if(fRecPoints==0x0){
+    fRecPoints = new TClonesArray("AliITSRecPoint",1000);
+  }
+       
+  TBranch *branch;
+  sprintf(branchname,"%sRecPoints",namedet);
+  branch = treeR->GetBranch(branchname);
+       
+  if (branch) {
+    branch->SetAddress(&fRecPoints);
+  }
+  else {
+    sprintf(branchname,"%sRecPointsF",namedet); 
+    branch = treeR->GetBranch(branchname);
+    if (branch) {
+      branch->SetAddress(&fRecPoints);
+    }
+  }
+
+}
+//_________________________________________________________________________
+TBranch* AliITSUpgradeReconstructor::MakeBranchInTree(TTree* const tree,
+                                                     const char* name, const char *classname,
+                                                     void* address,Int_t size,Int_t splitlevel)
+{
+  //
+  // Makes branch in given tree and diverts them to a separate file
+  // 
+  //
+  //
+
+  if (tree == 0x0) {
+    Error("MakeBranchInTree","Making Branch %s Tree is NULL",name);
+    return 0x0;
+  }
+  TBranch *branch = tree->GetBranch(name);
+  if (branch) {
+    return branch;
+  }
+  if (classname){
+    branch = tree->Branch(name,classname,address,size,splitlevel);
+  }
+  else {
+    branch = tree->Bronch(name, "TClonesArray", address, size, splitlevel);
+  }
+
+  return branch;
+}
+//________________________________________________________________________
+
+
+void AliITSUpgradeReconstructor::MakeBranch(TTree* tree, Option_t* option){
+
+  //Creates branches for clusters and recpoints
+  Bool_t cR = (strstr(option,"R")!=0);
+  Bool_t cRF = (strstr(option,"RF")!=0);
+
+  if(cRF)cR = kFALSE;
+
+  if(cR) MakeBranchR(tree);
+  if(cRF) MakeBranchRF(tree);
+
+}
+
+//_________________________________________________________________
+void AliITSUpgradeReconstructor::MakeBranchR(TTree *treeR, Option_t *opt){
+  //Creates tree branches for recpoints
+  // Inputs:
+  //      cont char *file  File name where RecPoints branch is to be written
+  //                       to. If blank it write the SDigits to the same
+  //                       file in which the Hits were found.
+
+  Int_t buffsz = 4000;
+  char branchname[30];
+  Bool_t oFast= (strstr(opt,"Fast")!=0);
+  Char_t detname[30] = "ITS";
+
+  if(oFast){
+    sprintf(branchname,"%sRecPointsF",detname);
+  } else {
+    sprintf(branchname,"%sRecPoints",detname);
+  }
+
+  if(!fRecPoints)fRecPoints = new TClonesArray("AliITSRecPoint",1000);
+  if (treeR)
+    MakeBranchInTree(treeR,branchname,0,&fRecPoints,buffsz,99);
+}
+
+//_____________________________________________________________________
+void AliITSUpgradeReconstructor::ResetDigits(){
+  // Reset number of digits and the digits array for the ITS detector.
+
+  if(!fDigits) return;
+  for(Int_t i=0;i<6;i++){
+    ResetDigits(i);
+  }
+}
+//____________________________________________________________________
+void AliITSUpgradeReconstructor::ResetDigits(Int_t branch){
+  // Reset number of digits and the digits array for this branch.
+
+  if(fDigits->At(branch)) ((TClonesArray*)fDigits->At(branch))->Clear();
+
+}
+//________________________________________________________________
+void AliITSUpgradeReconstructor::AddRecPoint(const AliITSRecPoint &r){
+  // Add a reconstructed space point to the list
+  // Inputs:
+  //      const AliITSRecPoint &r RecPoint class to be added to the tree
+  //                              of reconstructed points TreeR.
+  // Outputs:
+  //      none.
+  // Return:
+  //      none.
+
+  TClonesArray &lrecp = *fRecPoints;
+  new(lrecp[fNRecPoints++]) AliITSRecPoint(r);
+}
+
+//___________________________________________________________________
+void AliITSUpgradeReconstructor::DigitsToRecPoints(TTree *treeD,TTree *treeR){
+  AliITSsegmentationUpgrade *segmentation2 = 0x0;
+  AliITSRecPoint  recpnt; 
+  if(!segmentation2)
+  segmentation2 = new AliITSsegmentationUpgrade();
+  AliITSUpgradeClusterFinder *clf = new AliITSUpgradeClusterFinder();
+  TObjArray *digList= new TObjArray(6);
+  for(Int_t il=0; il<6; il ++) digList->AddAt(new TClonesArray("AliITSDigitUpgrade"),il);
+  for(Int_t ilayer=0; ilayer<6; ilayer ++) {
+    treeD->SetBranchAddress(Form("Layer%d",ilayer),&(*digList)[ilayer]);
+    //treeD->GetListOfLeaves()->Print();       
+  }//loop layer per tbranch
+  treeD->GetEntry(0);
+               
+  for(Int_t ilayer=0; ilayer < 6 ;ilayer ++){
+    TClonesArray *pArrDig= (TClonesArray*)digList->At(ilayer);
+    clf->StartEvent();
+    for(Int_t ientr =0; ientr < pArrDig->GetEntries() ; ientr++){
+      AliITSDigitUpgrade *dig = (AliITSDigitUpgrade*)pArrDig->At(ientr);
+      Int_t colz=dig->GetzPixelNumber();
+      Int_t rowx=dig->GetxPixelNumber();
+      Double_t hitcharge= (dig->GetNelectrons());
+      clf->ProcessHitOnline(ilayer,colz, rowx,(Short_t)hitcharge,dig->GetTracks());
+
+
+    }//ientr
+    clf->FinishEvent();
+    for(UInt_t nClu = 0; nClu <  clf -> GetClusterCount(ilayer); nClu++){
+      UShort_t charge = clf->GetCharge(ilayer, nClu);
+      recpnt.SetQ(charge);
+      recpnt.SetLayer(ilayer);
+      Int_t *lab=clf->GetLabels(ilayer,nClu);
+for(Int_t l=0; l<3; l++) {
+                        recpnt.SetLabel(lab[l],l);
+                        }
+if(clf->GetClusterSize(ilayer,nClu)==2){
+                        printf("\n\n CLUSTER LABELS (size %i) \n",clf->GetClusterSize(ilayer,nClu));
+                        for(Int_t i=0; i<10; i++ ){
+                         printf(" %i ",lab[i]);
+                         }
+                        printf("\n\n");
+                       }
+
+
+                       
+      Bool_t check2;
+      Double_t xcheck2=0.;
+      Double_t ycheck2=0.;
+      Double_t zcheck2=0.;
+      Double_t xzl2[2]={0.,0.};
+      Double_t XpixC2,ZpixC2=0.;
+
+      XpixC2 = clf-> GetClusterMeanRow(ilayer, nClu);
+      ZpixC2 = clf-> GetClusterMeanCol(ilayer, nClu);
+      xzl2[0] = XpixC2*(segmentation2->GetCellSizeX(ilayer))+0.5*(segmentation2-> GetCellSizeX(ilayer));
+      xzl2[1] = ZpixC2*(segmentation2->GetCellSizeZ(ilayer))+0.5*(segmentation2->GetCellSizeZ(ilayer))-(segmentation2->GetHalfLength(ilayer));
+      check2 = segmentation2->DetToGlobal(ilayer,xzl2[0], xzl2[1],xcheck2,ycheck2,zcheck2);
+      recpnt.SetType(clf->GetClusterType(ilayer,nClu ));
+    // recpnt.SetLocalCoord(xzl2[0],xzl2[1]); //temporary solution (no LocalToTrack Matrix)
+         //from global to tracking system coordinate
+       // global coordinate -> local coordinate getting alpha angle of the recpoint
+              Float_t xclg = xcheck2;//upgrade clusters global coordinate ( ITS official: GetX tracking coordinate)
+              Float_t yclg = ycheck2;
+              Float_t zclg = zcheck2;
+              Double_t phiclu1rad, phiclu1deg;
+              phiclu1rad=TMath::ATan2(yclg,xclg);//cluster phi angle (rad)
+              if (phiclu1rad<0) phiclu1rad+=TMath::TwoPi();//from 0 to 360
+              else if (phiclu1rad>=TMath::TwoPi()) phiclu1rad-=TMath::TwoPi();//
+
+              phiclu1deg=180.*phiclu1rad/TMath::Pi();// in deg
+              Int_t ladder;// virtual segmentation starting from the cluster phi
+
+              ladder=(Int_t)phiclu1deg/18;// in which ladder the cluster is
+              Double_t alpha= (ladder*18.+9.)*TMath::Pi()/180.;//angle at the center of the ladder (rad)
+
+              //alpha rotation 
+              Float_t xclu1_tr = xclg*TMath::Cos(alpha)-yclg*TMath::Sin(alpha);
+              Float_t yclu1 = yclg*TMath::Cos(alpha)+xclg*TMath::Sin(alpha);
+              Float_t xclu1 = TMath::Sqrt(xclu1_tr*xclu1_tr+yclu1*yclu1);
+              Float_t zclu1 = zclg;
+              Double_t phi_trk= (phiclu1rad-alpha);// cluster angle in the rotated system (rad)
+
+              yclu1=xclu1*phi_trk; // tracking system coordinate: r*phi
+      recpnt.SetX(0.);
+      recpnt.SetY(yclu1);
+      recpnt.SetZ(zclu1);
+      //  
+      Double_t xsize, zsize;
+      segmentation2->GetSegmentation(ilayer,xsize, zsize);
+      recpnt.SetSigmaY2(xsize/TMath::Sqrt(12)*xsize/TMath::Sqrt(12));
+      recpnt.SetSigmaZ2(zsize/TMath::Sqrt(12)*zsize/TMath::Sqrt(12));
+      TClonesArray &lrecp = *fRecPoints;
+      new(lrecp[fNRecPoints++]) AliITSRecPoint(recpnt);
+    }//cluster list entries
+    treeR->Fill();
+    ResetRecPoints();
+  }//ilayer
+}
+//_______________________________________________________________________________________________________________
+AliTracker* AliITSUpgradeReconstructor::CreateTracker() const
+{
+        // create a ITS tracker
+   //     Int_t trackerOpt = GetRecoParam()->GetTracker();
+    //    AliTracker* tracker;
+
+      //          tracker = new AliITStrackerUpgrade();
+                AliITStrackerUpgrade *trackUp = new AliITStrackerUpgrade();
+                if(GetRecoParam()->GetTrackerSAOnly()) trackUp->SetSAFlag(kTRUE);
+                if(trackUp->GetSAFlag())AliDebug(1,"Tracking Performed in ITS only\n");
+                if(GetRecoParam()->GetInwardFindingSA()){
+                        trackUp->SetInwardFinding();
+                        trackUp->SetInnerStartLayer(GetRecoParam()->GetInnerStartLayerSA());
+                }else{
+                        trackUp->SetOutwardFinding();
+                        trackUp->SetOuterStartLayer(GetRecoParam()->GetOuterStartLayerSA());
+                }
+                trackUp->SetMinNPoints(GetRecoParam()->GetMinNPointsSA());
+                return trackUp;
+}
+
+
+
diff --git a/ITS/UPGRADE/AliITSUpgradeReconstructor.h b/ITS/UPGRADE/AliITSUpgradeReconstructor.h
new file mode 100644 (file)
index 0000000..f82f8ea
--- /dev/null
@@ -0,0 +1,62 @@
+#ifndef ALIITSUPGRADERECONSTRUCTOR_H
+#define ALIITSUPGRADERECONSTRUCTOR_H
+/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
+ * See cxx source for full Copyright notice                               */
+
+/* $Id$ */
+
+//.
+// ITS upgrade  base class to reconstruct an event
+//.
+#include "AliITSReconstructor.h"        //base class
+#include "AliITSDigitUpgrade.h"           //Dig2Clu(), UseDig()
+#include "AliITSsegmentationUpgrade.h"
+#include "AliRunLoader.h"
+#include "AliRun.h"
+#include "AliStack.h"
+#include "AliITSUpgradeClusterFinder.h"
+#include "AliITSRecoParam.h"
+#include <TMatrixF.h>                //UseDig()
+#include <TFile.h>
+#include <TNtupleD.h>
+#include <TClonesArray.h>            //UseDig()
+#include <TObjArray.h>               //SigConv()
+class AliRawReader;                  //Reconstruct() with raw data   
+class AliITSRecPoint;
+class AliITSUpgradeReconstructor: public AliITSReconstructor
+{ 
+ public:
+  AliITSUpgradeReconstructor();               
+  virtual ~AliITSUpgradeReconstructor();                    //dtor  
+  virtual void Init();
+
+  virtual void SetTreeAddressD(TTree* const treeD); 
+  void SetTreeAddressR(TTree* const treeR);
+  void AddRecPoint(const AliITSRecPoint &p);
+  TBranch*  MakeBranchInTree(TTree* const tree,const char* name, const char *classname,void* address,Int_t size,Int_t splitlevel);
+               
+  virtual void ResetDigits(); 
+  virtual void ResetDigits(Int_t branch);
+  void MakeBranchRF(TTree *treeR){MakeBranchR(treeR,"Fast");} 
+  void DigitsToRecPoints(TTree *treeD,TTree *treeR);
+  void MakeBranchR(TTree *treeR,Option_t *opt=" ");
+  void ResetRecPoints(){if(fRecPoints) fRecPoints->Clear();fNRecPoints = 0;};
+  virtual void MakeBranch(TTree *tree,Option_t *opt);
+  virtual AliTracker*  CreateTracker() const;
+ private:
+  AliITSUpgradeReconstructor(const AliITSUpgradeReconstructor&);              //Not implemented
+  AliITSUpgradeReconstructor &operator=(const AliITSUpgradeReconstructor&);   //Not implemented
+  TClonesArray *fRecPoints;  //! List of reconstructed points
+  Int_t         fNRecPoints; // Number of rec points
+  TObjArray    *fDigits;     
+
+
+  //TString fmemberToWriteLater;
+  //  
+  ClassDef(AliITSUpgradeReconstructor, 1)        // class for the ITS reconstruction
+    };
+
+
+#endif
+
+
diff --git a/ITS/UPGRADE/AliITSlayerUpgrade.cxx b/ITS/UPGRADE/AliITSlayerUpgrade.cxx
new file mode 100644 (file)
index 0000000..3fd9640
--- /dev/null
@@ -0,0 +1,107 @@
+/**************************************************************************
+ * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
+ *                                                                        *
+ * Author: The ALICE Off-line Project.                                    *
+ * Contributors are mentioned in the code where appropriate.              *
+ *                                                                        *
+ * Permission to use, copy, modify and distribute this software and its   *
+ * documentation strictly for non-commercial purposes is hereby granted   *
+ * without fee, provided that the above copyright notice appears in all   *
+ * copies and that both the copyright notice and this permission notice   *
+ * appear in the supporting documentation. The authors make no claims     *
+ * about the suitability of this software for any purpose. It is          *
+ * provided "as is" without express or implied warranty.                  *
+ **************************************************************************/
+
+/* $Id$ */
+
+#include <Riostream.h>
+#include <TMath.h>
+#include <AliITSlayerUpgrade.h>
+#include <AliITStrackerMI.h>
+
+AliITSlayerUpgrade::AliITSlayerUpgrade():
+  fPhiOffset(0.),
+  fZOffset(0.),
+  fNsel(0),
+  fN(0)
+{  //--------------------------------------------------------------------
+  //default AliITSlayerUpgrade constructor
+  //--------------------------------------------------------------------
+}
+//___________________________________________________________________________
+AliITSlayerUpgrade::AliITSlayerUpgrade(Double_t p,Double_t z):
+  fPhiOffset(p),
+  fZOffset(z),
+  fNsel(0),
+  fN(0)
+{
+  //--------------------------------------------------------------------
+  //main AliITSlayerUpgrade constructor
+  //--------------------------------------------------------------------
+
+  for (Int_t i=0; i<AliITSRecoParam::fgkMaxClusterPerLayer; i++) fClusters[i]=0;
+
+}
+
+AliITSlayerUpgrade::~AliITSlayerUpgrade() {
+  //--------------------------------------------------------------------
+  // AliITSlayerUpgrade destructor
+  //--------------------------------------------------------------------
+//for (Int_t i=0; i<fN; i++) delete fClusters[i];
+cout<< " AliITSlayerUpgrade destructor " << endl;
+ResetClusters();
+
+}
+void AliITSlayerUpgrade::ResetClusters() {
+  //--------------------------------------------------------------------
+  // This function removes loaded clusters
+  //--------------------------------------------------------------------
+/*
+
+   for (Int_t s=0; s<kNsector; s++) {
+       Int_t &n=fN[s];
+       while (n) {
+          n--;
+ */
+
+for (Int_t i=0; i<fN; i++) delete fClusters[i];
+  fN=0;
+cout<< " AliITSlayerUpgrade::ResetClusters() : ho chiamato  resetCluster " << endl;
+   //    }
+ //  }
+return;
+}
+
+
+Int_t AliITSlayerUpgrade::InsertCluster(AliITSRecPoint *c) {
+//--------------------------------------------------------------------
+  // This function inserts a cluster to this layer in increasing
+  // order of the cluster's fZ
+  //--------------------------------------------------------------------
+fClusters[fN]=c;
+  fN++;
+  return 0;
+}
+
+//-----------------------------------------------------------------------
+const AliITSRecPoint *AliITSlayerUpgrade::GetNextCluster(Int_t &ci){
+  //--------------------------------------------------------------------
+  // This function returns clusters within the "window"
+  //--------------------------------------------------------------------
+  AliITSRecPoint *c=0;
+  ci=-1;
+  if (fNsel) {
+     fNsel--;
+     ci=fIndex[fNsel];
+     c=fClusters[ci];
+  }
+  return c;
+}
+//_____________________________________________________________________
+  Int_t AliITSlayerUpgrade::GetNumberOfClusters() const {
+  Int_t n=0;
+  n=fN;
+return n;
+}
+
diff --git a/ITS/UPGRADE/AliITSlayerUpgrade.h b/ITS/UPGRADE/AliITSlayerUpgrade.h
new file mode 100644 (file)
index 0000000..bb85c9e
--- /dev/null
@@ -0,0 +1,38 @@
+#ifndef ALIITSLAYERUPGRADE_H
+#define ALIITSLAYERUPGRADE_H
+/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
+ * See cxx source for full Copyright notice                               */
+
+/* $Id$ */
+#include <TObject.h>
+#include "AliITStrackerMI.h"
+#include "AliITSRecPoint.h"
+#include "AliITSRecoParam.h"
+ class AliITSlayerUpgrade : public TObject {
+
+  public:
+    AliITSlayerUpgrade();
+    AliITSlayerUpgrade(Double_t p, Double_t z);
+    virtual ~AliITSlayerUpgrade();
+    Int_t InsertCluster(AliITSRecPoint *c);
+    void ResetClusters();
+    const AliITSRecPoint *GetNextCluster(Int_t &ci);
+    AliITSRecPoint *GetCluster(Int_t i) const { return fClusters[i]; }
+    Int_t GetNumberOfClusters() const;
+  protected:
+    AliITSlayerUpgrade(const AliITSlayerUpgrade&);
+    AliITSlayerUpgrade &operator=(const AliITSlayerUpgrade &tr);
+    Double_t fPhiOffset;        // offset of the first detector in Phi
+    Double_t fZOffset;          // offset of the first detector in Z
+//    AliITSdetector *fDetectors; // array of detectors
+
+    AliITSRecPoint *fClusters[AliITSRecoParam::fgkMaxClusterPerLayer]; // pointers to clusters
+    Int_t fNsel;         // numbers of selected clusters 
+    Int_t fIndex[AliITSRecoParam::fgkMaxClusterPerLayer]; // indexes of selected clusters
+    Int_t fN;                       // number of clusters
+
+
+   ClassDef(AliITSlayerUpgrade,1);   
+
+  };
+#endif
diff --git a/ITS/UPGRADE/AliITSsegmentationUpgrade.cxx b/ITS/UPGRADE/AliITSsegmentationUpgrade.cxx
new file mode 100644 (file)
index 0000000..6acabda
--- /dev/null
@@ -0,0 +1,198 @@
+/**************************************************************************
+ * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
+ *                                                                        *
+ * Author: The ALICE Off-line Project.                                    *
+ * Contributors are mentioned in the code where appropriate.              *
+ *                                                                        *
+ * Permission to use, copy, modify and distribute this software and its   *
+ * documentation strictly for non-commercial purposes is hereby granted   *
+ * without fee, provided that the above copyright notice appears in all   *
+ * copies and that both the copyright notice and this permission notice   *
+ * appear in the supporting documentation. The authors make no claims     *
+ * about the suitability of this software for any purpose. It is          *
+ * provided "as is" without express or implied warranty.                  *
+ **************************************************************************/
+
+/* $Id$ */
+#include <TGeoManager.h>
+#include <TGeoVolume.h>
+#include <TGeoTube.h>
+#include <TVector3.h>
+#include <TMath.h>
+#include "AliGeomManager.h"
+#include "AliITSsegmentationUpgrade.h"
+#include "AliLog.h"
+#include <TFile.h>
+#include <iostream.h>
+//////////////////////////////////////////////////////
+// Segmentation class for                           //
+// ITS upgrade                                      //
+//                                                  //
+//////////////////////////////////////////////////////
+
+ClassImp(AliITSsegmentationUpgrade)
+
+//_____________________________________________________________________________
+
+  AliITSsegmentationUpgrade::AliITSsegmentationUpgrade(): TObject(),
+                                                         fCellSizeX(0),
+                                                         fCellSizeZ(0),
+                                                         fMinRadius(0),
+                                                         fMaxRadius(0),
+                                                         fHalfLength(0)
+{ 
+
+  AliInfo("Default constructor is called");
+  // Default constructor
+
+  if(!gGeoManager) AliGeomManager::LoadGeometry("geometry.root");
+  TFile *f=TFile::Open("Segmentation.root");
+  TArrayD *x=0;
+  TArrayD *z=0; 
+  if(!f){
+    AliInfo("Segmentation not available");
+  
+  }else {
+  
+    x=(TArrayD*)f->Get("CellSizeX");  
+    z=(TArrayD*)f->Get("CellSizeZ");
+  }
+  f->Close(); 
+    
+  Int_t i=0;
+  while(gGeoManager->GetVolume(Form("Layer%i",i))){
+    TGeoVolume *vol = gGeoManager->GetVolume(Form("Layer%i",i));
+    if(!vol) {
+      AliInfo(Form("the volume %s has not been found... exiting!",Form("Layer%i",i)));
+      return;
+    }
+    TGeoTube *shape = (TGeoTube*)vol->GetShape();
+    if(!shape) {
+      AliInfo(Form("the volume %s has not shape defined... exiting!",vol->GetName()));
+      return;
+    }   
+
+    // setting the geometry parameters (needed for trasformations Global-Local)
+
+    fMaxRadius.Set(i+1);   fMaxRadius.AddAt(shape->GetRmax(),i);
+    fMinRadius.Set(i+1);   fMinRadius.AddAt(shape->GetRmin(),i);
+    fHalfLength.Set(i+1); fHalfLength.AddAt(shape->GetDz(),i);
+    fCellSizeX.Set(i+1);
+    fCellSizeZ.Set(i+1);
+    fCellSizeX.AddAt(x->At(i),i);
+    fCellSizeZ.AddAt(z->At(i),i); 
+
+    i++;  
+  }
+
+
+
+}
+
+//_______________________________________________________________
+AliITSsegmentationUpgrade::AliITSsegmentationUpgrade(TArrayD radii, TArrayD widths, TArrayD Length): TObject(),
+                                                                                                    fCellSizeX(0),
+                                                                                                    fCellSizeZ(0),
+                                                                                                    fMinRadius(0),
+                                                                                                    fMaxRadius(0),
+                                                                                                    fHalfLength(0)
+{
+  for(Int_t i=0; i<radii.GetSize();i++){
+    fMaxRadius.Set(i+1);
+    fMaxRadius.AddAt(radii.At(i)+widths.At(i),i);
+    fMinRadius.Set(i+1);
+    fMinRadius.AddAt(radii.At(i),i);
+    fHalfLength.Set(i+1);
+    fHalfLength.AddAt(Length.At(i),i);
+  }
+}
+//_____________________________________________________________________________
+void AliITSsegmentationUpgrade::SetSegmentation(Int_t ilayer, Double_t xsize, Double_t zsize){
+  
+  // x/z size in microns
+  if(fCellSizeX.GetSize()<ilayer+1) fCellSizeX.Set(ilayer+1);
+  if(fCellSizeZ.GetSize()<ilayer+1) fCellSizeZ.Set(ilayer+1); 
+  AliDebug(10,Form("xsize %f zsize %f ilayer %i", xsize,zsize,ilayer));
+  fCellSizeX.AddAt(xsize,ilayer); 
+  fCellSizeZ.AddAt(zsize,ilayer);  
+  AliDebug(10,Form("fCellsizeX %f fCellSizeZ %f", fCellSizeX.At(ilayer), fCellSizeZ.At(ilayer)));       
+}
+//_____________________________________________________________________________
+void AliITSsegmentationUpgrade::SetFullSegmentation(TArrayD xsize, TArrayD zsize){
+  if(xsize.GetSize()!=zsize.GetSize())AliDebug(1,"Be Carefull Array Size Differ!!");
+    
+  if(xsize.GetSize()!=fMaxRadius.GetSize())AliDebug(10,Form("Be Carefull Segmentation Array (%i) and Geometry Array Differ (%i)!!",xsize.GetSize(),fMaxRadius.GetSize()));
+   
+  for(Int_t ilayer=0; ilayer<fMaxRadius.GetSize(); ilayer++)SetSegmentation(ilayer, xsize.At(ilayer),  zsize.At(ilayer));
+}
+//_________________________________________________________________________________
+void AliITSsegmentationUpgrade::GetSegmentation(Int_t ilayer, Double_t &xsize, Double_t &zsize ) const{
+  
+  xsize = fCellSizeX.At(ilayer);
+  zsize =fCellSizeZ.At(ilayer);
+}
+//_____________________________________________________________________________
+Bool_t  AliITSsegmentationUpgrade::GlobalToDet(Int_t ilayer, Double_t x,Double_t y,Double_t z,Double_t &xl,Double_t &zl) {
+  
+
+  if(TMath::Abs(z)>fHalfLength.At(ilayer)) return kFALSE;
+  
+  zl = z;
+  Double_t xyproj= TMath::Sqrt(x*x+y*y);
+  if(xyproj==0 || xyproj-0.001 > fMaxRadius.At(ilayer))return kFALSE;  
+  Double_t alpha= TMath::ATan2(y,x);
+  if(x>0 && y<0)alpha=alpha+2.*(TMath::Pi());
+  if(x<0 && y<0)alpha=alpha+2.*(TMath::Pi());
+  xl = xyproj*alpha;
+
+  return kTRUE;
+}
+//_____________________________________________________________________________
+Bool_t AliITSsegmentationUpgrade::DetToGlobal(Int_t ilayer, Double_t xl,Double_t zl,Double_t &x,Double_t &y, Double_t &z) const {
+  
+  if(TMath::Abs(z)>fHalfLength.At(ilayer)) return kFALSE;
+  z = zl;
+  Double_t alpha = xl/fMaxRadius.At(ilayer);
+
+  
+  x = fMaxRadius.At(ilayer)*TMath::Cos(alpha);
+  y = fMaxRadius.At(ilayer)*TMath::Sin(alpha);
+
+  Int_t layer=0;
+  layer=ilayer;
+  return kTRUE;
+}
+//_______________________________________________________________________________
+void AliITSsegmentationUpgrade::GetNpad(Int_t ilayer, Int_t &nx, Int_t &nz){
+      
+  if(fCellSizeX.At(ilayer)==0)AliDebug(1,"Attention! Check your X Segmentation!!");
+  if(fCellSizeZ.At(ilayer)==0)AliDebug(1,"Attention! Check your Z Segmentation!!");
+     
+  nx=(Int_t)(2.*TMath::Pi()*fMaxRadius.At(ilayer)/fCellSizeX.At(ilayer));
+  nz=(Int_t)(2.*fHalfLength.At(ilayer)/fCellSizeZ.At(ilayer));     
+
+}
+//________________________________________________________________________________
+const Int_t AliITSsegmentationUpgrade::GetNLayers(){
+
+  if(!gGeoManager) TGeoManager::Import("geometry.root");
+
+  Int_t nlay=0;
+
+  for(Int_t ivol=0; ivol<gGeoManager->GetListOfVolumes()->GetEntries();ivol++){
+    TString volname = gGeoManager->GetListOfVolumes()->At(ivol)->GetName();
+    if(!volname.Contains("Silicon")) continue;
+
+    nlay++;
+
+  }
+
+  return nlay;
+
+
+
+
+}
+
diff --git a/ITS/UPGRADE/AliITSsegmentationUpgrade.h b/ITS/UPGRADE/AliITSsegmentationUpgrade.h
new file mode 100644 (file)
index 0000000..55ee911
--- /dev/null
@@ -0,0 +1,75 @@
+#ifndef ALIITSSEGMENTATIONUPGRADE_H
+#define ALIITSSEGMENTATIONUPGRADE_H
+/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
+ * See cxx source for full Copyright notice                               */
+
+/* $Id$ */
+#include <TArrayD.h>
+
+
+//////////////////////////////////////////////////
+//  Authors A.Mastroserio                      //
+//          C.Terrevoli                                //
+//          annalisa.mastroserio@cern.ch       //      
+//         cristina.terrevoli@ba.infn.it       //
+// ITS Upgrade segmentation virtual base class  //
+//                                              //
+//////////////////////////////////////////////////
+
+
+class AliITSsegmentationUpgrade : public TObject {
+ public:
+
+  AliITSsegmentationUpgrade();
+  AliITSsegmentationUpgrade(TArrayD Radii, TArrayD widths, TArrayD Length);
+  virtual ~AliITSsegmentationUpgrade(){}//dtor
+    
+
+  // Set Detector Segmentation Parameters
+  virtual void SetSegmentation(Int_t ilayer, Double_t xsize, Double_t zsize); // x/z size in microns
+  virtual void SetFullSegmentation(TArrayD xsize, TArrayD zsize); // x/z size in microns
+  virtual void GetNpad(Int_t ilayer, Int_t &nx, Int_t &nz);
+
+  // Transformation from Geant cm detector center local coordinates
+  // to detector segmentation/cell coordiantes starting from (0,0).
+  Bool_t  GlobalToDet(Int_t ilayer, Double_t x,Double_t y,Double_t z,Double_t &xl,Double_t &zl);
+  // Transformation from detector segmentation/cell coordiantes starting
+  // from (0,0) to Geant cm detector center local coordinates.
+  Bool_t  DetToGlobal(Int_t ilayer, Double_t xl,Double_t zl,Double_t &x,Double_t &y, Double_t &z) const;
+  
+  //
+  // Get Detector Segmentation Parameters
+  //
+    
+  Double_t GetCellSizeX(Int_t ilayer){return fCellSizeX.At(ilayer);}
+  Double_t GetCellSizeZ(Int_t ilayer){return fCellSizeZ.At(ilayer);}
+  Double_t GetHalfLength(Int_t ilayer){return fHalfLength.At(ilayer);}
+  Double_t GetRadius(Int_t ilayer) {return fMinRadius.At(ilayer);}
+  
+  TArrayD GetFullCellSizeX() {return fCellSizeX;}
+  TArrayD GetFullCellSizeZ() {return fCellSizeZ;}
+  // Pixel size in x,z 
+  virtual void GetSegmentation(Int_t ilayer,  Double_t &xsize, Double_t &zsize) const;
+   
+  // layer thickness
+  virtual Float_t GetThickness(Int_t ilayer) const {if(ilayer > fMinRadius.GetSize() || ilayer < 0) return -1; else return fMaxRadius.At(ilayer) - fMinRadius.At(ilayer);}
+   
+  static const Int_t GetNLayers();  
+ protected:
+
+  TArrayD fCellSizeX;       //Size for each pixel in x -microns
+  TArrayD fCellSizeZ;       //Size for each pixel in z -microns
+  TArrayD fMinRadius ;      // layer inner radius
+  TArrayD fMaxRadius ;      // layer outer radius
+  TArrayD fHalfLength   ;   // layer length
+ private:
+  AliITSsegmentationUpgrade(const AliITSsegmentationUpgrade &source);
+  AliITSsegmentationUpgrade& operator=(const AliITSsegmentationUpgrade &source);
+
+  ClassDef(AliITSsegmentationUpgrade,1) //Segmentation class for Upgrade 
+
+    };
+
+#endif
+
diff --git a/ITS/UPGRADE/AliITStrackerUpgrade.cxx b/ITS/UPGRADE/AliITStrackerUpgrade.cxx
new file mode 100644 (file)
index 0000000..86aee2d
--- /dev/null
@@ -0,0 +1,1762 @@
+/**************************************************************************
+ * Copyright(c) 1998-2003, ALICE Experiment at CERN, All rights reserved. *
+ *                                                                        *
+ * Author: The ALICE Off-line Project.                                    *
+ * Contributors are mentioned in the code where appropriate.              *
+ *                                                                        *
+ * Permission to use, copy, modify and distribute this software and its   *
+ * documentation strictly for non-commercial purposes is hereby granted   *
+ * without fee, provided that the above copyright notice appears in all   *
+ * copies and that both the copyright notice and this permission notice   *
+ * appear in the supporting documentation. The authors make no claims     *
+ * about the suitability of this software for any purpose. It is          *
+ * provided "as is" without express or implied warranty.                  *
+ **************************************************************************/
+
+/* $Id$ */
+
+////////////////////////////////////////////////////
+//  ITS Upgrade Stand alone tracker class         //
+//  Authors: A.Mastroserio C.Terrevoli            //
+//  e-mail:annalisa.mastroserio@cern.ch           //
+//         cristina.terrevoli@ba.infn.it          //
+////////////////////////////////////////////////////
+
+#include <stdlib.h>
+
+#include <TArrayI.h>
+#include <TBranch.h>
+#include <TObjArray.h>
+#include <TTree.h>
+#include "AliRunLoader.h"
+#include "AliITSLoader.h"
+#include "AliESDEvent.h"
+#include "AliESDVertex.h"
+#include "AliESDtrack.h"
+#include "AliITSVertexer.h"
+#include "AliITSclusterTable.h"
+#include "AliITSRecPoint.h"
+#include "AliITStrackSA.h"
+#include "AliITStrackerMI.h"
+#include "AliITSlayerUpgrade.h"
+#include "AliITSsegmentationUpgrade.h"
+#include "AliITStrackerUpgrade.h"
+#include "AliITSReconstructor.h"
+#include "AliLog.h"
+#include "AliRun.h"
+
+ClassImp(AliITStrackerUpgrade)
+
+//____________________________________________________________________________
+  AliITStrackerUpgrade::AliITStrackerUpgrade():AliITStrackerMI(),
+                                              fNLayer(6),
+                                              fPhiEstimate(0),
+                                              fITSStandAlone(0),
+                                              fLambdac(0),
+                                              fPhic(0),
+                                              fCoef1(0),
+                                              fCoef2(0),
+                                              fCoef3(0),
+                                              fNloop(0),
+                                              fPhiWin(0),
+                                              fLambdaWin(0),
+                                              fVert(0),
+                                              fVertexer(0),
+                                              fListOfTracks(0),
+                                              fListOfSATracks(0),
+                                              fITSclusters(0),
+                                              fInwardFlag(0),
+                                              fOuterStartLayer(0),
+                                              fInnerStartLayer(5),
+                                              fMinNPoints(0),
+                                              fMinQ(0.),
+                                              fLayers(0),
+                                              fCluLayer(0),
+                                              fCluCoord(0){
+    // Default constructor
+    Init();
+  }
+//________________________________________________________________________
+AliITStrackerUpgrade::AliITStrackerUpgrade(const AliITStrackerUpgrade& tracker):AliITStrackerMI(),
+                                                                               fNLayer(tracker.fNLayer),
+                                                                               fPhiEstimate(tracker.fPhiEstimate),
+                                                                               fITSStandAlone(tracker.fITSStandAlone),
+                                                                               fLambdac(tracker.fLambdac),
+                                                                               fPhic(tracker.fPhic),
+                                                                               fCoef1(tracker.fCoef1),
+                                                                               fCoef2(tracker.fCoef2),
+                                                                               fCoef3(tracker.fCoef3),
+                                                                               fNloop(tracker.fNloop),
+                                                                               fPhiWin(tracker.fPhiWin),
+                                                                               fLambdaWin(tracker.fLambdaWin),
+                                                                               fVert(tracker.fVert),
+                                                                               fVertexer(tracker.fVertexer),
+                                                                               fListOfTracks(tracker.fListOfTracks),
+                                                                               fListOfSATracks(tracker.fListOfSATracks),
+                                                                               fITSclusters(tracker.fITSclusters),
+                                                                               fInwardFlag(tracker.fInwardFlag),
+                                                                               fOuterStartLayer(tracker.fOuterStartLayer),
+                                                                               fInnerStartLayer(tracker.fInnerStartLayer),
+                                                                               fMinNPoints(tracker.fMinNPoints),
+                                                                               fMinQ(tracker.fMinQ),
+                                                                               fLayers(tracker.fLayers),
+                                                                               fCluLayer(tracker.fCluLayer),
+                                                                               fCluCoord(tracker.fCluCoord) {
+  // Copy constructor
+  for(Int_t i=0;i<2;i++){
+    fPoint1[i]=tracker.fPoint1[i];
+    fPoint2[i]=tracker.fPoint2[i];
+    fPoint3[i]=tracker.fPoint3[i];
+    fPointc[i]=tracker.fPointc[i];
+  }
+  if(tracker.fVertexer && tracker.fVert){
+    fVert = new AliESDVertex(*tracker.fVert);
+  }
+  else {
+    fVert = tracker.fVert;
+  }
+  for(Int_t i=0;i<6;i++){
+    fCluLayer[i] = tracker.fCluLayer[i];
+    fCluCoord[i] = tracker.fCluCoord[i];
+  }
+}
+//______________________________________________________________________
+AliITStrackerUpgrade& AliITStrackerUpgrade::operator=(const AliITStrackerUpgrade& source){
+  // Assignment operator. 
+  this->~AliITStrackerUpgrade();
+  new(this) AliITStrackerUpgrade(source);
+  return *this;
+}
+
+//____________________________________________________________________________
+AliITStrackerUpgrade::~AliITStrackerUpgrade(){
+  // destructor
+  // if fVertexer is not null, the AliESDVertex obj. is owned by this class
+  // and is deleted here
+  if(fVertexer){
+    if(fVert)delete fVert;
+  }
+  fVert = 0;
+  fVertexer = 0;
+  if(fPhiWin)delete []fPhiWin;
+  if(fLambdaWin)delete []fLambdaWin;
+  fListOfTracks->Delete();
+  delete fListOfTracks;
+  fListOfSATracks->Delete();
+  delete fListOfSATracks;
+  if(fCluLayer){
+    for(Int_t i=0;i<6;i++){
+      if(fCluLayer[i]){
+       fCluLayer[i]->Delete();
+       delete fCluLayer[i];
+      }
+    }
+    delete [] fCluLayer;
+  }
+  if(fCluCoord){
+    for(Int_t i=0;i<AliITSgeomTGeo::GetNLayers();i++){
+      if(fCluCoord[i]){
+       fCluCoord[i]->Delete();
+       delete fCluCoord[i];
+      }
+    }
+    delete [] fCluCoord;
+  }
+  
+}
+
+//____________________________________________________________________________
+Int_t AliITStrackerUpgrade::Clusters2Tracks(AliESDEvent *event){
+  // This method is used to find and fit the tracks. By default the corresponding
+  // method in the parent class is invoked. In this way a combined tracking
+  // TPC+ITS is performed. If the flag fITSStandAlone is true, the tracking
+  // is done in the ITS only. In the standard reconstruction chain this option
+  // can be set via AliReconstruction::SetOption("ITS","onlyITS")
+  Int_t rc=0;
+  if(!fITSStandAlone){
+    rc=AliITStrackerMI::Clusters2Tracks(event);
+  }
+  else {
+    AliDebug(1,"Stand Alone flag set: doing tracking in ITS alone\n");
+  }
+  if(!rc){
+    rc=FindTracks(event,kFALSE);
+    if(AliITSReconstructor::GetRecoParam()->GetSAUseAllClusters()==kTRUE) {
+      rc=FindTracks(event,kTRUE);
+    }
+  }
+  return rc;
+}
+//_________________________________________________-
+void AliITStrackerUpgrade::Init(){
+  //  Reset all data members
+  fPhiEstimate=0;
+  for(Int_t i=0;i<3;i++){fPoint1[i]=0;fPoint2[i]=0;fPoint3[i]=0;}
+  fLambdac=0;
+  fPhic=0;
+  fCoef1=0;
+  fCoef2=0;
+  fCoef3=0;
+  fPointc[0]=0;
+  fPointc[1]=0;
+  fVert = 0;
+  fVertexer = 0;
+  Int_t nLoops=AliITSReconstructor::GetRecoParam()->GetNLoopsSA();
+  if(nLoops==33){
+    SetFixedWindowSizes();
+  }else{
+    Double_t phimin=AliITSReconstructor::GetRecoParam()->GetMinPhiSA();
+    Double_t phimax=AliITSReconstructor::GetRecoParam()->GetMaxPhiSA();
+    Double_t lambmin=AliITSReconstructor::GetRecoParam()->GetMinLambdaSA();
+    Double_t lambmax=AliITSReconstructor::GetRecoParam()->GetMaxLambdaSA();
+    SetCalculatedWindowSizes(nLoops,phimin,phimax,lambmin,lambmax);
+  }
+  fMinQ=AliITSReconstructor::GetRecoParam()->GetSAMinClusterCharge();
+  fITSclusters = 0;
+  SetOuterStartLayer(1);
+  SetSAFlag(kFALSE);
+  fListOfTracks=new TClonesArray("AliITStrackMI",100);
+  fListOfSATracks=new TClonesArray("AliITStrackSA",100);
+  fLayers=new AliITSlayerUpgrade*[6];//to be fixed
+  fCluLayer = 0;
+  fCluCoord = 0;
+  fMinNPoints = 3;
+  AliITSsegmentationUpgrade *segmentation2 = 0x0;
+  if(!segmentation2)
+    segmentation2 = new AliITSsegmentationUpgrade();
+  for(Int_t layer=0; layer<6; layer++){
+    Double_t p=0.;
+    Double_t zC= 0.;
+    fLayers[layer] = new AliITSlayerUpgrade(p,zC);
+  }
+
+       
+}
+//_______________________________________________________________________
+Int_t AliITStrackerUpgrade::LoadClusters(TTree *clusTree){ 
+  TClonesArray statITSCluster("AliITSRecPoint");
+  for(Int_t layer=0; layer<6; layer++){
+    TClonesArray *ITSCluster = &statITSCluster;
+    TBranch* itsClusterBranch=clusTree->GetBranch("ITSRecPoints");
+    if (!itsClusterBranch){
+      printf("can't get the branch with the ITS clusters ! \n");
+      return 1;
+    }
+    itsClusterBranch->SetAddress(&ITSCluster);
+    if (!clusTree->GetEvent(layer))    continue;
+    Int_t nCluster = ITSCluster->GetEntriesFast();
+    for(Int_t i=0; i<nCluster; i++){
+      AliITSRecPoint *recp = (AliITSRecPoint*)ITSCluster->UncheckedAt(i);
+
+      fLayers[layer]->InsertCluster(new AliITSRecPoint(*recp));
+    }//loop clusters
+  }//loop layer
+   
+  SetClusterTree(clusTree);
+  return 0;
+}
+
+//_______________________________________________________
+void AliITStrackerUpgrade::ResetForFinding(){
+  //  Reset data members used in all loops during track finding
+  fPhiEstimate=0;
+  for(Int_t i=0;i<3;i++){fPoint1[i]=0;fPoint2[i]=0;fPoint3[i]=0;}
+  fLambdac=0;
+  fPhic=0;
+  fCoef1=0;
+  fCoef2=0;
+  fCoef3=0;
+  fPointc[0]=0;
+  fPointc[1]=0;
+  fListOfTracks->Clear();
+  fListOfSATracks->Clear();
+}
+
+
+//______________________________________________________________________
+Int_t AliITStrackerUpgrade::FindTracks(AliESDEvent* event,Bool_t useAllClusters){
+
+  // Track finder using the ESD object
+  AliDebug(2,Form(" field is %f",event->GetMagneticField()));
+  printf(" field is %f",event->GetMagneticField());
+  AliDebug(2,Form("SKIPPING %d %d %d %d %d %d",ForceSkippingOfLayer(0),ForceSkippingOfLayer(1),ForceSkippingOfLayer(2),ForceSkippingOfLayer(3),ForceSkippingOfLayer(4),ForceSkippingOfLayer(5)));
+  if(!fITSclusters){
+    Fatal("FindTracks","ITS cluster tree is not accessed - Abort!!!\n Please use method SetClusterTree to pass the pointer to the tree\n");
+    return -1;
+  }
+
+  //Reads event and mark clusters of traks already found, with flag kITSin
+  Int_t nentr=event->GetNumberOfTracks();
+  if(!useAllClusters) {
+    while (nentr--) {
+      AliESDtrack *track=event->GetTrack(nentr);
+      if ((track->GetStatus()&AliESDtrack::kITSin) == AliESDtrack::kITSin){
+        Int_t idx[12];
+        Int_t ncl = track->GetITSclusters(idx);
+        for(Int_t k=0;k<ncl;k++){
+          AliITSRecPoint* cll = (AliITSRecPoint*)GetCluster(idx[k]);
+          cll->SetBit(kSAflag);
+        }
+      }
+    }
+  }else{
+    while (nentr--) {
+      AliESDtrack *track=event->GetTrack(nentr);
+      if ((track->GetStatus()&AliESDtrack::kITSin) == AliESDtrack::kITSin){
+        Int_t idx[12];
+        Int_t ncl = track->GetITSclusters(idx);
+        for(Int_t k=0;k<ncl;k++){
+          AliITSRecPoint* cll = (AliITSRecPoint*)GetCluster(idx[k]);
+          cll->ResetBit(kSAflag);
+        }
+      }
+    }
+  }
+  //Get primary vertex
+  Double_t primaryVertex[3];
+  event->GetVertex()->GetXYZ(primaryVertex);
+  Int_t nclusters[/*AliITSsegmentationUpgrade::GetNLayers()*/6]={0,0,0,0,0,0};
+  Int_t dmar[/*AliITSsegmentationUpgrade::GetNLayers()*/6]={0,0,0,0,0,0};
+  if (fCluLayer == 0) {
+    fCluLayer = new TClonesArray*[6];
+    fCluCoord = new TClonesArray*[6];
+    for(Int_t i=0;i<6;i++) {
+      fCluLayer[i]=0;
+      fCluCoord[i]=0;
+    }
+  }
+  for(Int_t i=0;i<6;i++){
+    if (!ForceSkippingOfLayer(i)) {
+      for(Int_t cli=0;cli<fLayers[i]->GetNumberOfClusters();cli++){
+        AliITSRecPoint* cls = (AliITSRecPoint*)fLayers[i]->GetCluster(cli);
+        if(cls->TestBit(kSAflag)==kTRUE) continue; //clusters used by TPC prol.
+        if(cls->GetQ()==0) continue; //fake clusters dead zones
+        if(i>1 && cls->GetQ()<=fMinQ) continue; // cut on SDD and SSD cluster charge
+        nclusters[i]++;
+      }
+    } 
+    dmar[i]=0;
+    if(!fCluLayer[i]){
+      fCluLayer[i] = new TClonesArray("AliITSRecPoint",nclusters[i]);
+    }else{
+      fCluLayer[i]->Delete();
+      fCluLayer[i]->Expand(nclusters[i]);
+    }
+    if(!fCluCoord[i]){
+      fCluCoord[i] = new TClonesArray("AliITSclusterTable",nclusters[i]);
+    }else{
+      fCluCoord[i]->Delete();
+      fCluCoord[i]->Expand(nclusters[i]);
+    }
+  }
+  for(Int_t ilay=0;ilay<AliITSgeomTGeo::GetNLayers();ilay++){
+    TClonesArray &clulay = *fCluLayer[ilay];
+    TClonesArray &clucoo = *fCluCoord[ilay];
+    if (!ForceSkippingOfLayer(ilay)){
+      for(Int_t cli=0;cli<fLayers[ilay]->GetNumberOfClusters();cli++){
+        AliITSRecPoint* cls = (AliITSRecPoint*)fLayers[ilay]->GetCluster(cli);
+        if(cls->TestBit(kSAflag)==kTRUE) continue;
+        if(cls->GetQ()==0) continue;
+        Double_t phi=0;Double_t lambda=0;
+        Double_t x=0;Double_t y=0;Double_t z=0;
+        Float_t sx=0;Float_t sy=0;Float_t sz=0;
+        GetCoorAngles(cls,phi,lambda,x,y,z,primaryVertex);
+        GetCoorErrors(cls,sx,sy,sz);
+        new (clulay[dmar[ilay]]) AliITSRecPoint(*cls);
+        new (clucoo[dmar[ilay]]) AliITSclusterTable(x,y,z,sx,sy,sz,phi,lambda,cli);
+        dmar[ilay]++;
+      }
+    }
+  }
+
+
+  // track counter
+  Int_t ntrack=0;
+
+  static Int_t nClusLay[6];//counter for clusters on each layer
+  Int_t startLayForSeed=0;
+  Int_t lastLayForSeed=fOuterStartLayer;
+  Int_t nSeedSteps=lastLayForSeed-startLayForSeed;
+  Int_t seedStep=1;
+  if(fInwardFlag){
+    startLayForSeed=6-1;
+    lastLayForSeed=fInnerStartLayer;
+    nSeedSteps=startLayForSeed-lastLayForSeed;
+    seedStep=-1;
+  }
+  // loop on minimum number of points
+  for(Int_t iMinNPoints=6; iMinNPoints>=fMinNPoints; iMinNPoints--) {
+    // loop on starting layer for track finding
+    for(Int_t iSeedLay=0; iSeedLay<=nSeedSteps; iSeedLay++) {
+      Int_t theLay=startLayForSeed+iSeedLay*seedStep;
+      if(ForceSkippingOfLayer(theLay)) continue;
+      Int_t minNPoints=iMinNPoints-theLay;
+      if(fInwardFlag) minNPoints=iMinNPoints-(6-1-theLay);
+      for(Int_t i=theLay+1;i<6;i++)
+        if(ForceSkippingOfLayer(i))
+          minNPoints--;
+      if(minNPoints<fMinNPoints) continue;
+
+      // loop on phi and lambda window size
+      for(Int_t nloop=0;nloop<fNloop;nloop++){
+       Int_t nclTheLay=fCluLayer[theLay]->GetEntries();
+        while(nclTheLay--){
+          ResetForFinding();
+          Bool_t useRP=SetFirstPoint(theLay,nclTheLay,primaryVertex);
+          if(!useRP) continue;
+          AliITStrackSA trs;
+
+          Int_t pflag=0;
+          Int_t kk;
+          for(kk=0;kk<6;kk++) nClusLay[kk] = 0;
+
+          kk=0;
+          nClusLay[kk] = SearchClusters(theLay,fPhiWin[nloop],fLambdaWin[nloop],
+                                        &trs,primaryVertex[2],pflag);
+          Int_t nextLay=theLay+seedStep;
+          Bool_t goon=kTRUE;
+          while(goon){
+
+            kk++;
+            nClusLay[kk] = SearchClusters(nextLay,fPhiWin[nloop],fLambdaWin[nloop],
+                                         &trs,primaryVertex[2],pflag);
+            if(nClusLay[kk]!=0){
+
+                     pflag=1;
+              if(kk==1) {
+                fPoint3[0]=fPointc[0];
+                fPoint3[1]=fPointc[1];
+              } else {
+                UpdatePoints();
+              }
+            }
+            nextLay+=seedStep;
+            if(nextLay<0 || nextLay==6) goon=kFALSE;
+          }
+
+
+          Int_t layOK=0;
+          if(!fInwardFlag){
+            for(Int_t nnp=0;nnp<6-theLay;nnp++){
+              if(nClusLay[nnp]!=0) layOK+=1;
+            }
+          }else{
+            for(Int_t nnp=theLay; nnp>=0; nnp--){
+              if(nClusLay[nnp]!=0) layOK+=1;
+            }
+          }
+         if(layOK>=minNPoints){
+           AliDebug(2,Form("---NPOINTS: %d; MAP: %d %d %d %d %d %d\n",layOK,nClusLay[0],nClusLay[1],nClusLay[2],nClusLay[3],nClusLay[4],nClusLay[5]));
+            AliITStrackV2* tr2 = 0;
+            Bool_t onePoint = kFALSE;
+            tr2 = FitTrack(&trs,primaryVertex,onePoint);
+            if(!tr2){
+              continue;
+            }
+            AliDebug(2,Form("---NPOINTS fit: %d\n",tr2->GetNumberOfClusters()));
+       
+            StoreTrack(tr2,event,useAllClusters);
+            ntrack++;
+
+          }
+
+        }//end loop on clusters of theLay
+      } //end loop on window sizes
+    } //end loop on theLay
+  }//end loop on min points
+  if(!useAllClusters) AliInfo(Form("Number of found tracks: %d",event->GetNumberOfTracks()));
+
+  ResetForFinding();
+  return 0;
+
+}
+//________________________________________________________________________
+
+AliITStrackV2* AliITStrackerUpgrade::FitTrack(AliITStrackSA* tr,Double_t *primaryVertex,Bool_t onePoint) {
+
+  
+  const Int_t kMaxClu=AliITStrackSA::kMaxNumberOfClusters;
+
+  
+  static Int_t clind[6][kMaxClu];
+  static Int_t clmark[6][kMaxClu];
+  static Int_t end[6];
+  static AliITSRecPoint *listlayer[6][kMaxClu];
+
+  for(Int_t i=0;i<6;i++) {
+    end[i]=0;
+    for(Int_t j=0;j<kMaxClu; j++){
+      clind[i][j]=0;
+      clmark[i][j]=0;
+      listlayer[i][j]=0;
+    }
+  }
+  Int_t inx[6]; 
+  for (Int_t k=0; k<6; k++) inx[k]=-1;
+  Int_t nclusters = tr->GetNumberOfClustersSA();
+  for(Int_t ncl=0;ncl<nclusters;ncl++){
+    Int_t index = tr->GetClusterIndexSA(ncl); 
+    Int_t lay = (index & 0xf0000000) >> 28;
+    Int_t cli = index&0x0fffffff;
+    AliITSRecPoint* cl = (AliITSRecPoint*)fLayers[lay]->GetCluster(cli);
+    if(cl->TestBit(kSAflag)==kTRUE) cl->ResetBit(kSAflag);  
+    inx[lay]=index;
+    Int_t nInLay=end[lay];
+    listlayer[lay][nInLay]=cl;
+    clind[lay][nInLay]=index;
+    end[lay]++;
+  }
+
+  for(Int_t nlay=0;nlay<6;nlay++){
+    for(Int_t ncl=0;ncl<tr->GetNumberOfMarked(nlay);ncl++){
+      Int_t mark = tr->GetClusterMark(nlay,ncl);
+      clmark[nlay][ncl]=mark;
+    }
+  }
+
+
+  Int_t firstLay=-1,secondLay=-1;
+  for(Int_t i=0;i<6;i++) {
+    if(end[i]==0) {
+      end[i]=1;
+    }else{
+      if(firstLay==-1) {
+       firstLay=i;
+      } else if(secondLay==-1) {
+       secondLay=i;
+      }
+    }
+  }
+
+  if(firstLay==-1 || (secondLay==-1 && !onePoint)) return 0;
+  TClonesArray &arrMI= *fListOfTracks;
+  TClonesArray &arrSA= *fListOfSATracks;
+  Int_t nFoundTracks=0;
+
+  for(Int_t l0=0;l0<end[0];l0++){ //loop on layer 1
+    AliITSRecPoint* cl0 = (AliITSRecPoint*)listlayer[0][l0];
+    for(Int_t l1=0;l1<end[1];l1++){ //loop on layer 2
+      AliITSRecPoint* cl1 = (AliITSRecPoint*)listlayer[1][l1];
+      for(Int_t l2=0;l2<end[2];l2++){  //loop on layer 3
+        AliITSRecPoint* cl2 = (AliITSRecPoint*)listlayer[2][l2];
+        for(Int_t l3=0;l3<end[3];l3++){ //loop on layer 4   
+          AliITSRecPoint* cl3 = (AliITSRecPoint*)listlayer[3][l3];
+          for(Int_t l4=0;l4<end[4];l4++){ //loop on layer 5
+            AliITSRecPoint* cl4 = (AliITSRecPoint*)listlayer[4][l4];
+            for(Int_t l5=0;l5<end[5];l5++){ //loop on layer 6  
+              AliITSRecPoint* cl5 = (AliITSRecPoint*)listlayer[5][l5];
+
+
+             Double_t x1,y1,z1,sx1,sy1,sz1;
+             Double_t x2,y2,z2,sx2,sy2,sz2;
+             AliITSRecPoint* p1=0;
+             AliITSRecPoint* p2=0;
+             Int_t index1=0,index2=0;
+             Int_t mrk1=0,mrk2=0;
+
+             switch(firstLay) {
+             case 0:
+               p1=cl0;
+               index1=clind[0][l0];mrk1=clmark[0][l0];
+               break;
+             case 1:
+               p1=cl1;
+               index1=clind[1][l1];mrk1=clmark[1][l1];
+               break;
+             case 2:
+               p1=cl2;
+               index1=clind[2][l2];mrk1=clmark[2][l2];
+               break;
+             case 3:
+               p1=cl3;
+               index1=clind[3][l3];mrk1=clmark[3][l3];
+               break;
+             case 4:
+               p1=cl4;
+               index1=clind[4][l4];mrk1=clmark[4][l4];
+               break;
+             }
+
+             switch(secondLay) {
+             case 1:
+               p2=cl1;
+               index2=clind[1][l1];mrk2=clmark[1][l1];
+               break;
+             case 2:
+               p2=cl2;
+               index2=clind[2][l2];mrk2=clmark[2][l2];
+               break;
+             case 3:
+               p2=cl3;
+               index2=clind[3][l3];mrk2=clmark[3][l3];
+               break;
+             case 4:
+               p2=cl4;
+               index2=clind[4][l4];mrk2=clmark[4][l4];
+               break;
+             case 5:
+               p2=cl5;
+               index2=clind[5][l5];mrk2=clmark[5][l5];
+               break;
+             default:
+               p2=0;
+               index2=-1;mrk2=-1;
+               break;
+             }
+
+             Int_t layer = 0;
+             Double_t radius = 0.;
+              Double_t yclu1 = p1->GetY();
+              Double_t zclu1 = p1->GetZ();
+             layer=p1->GetLayer();
+             AliITSsegmentationUpgrade *segmentation = 0x0;
+             if(!segmentation)
+                segmentation = new AliITSsegmentationUpgrade();
+             radius=segmentation->GetRadius(layer);
+             Double_t cv=0.,tgl2=0.,phi2=0.;
+             Int_t cln1=mrk1;
+             AliITSclusterTable* arr1 = (AliITSclusterTable*)GetClusterCoord(firstLay,cln1);
+             x1 = arr1->GetX();
+             y1 = arr1->GetY();
+             z1 = arr1->GetZ();
+             sx1 = arr1->GetSx();
+             sy1 = arr1->GetSy();
+             sz1 = arr1->GetSz();
+
+             if(secondLay>0) {
+               Int_t cln2=mrk2;
+               AliITSclusterTable* arr2 = (AliITSclusterTable*)GetClusterCoord(secondLay,cln2);
+               x2 = arr2->GetX();
+               y2 = arr2->GetY();
+               z2 = arr2->GetZ();
+               sx2 = arr2->GetSx();
+               sy2 = arr2->GetSy();
+               sz2 = arr2->GetSz();
+               cv = Curvature(primaryVertex[0],primaryVertex[1],x1,y1,x2,y2);
+               tgl2 = (z2-z1)/TMath::Sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
+               phi2 = TMath::ATan2((y2-y1),(x2-x1));
+             }
+             Double_t x,y,z = 0.;
+             Double_t xz[2];
+             xz[0]= p1->GetDetLocalX(); 
+             xz[1]= p1->GetDetLocalZ();   
+             Bool_t check2;
+             check2 = segmentation->DetToGlobal(layer,xz[0], xz[1],x,y,z);
+
+
+              Double_t phiclrad, phicldeg;
+              phiclrad=TMath::ATan2(y,x); 
+              if (phiclrad<0) phiclrad+=TMath::TwoPi();
+              else if (phiclrad>=TMath::TwoPi()) phiclrad-=TMath::TwoPi();
+
+              phicldeg=180.*phiclrad/TMath::Pi();
+              Int_t ladder=(Int_t)(phicldeg/18.);//virtual segmentation
+              Double_t alpha= (ladder*18.+9.)*TMath::Pi()/180.;
+
+
+              AliITStrackSA trac(alpha,radius,yclu1,zclu1,phi2,tgl2,cv,1);
+
+
+              if(cl5!=0) {
+               trac.AddClusterV2(5,(clind[5][l5] & 0x0fffffff)>>0);
+               trac.AddClusterMark(5,clmark[5][l5]);
+             }
+              if(cl4!=0){
+               trac.AddClusterV2(4,(clind[4][l4] & 0x0fffffff)>>0);
+               trac.AddClusterMark(4,clmark[4][l4]);
+             }
+              if(cl3!=0){
+               trac.AddClusterV2(3,(clind[3][l3] & 0x0fffffff)>>0);
+               trac.AddClusterMark(3,clmark[3][l3]);
+             }
+              if(cl2!=0){
+               trac.AddClusterV2(2,(clind[2][l2] & 0x0fffffff)>>0);
+               trac.AddClusterMark(2,clmark[2][l2]);
+             }
+              if(cl1!=0){
+               trac.AddClusterV2(1,(clind[1][l1] & 0x0fffffff)>>0);
+               trac.AddClusterMark(1,clmark[1][l1]);
+             }
+              if(cl0!=0){
+               trac.AddClusterV2(0,(clind[0][l0] & 0x0fffffff)>>0);
+               trac.AddClusterMark(0,clmark[0][l0]);
+             }
+  
+             //fit with Kalman filter using AliITStrackerMI::RefitAtBase()
+             AliITStrackSA ot(trac);
+              ot.ResetCovariance(10.);
+              ot.ResetClusters();
+              
+             // Propagate inside the innermost layer with a cluster 
+             if(ot.Propagate(ot.GetX()-0.1*ot.GetX())) {
+               Double_t rt=0.;
+               rt=segmentation->GetRadius(5);
+               if(RefitAtBase(rt,&ot,inx)){ //fit from layer 1 to layer 6
+                 AliITStrackMI otrack2(ot);
+                 otrack2.ResetCovariance(10.); 
+                 otrack2.ResetClusters();
+                 
+                 //fit from layer 6 to layer 1
+                 if(RefitAtBase(/*AliITSRecoParam::GetrInsideSPD1()*/segmentation->GetRadius(0),&otrack2,inx)) {//check clind
+                   new(arrMI[nFoundTracks]) AliITStrackMI(otrack2);
+                   new(arrSA[nFoundTracks]) AliITStrackSA(trac);
+                   ++nFoundTracks;
+                 }
+                              
+               }       
+             }
+            }//end loop layer 6
+          }//end loop layer 5
+        }//end loop layer 4        
+      }//end loop layer 3
+    }//end loop layer 2 
+  }//end loop layer 1
+
+
+
+
+  if(fListOfTracks->GetEntries()==0) return 0;
+
+  Int_t lowchi2 = FindTrackLowChiSquare();
+  AliITStrackV2* otrack =(AliITStrackV2*)fListOfTracks->At(lowchi2);
+  AliITStrackSA* trsa = (AliITStrackSA*)fListOfSATracks->At(lowchi2);
+  if(otrack==0) {
+    return 0;
+  }
+  Int_t indexc[6];
+  for(Int_t i=0;i<6;i++) indexc[i]=0;
+  for(Int_t nind=0;nind<otrack->GetNumberOfClusters();nind++){
+    indexc[nind] = otrack->GetClusterIndex(nind);
+  }      
+  //remove clusters of found track
+  for(Int_t nlay=0;nlay<6;nlay++){
+    for(Int_t cln=0;cln<trsa->GetNumberOfMarked(nlay);cln++){
+      Int_t index = trsa->GetClusterMark(nlay,cln);
+      fCluLayer[nlay]->RemoveAt(index);
+      RemoveClusterCoord(nlay,index);
+      fCluLayer[nlay]->Compress();
+    }    
+  }
+  return otrack;
+
+}
+
+//_______________________________________________________
+void AliITStrackerUpgrade::StoreTrack(AliITStrackV2 *t,AliESDEvent *event, Bool_t pureSA) /*const*/ 
+{
+  //
+  // Add new track to the ESD
+  //
+  AliESDtrack outtrack;
+  outtrack.UpdateTrackParams(t,AliESDtrack::kITSin);
+  if(pureSA) outtrack.SetStatus(AliESDtrack::kITSpureSA);
+  outtrack.SetStatus(AliESDtrack::kITSout);
+  outtrack.SetStatus(AliESDtrack::kITSrefit);
+  Double_t sdedx[4]={0.,0.,0.,0.};
+  for(Int_t i=0; i<4; i++) sdedx[i]=t->GetSampledEdx(i);
+  outtrack.SetITSdEdxSamples(sdedx);
+  event->AddTrack(&outtrack);
+  return;
+}
+
+
+//_______________________________________________________
+Int_t AliITStrackerUpgrade::SearchClusters(Int_t layer,Double_t phiwindow,Double_t lambdawindow, AliITStrackSA* trs,Double_t /*zvertex*/,Int_t pflag){
+  //function used to to find the clusters associated to the track
+
+  AliITSsegmentationUpgrade *segmentation = 0x0;
+  if(!segmentation)
+    segmentation = new AliITSsegmentationUpgrade();
+
+  if(ForceSkippingOfLayer(layer)) return 0;
+
+  Int_t nc=0;
+  Double_t r=segmentation->GetRadius(layer);
+  if(pflag==1){      
+    Float_t cx1,cx2,cy1,cy2;
+    FindEquation(fPoint1[0],fPoint1[1],fPoint2[0],fPoint2[1],fPoint3[0],fPoint3[1],fCoef1,fCoef2,fCoef3);
+    if (FindIntersection(fCoef1,fCoef2,fCoef3,-r*r,cx1,cy1,cx2,cy2)==0)
+      return 0;
+    Double_t fi1=TMath::ATan2(cy1-fPoint1[1],cx1-fPoint1[0]);
+    Double_t fi2=TMath::ATan2(cy2-fPoint1[1],cx2-fPoint1[0]);
+    fPhiEstimate=ChoosePoint(fi1,fi2,fPhic);
+  }
+
+  Int_t ncl = fCluLayer[layer]->GetEntries();
+  for (Int_t index=0; index<ncl; index++) {
+    AliITSRecPoint *c = (AliITSRecPoint*)fCluLayer[layer]->At(index);
+    if (!c) continue;
+    if (c->GetQ()<=0) continue;
+    if(layer>1 && c->GetQ()<=fMinQ) continue;
+    
+    AliITSclusterTable* arr = (AliITSclusterTable*)GetClusterCoord(layer,index);
+    
+    Double_t phi;
+    Double_t xT,yT;
+    xT=arr->GetX();
+    yT=arr->GetY();
+    phi=arr->GetPhi();
+    if (TMath::Abs(phi-fPhiEstimate)>phiwindow)
+      {
+        continue;
+      }
+
+    Double_t lambda = arr->GetLambda();
+    if (TMath::Abs(lambda-fLambdac)>lambdawindow) continue;
+
+    if(trs->GetNumberOfClustersSA()==trs->GetMaxNumberOfClusters()) return 0;
+    if(trs->GetNumberOfMarked(layer)==trs->GetMaxNMarkedPerLayer()) return 0;
+    Int_t orind = arr->GetOrInd();
+    trs->AddClusterSA(layer,orind);
+    trs->AddClusterMark(layer,index);
+       
+    nc++;
+    fLambdac=lambda;
+    fPhiEstimate=phi;
+
+    fPointc[0]=arr->GetX();
+    fPointc[1]=arr->GetY();
+  }
+  return nc;
+}
+
+//________________________________________________________________
+Bool_t AliITStrackerUpgrade::SetFirstPoint(Int_t lay, Int_t clu, Double_t* primaryVertex){
+  // Sets the first point (seed) for tracking
+
+  AliITSRecPoint* cl = (AliITSRecPoint*)fCluLayer[lay]->At(clu);
+  if(!cl) return kFALSE;
+  if (cl->GetQ()<=0) return kFALSE;
+  if(lay>1 && cl->GetQ()<=fMinQ) return kFALSE;
+  AliITSclusterTable* arr = (AliITSclusterTable*)GetClusterCoord(lay,clu);
+  fPhic = arr->GetPhi();
+  fLambdac = arr->GetLambda();
+  fPhiEstimate = fPhic;
+  fPoint1[0]=primaryVertex[0];
+  fPoint1[1]=primaryVertex[1];
+  fPoint2[0]=arr->GetX();
+  fPoint2[1]=arr->GetY();
+  return kTRUE; 
+}
+
+//________________________________________________________________
+void AliITStrackerUpgrade::UpdatePoints(){
+  //update of points for the estimation of the curvature  
+
+  fPoint2[0]=fPoint3[0];
+  fPoint2[1]=fPoint3[1];
+  fPoint3[0]=fPointc[0];
+  fPoint3[1]=fPointc[1];
+
+  
+}
+
+//___________________________________________________________________
+Int_t AliITStrackerUpgrade::FindEquation(Float_t x1, Float_t y1, Float_t x2, Float_t y2, Float_t x3, Float_t y3,Float_t& a, Float_t& b, Float_t& c){
+
+  //given (x,y) of three recpoints (in global coordinates) 
+  //returns the parameters a,b,c of circonference x*x + y*y +a*x + b*y +c
+
+  Float_t den = (x3-x1)*(y2-y1)-(x2-x1)*(y3-y1);
+  if(den==0) return 0;
+  a = ((y3-y1)*(x2*x2+y2*y2-x1*x1-y1*y1)-(y2-y1)*(x3*x3+y3*y3-x1*x1-y1*y1))/den;
+  b = -(x2*x2-x1*x1+y2*y2-y1*y1+a*(x2-x1))/(y2-y1);
+  c = -x1*x1-y1*y1-a*x1-b*y1;
+  return 1;
+}
+//__________________________________________________________________________
+Int_t AliITStrackerUpgrade::FindIntersection(Float_t a1, Float_t b1, Float_t c1, Float_t c2,Float_t& x1,Float_t& y1, Float_t& x2, Float_t& y2){
+  //Finds the intersection between the circonference of the track and the circonference centered in (0,0) represented by one layer
+  //c2 is -rlayer*rlayer
+
+  if(a1==0) return 0;
+  Double_t m = c2-c1; 
+  Double_t aA = (b1*b1)/(a1*a1)+1;
+  Double_t bB = (-2*m*b1/(a1*a1));
+  Double_t cC = c2+(m*m)/(a1*a1);
+  Double_t dD = bB*bB-4*aA*cC;
+  if(dD<0) return 0;
+  y1 = (-bB+TMath::Sqrt(dD))/(2*aA); 
+  y2 = (-bB-TMath::Sqrt(dD))/(2*aA); 
+  x1 = (c2-c1-b1*y1)/a1;
+  x2 = (c2-c1-b1*y2)/a1;
+
+  return 1; 
+}
+//____________________________________________________________________
+Double_t AliITStrackerUpgrade::Curvature(Double_t x1,Double_t y1,Double_t 
+                                        x2,Double_t y2,Double_t x3,Double_t y3){
+
+  //calculates the curvature of track  
+  Double_t den = (x3-x1)*(y2-y1)-(x2-x1)*(y3-y1);
+  if(den==0) return 0;
+  Double_t a = ((y3-y1)*(x2*x2+y2*y2-x1*x1-y1*y1)-(y2-y1)*(x3*x3+y3*y3-x1*x1-y1*y1))/den;
+  Double_t b = -(x2*x2-x1*x1+y2*y2-y1*y1+a*(x2-x1))/(y2-y1);
+  Double_t c = -x1*x1-y1*y1-a*x1-b*y1;
+  Double_t xc=-a/2.;
+
+  if((a*a+b*b-4*c)<0) return 0;
+  Double_t rad = TMath::Sqrt(a*a+b*b-4*c)/2.;
+  if(rad==0) return 0;
+  
+  if((x1>0 && y1>0 && x1<xc)) rad*=-1;
+  if((x1<0 && y1>0 && x1<xc)) rad*=-1;
+  //  if((x1<0 && y1<0 && x1<xc)) rad*=-1;
+  // if((x1>0 && y1<0 && x1<xc)) rad*=-1;
+  
+  return 1/rad;
+}
+
+
+//____________________________________________________________________
+Double_t AliITStrackerUpgrade::ChoosePoint(Double_t p1, Double_t p2, Double_t pp){
+
+  //Returns the point closest to pp
+
+  Double_t diff1 = p1-pp;
+  Double_t diff2 = p2-pp;
+  
+  if(TMath::Abs(diff1)<TMath::Abs(diff2)) fPhiEstimate=p1;
+  else fPhiEstimate=p2;  
+  return fPhiEstimate;
+  
+}
+
+
+//_________________________________________________________________
+Int_t AliITStrackerUpgrade::FindTrackLowChiSquare() const {
+  // returns track with lowest chi square  
+  Int_t dim=fListOfTracks->GetEntries();
+  if(dim<=1) return 0;
+  AliITStrackV2* trk = (AliITStrackV2*)fListOfTracks->At(0);
+  Double_t minChi2=trk->GetChi2();
+  Int_t index=0;
+  for(Int_t i=1;i<dim;i++){
+    trk = (AliITStrackV2*)fListOfTracks->At(i);
+    Double_t chi2=trk->GetChi2();
+    if(chi2<minChi2){
+      minChi2=chi2;
+      index=i;
+    }
+  }
+  return index;
+}
+
+//__________________________________________________________
+/*Int_t AliITStrackerUpgrade::FindLabel(Int_t l0, Int_t l1, Int_t l2, Int_t l3, Int_t l4, Int_t l5){
+
+//function used to determine the track label
+  
+Int_t lb[6] = {l0,l1,l2,l3,l4,l5};
+Int_t aa[6]={1,1,1,1,1,1};
+Int_t ff=0; 
+Int_t ll=0;
+Int_t k=0;Int_t w=0;Int_t num=6;
+for(Int_t i=5;i>=0;i--) if(lb[i]==-1) num=i;
+  
+while(k<num){
+  
+for(Int_t i=k+1;i<num;i++){
+    
+if(lb[k]==lb[i] && aa[k]!=0){
+      
+aa[k]+=1;
+aa[i]=0;
+}
+}
+k++;
+}
+
+while(w<num){
+for(Int_t j=0;j<6;j++){
+if(aa[w]<aa[j]){
+ff=aa[w];
+aa[w]=aa[j];
+aa[j]=ff;
+ll=lb[w];
+lb[w]=lb[j];
+lb[j]=ll;
+}
+}
+w++;
+}
+  
+if(num<1) return -1; 
+return lb[num-1];
+}
+*/
+//_____________________________________________________________________________
+/*Int_t AliITStrackerUpgrade::Label(Int_t gl1, Int_t gl2, Int_t gl3, Int_t gl4, Int_t gl5, Int_t gl6,Int_t gl7, Int_t gl8, Int_t gl9, Int_t gl10,Int_t gl11,
+  Int_t gl12, Int_t gl13, Int_t gl14,Int_t gl15, Int_t gl16, Int_t gl17, Int_t gl18, Int_t minNPoints){
+
+  //function used to assign label to the found track. If track is fake, the label is negative
+
+  Int_t lb0[6] = {gl1,gl2,gl3,gl4,gl5,gl6};
+  Int_t lb1[6] = {gl7,gl8,gl9,gl10,gl11,gl12};
+  Int_t lb2[6] = {gl13,gl14,gl15,gl16,gl17,gl18};
+  Int_t ll=FindLabel(lb0[0],lb0[1],lb0[2],lb0[3],lb0[4],lb0[5]);
+  Int_t lflag=0;Int_t num=6;
+  if(lb0[5]==-1 && lb1[5]==-1 && lb2[5]==-1) num=5;
+
+  for(Int_t i=0;i<num;i++){
+  if(lb0[i]==ll || lb1[i]==ll || lb2[i]==ll) lflag+=1;
+  }
+
+  if(lflag>=minNPoints) return ll;
+  else return -ll;
+
+  
+  }
+*/
+//_____________________________________________________________________________
+void AliITStrackerUpgrade::SetCalculatedWindowSizes(Int_t n, Float_t phimin, Float_t phimax, Float_t lambdamin, Float_t lambdamax){
+  // Set sizes of the phi and lambda windows used for track finding
+  fNloop = n;
+  if(fPhiWin) delete [] fPhiWin;
+  if(fLambdaWin) delete [] fLambdaWin;
+  fPhiWin = new Double_t[fNloop];
+  fLambdaWin = new Double_t[fNloop];
+  Float_t stepPhi=(phimax-phimin)/(Float_t)(fNloop-1);
+  Float_t stepLambda=(lambdamax-lambdamin)/(Float_t)(fNloop-1);
+  for(Int_t k=0;k<fNloop;k++){
+    Float_t phi=phimin+k*stepPhi;
+    Float_t lam=lambdamin+k*stepLambda;
+    fPhiWin[k]=phi;
+    fLambdaWin[k]=lam;
+  }
+}
+//_____________________________________________________________________________
+void AliITStrackerUpgrade::SetFixedWindowSizes(Int_t n, Double_t *phi, Double_t *lam){
+  // Set sizes of the phi and lambda windows used for track finding
+  fNloop = n;
+  if(phi){ // user defined values
+    fPhiWin = new Double_t[fNloop];
+    fLambdaWin = new Double_t[fNloop];
+    for(Int_t k=0;k<fNloop;k++){
+      fPhiWin[k]=phi[k];
+      fLambdaWin[k]=lam[k];
+    }
+  }
+  else {  // default values
+            
+    Double_t phid[33]   = {0.002,0.003,0.004,0.0045,0.0047,
+                          0.005,0.0053,0.0055,
+                          0.006,0.0063,0.0065,0.007,0.0073,0.0075,0.0077,
+                          0.008,0.0083,0.0085,0.0087,0.009,0.0095,0.0097,
+                          0.01,0.0105,0.011,0.0115,0.012,0.0125,0.013,0.0135,0.0140,0.0145};
+    Double_t lambdad[33] = {0.003,0.004,0.005,0.005,0.005,
+                           0.005,0.005,0.006,
+                           0.006,0.006,0.006,0.007,0.007,0.007,0.007,
+                           0.007,0.007,0.007,0.007,0.007,0.007,0.007,
+                           0.008,0.008,0.008,0.008,0.008,0.008,0.008,0.008,0.008,0.008};
+    
+    if(fNloop!=33){
+      fNloop = 33;
+    }
+    
+    
+    fPhiWin = new Double_t[fNloop];
+    fLambdaWin = new Double_t[fNloop];
+
+    Double_t factor=AliITSReconstructor::GetRecoParam()->GetFactorSAWindowSizes(); 
+  
+    for(Int_t k=0;k<fNloop;k++){
+      fPhiWin[k]=phid[k]*factor;
+      fLambdaWin[k]=lambdad[k]*factor;
+    }
+  
+  }
+
+}
+//_______________________________________________________________________
+void AliITStrackerUpgrade::GetCoorAngles(AliITSRecPoint* cl,Double_t &phi,Double_t &lambda, Double_t &x, Double_t &y,Double_t &z,Double_t* vertex){
+  //Returns values of phi (azimuthal) and lambda angles for a given cluster
+  /*  
+      Double_t rot[9];     fGeom->GetRotMatrix(module,rot);
+      Int_t lay,lad,det; fGeom->GetModuleId(module,lay,lad,det);
+      Float_t tx,ty,tz;  fGeom->GetTrans(lay,lad,det,tx,ty,tz);     
+
+      Double_t alpha=TMath::ATan2(rot[1],rot[0])+TMath::Pi();
+      Double_t phi1=TMath::Pi()/2+alpha;
+      if (lay==1) phi1+=TMath::Pi();
+
+      Float_t cp=TMath::Cos(phi1), sp=TMath::Sin(phi1);
+      Float_t r=tx*cp+ty*sp;
+
+      xyz= r*cp - cl->GetY()*sp;
+      y= r*sp + cl->GetY()*cp;
+      z=cl->GetZ();
+  */
+  
+  Double_t xz[2];
+  xz[0]= cl->GetDetLocalX(); 
+  xz[1]= cl->GetDetLocalZ() ; 
+  AliITSsegmentationUpgrade *segmentation2 = 0x0;
+  if(!segmentation2)
+    segmentation2 = new AliITSsegmentationUpgrade();
+  Bool_t check2;
+  Int_t ilayer;
+  ilayer = cl->GetLayer();
+  check2 = segmentation2->DetToGlobal(ilayer,xz[0], xz[1],x,y,z);
+
+  if(x!=0 && y!=0)  
+    phi=TMath::ATan2(y-vertex[1],x-vertex[0]);
+  lambda=TMath::ATan2(z-vertex[2],TMath::Sqrt((x-vertex[0])*(x-vertex[0])+(y-vertex[1])*(y-vertex[1])));
+}
+
+//________________________________________________________________________
+void AliITStrackerUpgrade::GetCoorErrors(AliITSRecPoint* cl,Float_t &sx,Float_t &sy, Float_t &sz){
+
+  //returns sigmax, y, z of cluster in global coordinates
+  /*
+    Double_t rot[9];     fGeom->GetRotMatrix(module,rot);
+    Int_t lay,lad,det; 
+    AliITSgeomTGeo::GetModuleId(module,lay,lad,det);
+    Double_t alpha=TMath::ATan2(rot[1],rot[0])+TMath::Pi();
+    Double_t phi=TMath::Pi()/2+alpha;
+    if (lay==1) phi+=TMath::Pi();
+
+    Float_t cp=TMath::Cos(phi), sp=TMath::Sin(phi);
+  */
+  Float_t covm[6];
+  cl->GetGlobalCov(covm);
+  sx=TMath::Sqrt(covm[0]);
+  sy=TMath::Sqrt(covm[3]);
+  sz=TMath::Sqrt(covm[5]);
+
+
+
+  //  Float_t covm[6];
+  //  cl->GetGlobalCov(covm);
+  //  sx=12*1e-04;//TMath::Sqrt(covm[0]);
+  //  sy=12*1e-04;//TMath::Sqrt(covm[3]);
+  //  sz=40*1e-04;//TMath::Sqrt(covm[5]);
+  /*
+    sx = TMath::Sqrt(sp*sp*cl->GetSigmaY2());
+    sy = TMath::Sqrt(cp*cp*cl->GetSigmaY2());
+    sz = TMath::Sqrt(cl->GetSigmaZ2());
+  */
+}
+//_____________________________________________________________
+void AliITStrackerUpgrade::UnloadClusters() {
+  //--------------------------------------------------------------------
+  //This function unloads ITS clusters
+  //--------------------------------------------------------------------
+  for (Int_t i=0; i<6; i++) fLayers[i]->ResetClusters();
+}
+//______________________________________________________________________
+Bool_t AliITStrackerUpgrade::RefitAtBase(Double_t xx,AliITStrackMI *track,
+                                        const Int_t *clusters)
+{
+  //--------------------------------------------------------------------
+  // Simplified version for ITS upgrade studies -- does not use module info
+  //--------------------------------------------------------------------
+  Int_t index[AliITSgeomTGeo::kNLayers];
+  Int_t k;
+  for (k=0; k<AliITSgeomTGeo::GetNLayers(); k++) index[k]=-1;
+  //
+  for (k=0; k<AliITSgeomTGeo::GetNLayers(); k++) {
+    index[k]=clusters[k];
+  }
+  AliITSsegmentationUpgrade *segmentation = 0x0;
+  if(!segmentation)
+    segmentation = new AliITSsegmentationUpgrade();
+
+  ULong_t trStatus=0;
+  if(track->GetESDtrack()) trStatus=track->GetStatus();
+  Int_t innermostlayer=0;
+  if(trStatus&AliESDtrack::kTPCin)  {
+    innermostlayer=5;
+    Double_t drphi = TMath::Abs(track->GetD(0.,0.));
+    for(innermostlayer=0; innermostlayer<AliITSgeomTGeo::GetNLayers(); innermostlayer++) {
+      if( (drphi < (segmentation->GetRadius(innermostlayer)+1.)) ||
+          index[innermostlayer] >= 0 ) break;
+    }
+    AliDebug(2,Form(" drphi  %f  innermost %d",drphi,innermostlayer));
+  }
+
+  Int_t from, to, step;
+  if (xx > track->GetX()) {
+    from=innermostlayer; to=6;
+    step=+1;
+  } else {
+    from=AliITSgeomTGeo::GetNLayers()-1; to=innermostlayer-1;
+    step=-1;
+  }
+  TString dir = (step>0 ? "outward" : "inward");
+
+  for (Int_t ilayer = from; ilayer != to; ilayer += step) {
+    Double_t r=0.;
+    r=segmentation->GetRadius(ilayer);
+
+    if (step<0 && xx>r){
+      break;
+    }
+
+    // material between SSD and SDD, SDD and SPD
+    //      Double_t hI=ilayer-0.5*step; 
+    //      if (TMath::Abs(hI-3.5)<0.01) // SDDouter
+    //        if(!CorrectForShieldMaterial(track,"SDD",dir)) return kFALSE;
+    //      if (TMath::Abs(hI-1.5)<0.01) // SPDouter
+    //        if(!CorrectForShieldMaterial(track,"SPD",dir)) return kFALSE;
+
+
+    Double_t oldGlobXYZ[3];
+
+    if (!track->GetXYZ(oldGlobXYZ)) {
+      return kFALSE;
+    }
+    // continue if we are already beyond this layer
+    Double_t oldGlobR = TMath::Sqrt(oldGlobXYZ[0]*oldGlobXYZ[0]+oldGlobXYZ[1]*oldGlobXYZ[1]);
+    if(step>0 && oldGlobR > r){
+      continue; // going outward
+    }
+    if(step<0 && oldGlobR < r) {
+      continue; // going inward
+    }
+    Double_t phi,z;
+    if (!track->GetPhiZat(r,phi,z)){
+      return kFALSE;
+    }
+    // only for ITS-SA tracks refit
+    track->SetCheckInvariant(kFALSE);
+      
+    if (phi<0) phi+=TMath::TwoPi();//from 0 to 360 (rad) 
+    else if (phi>=TMath::TwoPi()) phi-=TMath::TwoPi();//
+    Double_t phideg=0.;  
+    phideg=180.*phi/TMath::Pi();// in deg  
+    Int_t ladder=(Int_t)(phideg/18.);// virtual segmentation 
+    Double_t alpha= (ladder*18.+9.)*TMath::Pi()/180.;
+    
+    if (!track->Propagate(alpha,r)) {
+      return kFALSE;
+    }
+
+    const AliITSRecPoint *clAcc=0;
+    Double_t maxchi2=1000.*AliITSReconstructor::GetRecoParam()->GetMaxChi2();
+
+    Int_t idx=index[ilayer];
+    if (idx>=0) { // cluster in this layer   
+      Int_t cli = idx&0x0fffffff;
+      const AliITSRecPoint *cl=(AliITSRecPoint *)fLayers[ilayer]->GetCluster(cli);
+
+      if (cl) {                                                                  
+       Int_t cllayer = (idx & 0xf0000000) >> 28;;                               
+       Double_t chi2=GetPredictedChi2MI(track,cl,cllayer);                      
+       if (chi2<maxchi2) {                                                      
+         clAcc=cl;                                                              
+         maxchi2=chi2;                                                          
+       } else {                                                                 
+         return kFALSE;                                                         
+       }                                                                        
+      }                                                                          
+    }              
+
+    if (clAcc) {
+      if (!UpdateMI(track,clAcc,maxchi2,idx)){
+       return kFALSE;
+      }
+      track->SetSampledEdx(clAcc->GetQ(),ilayer-2);
+    }
+
+
+    // Correct for material of the current layer
+    // cross material
+    // add time if going outward
+    if(!CorrectForLayerMaterial(track,ilayer,oldGlobXYZ,dir)){
+      return kFALSE;
+    }
+    track->SetCheckInvariant(kFALSE);
+  } // end loop on layers
+
+  if (!track->PropagateTo(xx,0.,0.)){
+    return kFALSE;
+  }
+  return kTRUE;
+}
+
+//_____________________________________________________________________
+Int_t AliITStrackerUpgrade::UpdateMI(AliITStrackMI* track, const AliITSRecPoint* cl,Double_t chi2,Int_t index) const
+{
+  //
+  // Update ITS track
+  //
+  Int_t layer = (index & 0xf0000000) >> 28;
+  track->SetClIndex(layer, index);
+  if (TMath::Abs(cl->GetQ())<1.e-13) return 0;  // ingore the "virtual" clusters
+
+
+  // Take into account the mis-alignment (bring track to cluster plane)
+  Double_t xTrOrig=track->GetX();
+  Double_t trxyz[3]; track->GetXYZ(trxyz);
+  Float_t xclu1 = cl->GetX();//upgrade clusters tracking coordinate
+  //Float_t yclu1 = cl->GetY();
+  //Float_t zclu1 = cl->GetZ();
+  if (!track->Propagate(xTrOrig+xclu1)){
+    return 0;
+  }
+  AliCluster c(*cl);
+  c.SetSigmaY2(track->GetSigmaY(layer)*track->GetSigmaY(layer));
+  c.SetSigmaZ2(track->GetSigmaZ(layer)*track->GetSigmaZ(layer));
+  c.SetSigmaYZ(track->GetSigmaYZ(layer));
+
+  // Bring the track back to detector plane in ideal geometry  
+  Int_t updated = track->UpdateMI(&c,chi2,index);
+  if (!track->Propagate(xTrOrig)) {
+    return 0;
+  }
+  if(!updated){
+    AliDebug(2,"update failed");
+  }
+  return updated;
+}
+//____________________________________________________________________-
+Int_t AliITStrackerUpgrade::CorrectForLayerMaterial(AliITStrackMI *t,
+                                                   Int_t layerindex,
+                                                   Double_t oldGlobXYZ[3],
+                                                   TString direction) {
+  //-------------------------------------------------------------------
+  // Propagate beyond layer and correct for material
+  // (material budget in different ways according to fUseTGeo value)
+  // Add time if going outward (PropagateTo or PropagateToTGeo)
+  //-------------------------------------------------------------------
+
+  // Define budget mode:
+  // 0: material from AliITSRecoParam (hard coded)
+  // 1: material from TGeo in stepsof X cm (on the fly)
+  //    X = AliITSRecoParam::GetStepSizeTGeo()
+  // 2: material from lut
+  // 3: material from TGeo in one step (same for all hypotheses)
+  Int_t mode;
+  switch(fUseTGeo) {
+  case 0:
+    mode=0;
+    break;
+  case 1:
+    mode=1;
+    break;
+  case 2:
+    mode=2;
+    break;
+  case 3:
+    if(fTrackingPhase.Contains("Clusters2Tracks"))
+      { mode=3; } else { mode=1; }
+    break;
+  case 4:
+    if(fTrackingPhase.Contains("Clusters2Tracks"))
+      { mode=3; } else { mode=2; }
+    break;
+  default:
+    mode=0;
+    break;
+  }
+  if(fTrackingPhase.Contains("Default")) {
+    mode=0;
+  }
+  Float_t  dir = (direction.Contains("inward") ? 1. : -1.);
+  Double_t r = 0.;
+  AliITSsegmentationUpgrade *segmentation = 0x0;
+  if(!segmentation)
+    segmentation = new AliITSsegmentationUpgrade();
+  r=segmentation->GetRadius(layerindex);
+  Double_t deltar=(layerindex<2 ? 0.10*r : 0.05*r);
+  Double_t rToGo=TMath::Sqrt(t->GetX()*t->GetX()+t->GetY()*t->GetY())-deltar*dir;
+  Double_t xToGo;
+  if (!t->GetLocalXat(rToGo,xToGo)) {
+    return 0;
+  }
+  Int_t index=6*fCurrentEsdTrack+layerindex;
+
+
+  Double_t xOverX0=0.0,x0=0.0,lengthTimesMeanDensity=0.0;
+  Int_t nsteps=1;
+  // back before material (no correction)
+  Double_t rOld,xOld;
+  rOld=TMath::Sqrt(oldGlobXYZ[0]*oldGlobXYZ[0]+oldGlobXYZ[1]*oldGlobXYZ[1]);
+  if (!t->GetLocalXat(rOld,xOld)) return 0;
+  if (!t->Propagate(xOld)) return 0;
+
+  switch(mode) {
+  case 1:
+    x0=21.82;
+    xOverX0 = segmentation->GetThickness(layerindex)/x0;
+
+    lengthTimesMeanDensity = xOverX0*x0;
+    lengthTimesMeanDensity *= dir;
+    // Bring the track beyond the material
+    if (!t->PropagateTo(xToGo,xOverX0,lengthTimesMeanDensity/xOverX0)){
+      return 0;
+    }
+    break;
+  case 0:
+    nsteps = (Int_t)(TMath::Abs(xOld-xToGo)/AliITSReconstructor::GetRecoParam()->GetStepSizeTGeo())+1;
+    if (!t->PropagateToTGeo(xToGo,nsteps)) return 0; // cross the material and apply correction
+    break;
+  case 2:
+    if(fxOverX0Layer[layerindex]<0) BuildMaterialLUT("Layers");
+    xOverX0 = fxOverX0Layer[layerindex];
+    lengthTimesMeanDensity = fxTimesRhoLayer[layerindex];
+    lengthTimesMeanDensity *= dir;
+    // Bring the track beyond the material
+    if (!t->PropagateTo(xToGo,xOverX0,lengthTimesMeanDensity/xOverX0)) return 0;
+    break;
+  case 3:
+    if(!fxOverX0LayerTrks || index<0 || index>=6*fNtracks) Error("CorrectForLayerMaterial","Incorrect usage of UseTGeo option!\n");
+    if(fxOverX0LayerTrks[index]<0) {
+      nsteps = (Int_t)(TMath::Abs(xOld-xToGo)/AliITSReconstructor::GetRecoParam()->GetStepSizeTGeo())+1;
+      if (!t->PropagateToTGeo(xToGo,nsteps,xOverX0,lengthTimesMeanDensity)) return 0;
+      Double_t angle=TMath::Sqrt((1.+t->GetTgl()*t->GetTgl())/
+                                 ((1.-t->GetSnp())*(1.+t->GetSnp())));
+      fxOverX0LayerTrks[index] = TMath::Abs(xOverX0)/angle;
+      fxTimesRhoLayerTrks[index] = TMath::Abs(lengthTimesMeanDensity)/angle;
+      return 1;
+    }
+    xOverX0 = fxOverX0LayerTrks[index];
+    lengthTimesMeanDensity = fxTimesRhoLayerTrks[index];
+    lengthTimesMeanDensity *= dir;
+    // Bring the track beyond the material
+    if (!t->PropagateTo(xToGo,xOverX0,lengthTimesMeanDensity/xOverX0)){
+      return 0;
+    }
+    break;
+  }
+
+
+  return 1;
+}
+
+
+//_____________________________________________________________________________
+Double_t AliITStrackerUpgrade::GetPredictedChi2MI(AliITStrackMI* track, const AliITSRecPoint *cluster,Int_t layer)
+{
+  //
+  // Compute predicted chi2
+  //
+  Float_t erry,errz,covyz;
+  Float_t theta = track->GetTgl();
+  Float_t phi   = track->GetSnp();
+  phi = TMath::Abs(phi)*TMath::Sqrt(1./((1.-phi)*(1.+phi)));
+  GetError(layer,cluster,theta,phi,track->GetExpQ(),erry,errz,covyz);
+  AliDebug(2,Form(" chi2: tr-cl   %f  %f   tr X %f cl X %f",track->GetY()-cluster->GetY(),track->GetZ()-cluster->GetZ(),track->GetX(),cluster->GetX()));
+  // Take into account the mis-alignment (bring track to cluster plane)
+  Double_t xTrOrig=track->GetX();
+  if (!track->Propagate(xTrOrig+cluster->GetX())) return 1000.;
+  AliDebug(2,Form(" chi2: tr-cl   %f  %f   tr X %f cl X %f",track->GetY()-cluster->GetY(),track->GetZ()-cluster->GetZ(),track->GetX(),cluster->GetX()));
+  Double_t chi2 = track->GetPredictedChi2MI(cluster->GetY(),cluster->GetZ(),erry,errz,covyz);
+  // Bring the track back to detector plane in ideal geometry
+  // [mis-alignment will be accounted for in UpdateMI()]
+  if (!track->Propagate(xTrOrig)) return 1000.;
+  Float_t ny=0.,nz=0.;
+  //GetNTeor(layer,cluster,theta,phi,ny,nz);
+  Double_t delta = cluster->GetNy()+cluster->GetNz()-nz-ny;
+  if (delta>1){
+    chi2+=0.5*TMath::Min(delta/2,2.);
+    chi2+=2.*cluster->GetDeltaProbability();
+  }
+  //
+  track->SetNy(layer,ny);
+  track->SetNz(layer,nz);
+  track->SetSigmaY(layer,erry);
+  track->SetSigmaZ(layer, errz);
+  track->SetSigmaYZ(layer,covyz);
+  //track->fNormQ[layer] = cluster->GetQ()/TMath::Sqrt(1+theta*theta+phi*phi);
+  track->SetNormQ(layer,cluster->GetQ()/TMath::Sqrt((1.+ track->GetTgl()*track->GetTgl())/((1.-track->GetSnp())*(1.+track->GetSnp()))));
+  return chi2;
+}
+//________________________________________________________________
+Int_t AliITStrackerUpgrade::GetError(Int_t /*layer*/,
+                                    const AliITSRecPoint *cl,
+                                    Float_t /*tgl*/,Float_t /*tgphitr*/,Float_t /*expQ*/,
+                                    Float_t &erry,Float_t &errz,Float_t &covyz,
+                                    Bool_t /*addMisalErr*/)
+{
+  //
+  // Calculate cluster position error for the upgrade
+  //
+  Int_t retval=0;
+  covyz=0.;
+  retval = GetErrorOrigRecPoint(cl,erry,errz,covyz);
+
+
+
+  return retval;
+                                                                                   
+}
+//____________________________________________________________________-
+
+Int_t AliITStrackerUpgrade::GetErrorOrigRecPoint(const AliITSRecPoint*cl,
+                                                Float_t &erry,Float_t &errz,Float_t &covyz)
+{
+  //
+  // Calculate cluster position error (just take error from AliITSRecPoint)
+  //
+  erry   = TMath::Sqrt(cl->GetSigmaY2());
+  errz   = TMath::Sqrt(cl->GetSigmaZ2());
+  covyz  = cl->GetSigmaYZ();
+  return 1;
+}
+//__________________________
+void AliITStrackerUpgrade::GetNTeor(Int_t layer,const AliITSRecPoint* /*cl*/,
+                                   Float_t tgl,Float_t tgphitr,
+                                   Float_t &ny,Float_t &nz)
+{
+  //
+  // Get "mean shape" (original parametrization from AliITStrackerMI)
+  //
+  tgl = TMath::Abs(tgl);
+  tgphitr = TMath::Abs(tgphitr);
+
+  // SPD
+  if (layer==0) {
+    ny = 1.+tgphitr*3.2;
+    nz = 1.+tgl*0.34;
+    return;
+  }
+  if (layer==1) {
+    ny = 1.+tgphitr*3.2;
+    nz = 1.+tgl*0.28;
+    return;
+  }
+  // SSD
+  if (layer==4 || layer==5) {
+    ny = 2.02+tgphitr*1.95;
+    nz = 2.02+tgphitr*2.35;
+    return;
+  }
+  // SDD
+  ny  = 6.6-2.7*tgphitr;
+  nz  = 2.8-3.11*tgphitr+0.45*tgl;
+  return;
+}
+//_________________________________________________________________
+Int_t AliITStrackerUpgrade::PropagateBack(AliESDEvent *event) {
+  //--------------------------------------------------------------------
+  // This functions propagates reconstructed ITS tracks back
+  // The clusters must be loaded !
+  //--------------------------------------------------------------------
+  fTrackingPhase="PropagateBack";
+  Int_t nentr=event->GetNumberOfTracks();
+  Info("PropagateBack", "Number of ESD tracks: %d\n", nentr);
+  Int_t ntrk=0;
+  for (Int_t i=0; i<nentr; i++) {
+    AliESDtrack *esd=event->GetTrack(i);
+
+    if ((esd->GetStatus()&AliESDtrack::kITSin)==0) continue;
+    if (esd->GetStatus()&AliESDtrack::kITSout) continue;
+
+    AliITStrackMI *t=0;
+    try {
+      t=new AliITStrackMI(*esd);
+    } catch (const Char_t *msg) {
+      //Warning("PropagateBack",msg);
+      delete t;
+      continue;
+    }
+    t->SetExpQ(TMath::Max(0.8*t->GetESDtrack()->GetTPCsignal(),30.));
+
+    ResetTrackToFollow(*t);
+
+    /*
+    // propagate to vertex [SR, GSI 17.02.2003]
+    // Start Time measurement [SR, GSI 17.02.2003], corrected by I.Belikov
+    if (CorrectForPipeMaterial(&fTrackToFollow,"inward")) {
+    if (fTrackToFollow.PropagateToVertex(event->GetVertex()))
+    fTrackToFollow.StartTimeIntegral();
+    // from vertex to outside pipe
+    CorrectForPipeMaterial(&fTrackToFollow,"outward");
+    }*/
+    // Start time integral and add distance from current position to vertex
+    Double_t xyzTrk[3],xyzVtx[3]={GetX(),GetY(),GetZ()};
+    fTrackToFollow.GetXYZ(xyzTrk);
+    Double_t dst2 = 0.;
+    for (Int_t icoord=0; icoord<3; icoord++) {
+      Double_t di = xyzTrk[icoord] - xyzVtx[icoord];
+      dst2 += di*di;
+    }
+    fTrackToFollow.StartTimeIntegral();
+    fTrackToFollow.AddTimeStep(TMath::Sqrt(dst2));
+
+    fTrackToFollow.ResetCovariance(10.); 
+    fTrackToFollow.ResetClusters();
+    //
+    Int_t inx[6];
+    for (Int_t k=0; k<6; k++) inx[k]=-1;
+    Int_t nclusters = t->GetNumberOfClusters();
+    for(Int_t ncl=0;ncl<nclusters;ncl++){
+      Int_t index = t-> GetClIndex(ncl);
+      Int_t lay = (index & 0xf0000000) >> 28;
+      inx[lay]=index;
+    }
+    //   
+    if (RefitAtBase(43.6,&fTrackToFollow,inx)) {
+      //fTrackToFollow.SetLabel(t->GetLabel());//
+      //fTrackToFollow.CookdEdx();
+      //CookLabel(&fTrackToFollow,0.); //For comparison only
+      fTrackToFollow.UpdateESDtrack(AliESDtrack::kITSout);
+      UseClusters(&fTrackToFollow);
+      ntrk++;
+    }
+    delete t;
+  }
+
+  AliInfo(Form("Number of back propagated ITS tracks: %d out of %d ESD tracks",ntrk,nentr));
+
+  fTrackingPhase="Default";
+
+  return 0;
+}
+//_________________________________________________________________________
+AliCluster *AliITStrackerUpgrade::GetCluster(Int_t index) const {
+  //--------------------------------------------------------------------
+  //       Return pointer to a given cluster
+  //--------------------------------------------------------------------
+  Int_t l=(index & 0xf0000000) >> 28;
+  AliInfo(Form("index %i  cluster index %i layer %i", index,index & 0x0fffffff,index & 0xf0000000));
+  return fLayers[l]->GetCluster(index);
+}
+//______________________________________________________________________________
+Int_t AliITStrackerUpgrade::CorrectForPipeMaterial(AliITStrackMI *t, TString direction) {
+//-------------------------------------------------------------------
+// Propagate beyond beam pipe and correct for material
+// (material budget in different ways according to fUseTGeo value)
+// Add time if going outward (PropagateTo or PropagateToTGeo)
+//-------------------------------------------------------------------
+
+// Define budget mode:
+// 0: material from AliITSRecoParam (hard coded)
+// 1: material from TGeo in one step (on the fly)
+// 2: material from lut
+// 3: material from TGeo in one step (same for all hypotheses)
+Int_t mode;
+switch(fUseTGeo) {
+ case 0:
+   mode=0;
+   break;
+ case 1:
+   mode=1;
+   break;
+ case 2:
+   mode=2;
+   break;
+ case 3:
+   if(fTrackingPhase.Contains("Clusters2Tracks"))
+     { mode=3; } else { mode=1; }
+   break;
+ case 4:
+   if(fTrackingPhase.Contains("Clusters2Tracks"))
+     { mode=3; } else { mode=2; }
+   break;
+ default:
+   mode=0;
+   break;
+ }
+if(fTrackingPhase.Contains("Default")) mode=0;
+Int_t index=fCurrentEsdTrack;
+
+Float_t  dir = (direction.Contains("inward") ? 1. : -1.);
+Double_t rToGo=(dir>0 ? AliITSRecoParam::GetrInsidePipe() : AliITSRecoParam::GetrOutsidePipe());
+Double_t xToGo;
+if (!t->GetLocalXat(rToGo,xToGo)) return 0;
+
+Double_t xOverX0,x0,lengthTimesMeanDensity;
+
+switch(mode) {
+ case 1:
+   xOverX0 = AliITSRecoParam::GetdPipe();
+   x0 = AliITSRecoParam::GetX0Be();
+   lengthTimesMeanDensity = xOverX0*x0;
+   lengthTimesMeanDensity *= dir;
+   if (!t->PropagateTo(xToGo,xOverX0,lengthTimesMeanDensity/xOverX0)) return 0;
+   break;
+ case 0:
+   if (!t->PropagateToTGeo(xToGo,1)) return 0;
+   break;
+ case 2:
+   if(fxOverX0Pipe<0) BuildMaterialLUT("Pipe");
+   xOverX0 = fxOverX0Pipe;
+   lengthTimesMeanDensity = fxTimesRhoPipe;
+   lengthTimesMeanDensity *= dir;
+   if (!t->PropagateTo(xToGo,xOverX0,lengthTimesMeanDensity/xOverX0)) return 0;
+   break;
+ case 3:
+   if(!fxOverX0PipeTrks || index<0 || index>=fNtracks) Error("CorrectForPipeMaterial","Incorrect usage of UseTGeo option!\n");
+   if(fxOverX0PipeTrks[index]<0) {
+     if (!t->PropagateToTGeo(xToGo,1,xOverX0,lengthTimesMeanDensity)) return 0;
+     Double_t angle=TMath::Sqrt((1.+t->GetTgl()*t->GetTgl())/
+                               ((1.-t->GetSnp())*(1.+t->GetSnp())));
+     fxOverX0PipeTrks[index] = TMath::Abs(xOverX0)/angle;
+     fxTimesRhoPipeTrks[index] = TMath::Abs(lengthTimesMeanDensity)/angle;
+     return 1;
+   }
+   xOverX0 = fxOverX0PipeTrks[index];
+   lengthTimesMeanDensity = fxTimesRhoPipeTrks[index];
+   lengthTimesMeanDensity *= dir;
+   if (!t->PropagateTo(xToGo,xOverX0,lengthTimesMeanDensity/xOverX0)) return 0;
+   break;
+ }
+
+return 1;
+}
+//__________________________________________________________________________
+Int_t AliITStrackerUpgrade::RefitInward(AliESDEvent *event) {
+  //--------------------------------------------------------------------
+  // This functions refits ITS tracks using the
+  // "inward propagated" TPC tracks
+  // The clusters must be loaded !
+  //--------------------------------------------------------------------
+  fTrackingPhase="RefitInward";
+  Int_t nentr=event->GetNumberOfTracks();
+  for (Int_t i=0; i<nentr; i++) {
+    AliESDtrack *esd=event->GetTrack(i);
+
+    // if ((esd->GetStatus()&AliESDtrack::kITSout) == 0) continue;
+    // if (esd->GetStatus()&AliESDtrack::kITSrefit) continue;
+    //if (esd->GetStatus()&AliESDtrack::kTPCout)
+    //  if ((esd->GetStatus()&AliESDtrack::kTPCrefit)==0) continue;
+    AliITStrackMI *t=0;
+    try {
+      t=new AliITStrackMI(*esd);
+    } catch (const Char_t *msg) {
+      //Warning("RefitInward",msg);
+      delete t;
+      continue;
+    }
+
+    ResetTrackToFollow(*t);
+    // fTrackToFollow.ResetClusters();
+    //  if ((esd->GetStatus()&AliESDtrack::kTPCin)==0)
+    //  fTrackToFollow.ResetCovariance(10.);
+    //Refitting...
+    //The beam pipe
+    // if (CorrectForPipeMaterial(&fTrackToFollow,"inward")) {
+    fTrackToFollow.UpdateESDtrack(AliESDtrack::kITSrefit);
+    AliESDtrack  *esdTrack =fTrackToFollow.GetESDtrack();
+    Double_t r[3]={0.,0.,0.};
+    Double_t maxD=3.;
+    esdTrack->RelateToVertex(event->GetVertex(),GetBz(r),maxD);
+    // }
+    delete t;
+  }
+
+  fTrackingPhase="Default";
+  return 0;
+}
+
+
+
diff --git a/ITS/UPGRADE/AliITStrackerUpgrade.h b/ITS/UPGRADE/AliITStrackerUpgrade.h
new file mode 100644 (file)
index 0000000..6c38324
--- /dev/null
@@ -0,0 +1,160 @@
+#ifndef ALIITSTRACKERUPGRADE_H
+#define ALIITSTRACKERUPGRADE_H 
+
+
+
+#include "AliITStrackerMI.h"
+#include "AliITSlayerUpgrade.h"
+#include "AliITStrackMI.h"
+
+/* Copyright(c) 1998-2003, ALICE Experiment at CERN, All rights reserved. *
+ * See cxx source for full Copyright notice                               */
+
+/* $Id$ */
+////////////////////////////////////////////////////
+//  ITS Upgrade Stand alone tracker class         //
+//  Authors: A.Mastroserio C.Terrevoli            //
+//  e-mail:annalisa.mastroserio@cern.ch           //
+//         cristina.terrevoli@ba.infn.it          //
+//  tracks are saved as AliITStrackV2 objects     //
+////////////////////////////////////////////////////
+
+#include <TClonesArray.h>
+
+class AliITSclusterTable;
+class AliITStrackSA;
+class AliESDVertex;
+class AliESDEvent;
+class AliITSVertexer;
+class TTree;
+class TArrayD;
+
+class AliITStrackerUpgrade : public AliITStrackerMI {
+
+
+ public:
+
+  AliITStrackerUpgrade();
+  AliITStrackerUpgrade(const AliITStrackerUpgrade& tracker);
+  AliITStrackerUpgrade& operator=(const AliITStrackerUpgrade& source);
+  virtual ~AliITStrackerUpgrade();  
+ virtual Int_t Clusters2Tracks(AliESDEvent *event);  
+ Int_t FindTracks(AliESDEvent* event,Bool_t useAllClusters=kFALSE);
+  Int_t PropagateBack(AliESDEvent *event);
+  Int_t CorrectForPipeMaterial(AliITStrackMI *t, TString direction="inward");  
+  Int_t RefitInward(AliESDEvent *event);//{return 0;}
+  AliCluster *GetCluster(Int_t index) const;
+
+  AliITStrackV2* FitTrack(AliITStrackSA* tr,Double_t* primaryVertex,Bool_t onePoint=kFALSE);
+  void StoreTrack(AliITStrackV2 *t,AliESDEvent *event, Bool_t pureSA) /*const*/; 
+  Int_t FindTrackLowChiSquare() const;
+  Int_t LoadClusters(TTree *clusTree);
+  void SetVertex(AliESDVertex *vtx){fVert = vtx;}
+  void SetClusterTree(TTree * itscl){fITSclusters = itscl;}
+
+  void SetOutwardFinding() {fInwardFlag=kFALSE;}
+  void SetInwardFinding() {fInwardFlag=kTRUE;}
+  void SetOuterStartLayer(Int_t osl = 0) {
+    if(osl>(fNLayer-2)) AliWarning("Minimum Number of layers is 2. OuterStartLayer set to Nlayers-2");
+    fOuterStartLayer = TMath::Min(fNLayer-2,osl);
+  }
+  Int_t GetOuterStartLayer() const {return fOuterStartLayer;}
+  void SetInnerStartLayer(Int_t isl = 5) {
+    if(isl<1) AliWarning("Minimum Number of layers is 2. InnerStartLayer set to 1");
+    fInnerStartLayer = TMath::Max(1,isl);
+  }
+  Int_t GetInnerStartLayer() const {return fInnerStartLayer;}
+  void SetSAFlag(Bool_t fl){fITSStandAlone=fl;}  // StandAlone flag setter
+  Bool_t GetSAFlag() const {return fITSStandAlone;} // StandAlone flag gett
+  void SetFixedWindowSizes(Int_t n=46, Double_t *phi=0, Double_t *lam=0);
+  void SetCalculatedWindowSizes(Int_t n=10, Float_t phimin=0.002, Float_t phimax=0.0145, Float_t lambdamin=0.003, Float_t lambdamax=0.008);
+  void UnloadClusters();
+  void SetMinNPoints(Int_t np){fMinNPoints=np;}
+  Int_t GetMinNPoints() const {return fMinNPoints;}
+  void SetMinimumChargeSDDSSD(Float_t minq=0.){fMinQ=minq;}
+  enum {kSAflag=0x8000}; //flag to mark clusters used in the SA tracker
+
+ protected:
+
+  //Initialization
+  void Init();
+  void  CreateLayers(Int_t iEvent);
+  void ResetForFinding();
+  void UpdatePoints();
+  Bool_t SetFirstPoint(Int_t lay, Int_t clu, Double_t* primaryVertex);
+  static Double_t Curvature(Double_t x1,Double_t y1,Double_t x2,Double_t y2,
+                     Double_t x3,Double_t y3);
+
+  Double_t ChoosePoint(Double_t p1, Double_t p2, Double_t pp); 
+
+  static Int_t   FindIntersection(Float_t a1, Float_t b1, Float_t c1, Float_t c2, 
+                           Float_t& x1,Float_t& y1, Float_t& x2, Float_t& y2);
+  static Int_t   FindEquation(Float_t x1, Float_t y1, Float_t x2, Float_t y2, 
+                       Float_t x3, Float_t y3,Float_t& a, Float_t& b, 
+                       Float_t& c);
+  static Int_t FindLabel(Int_t l1, Int_t l2, Int_t l3, Int_t l4, Int_t l5, Int_t l6);
+  static Int_t Label(Int_t gl1, Int_t gl2, Int_t gl3, Int_t gl4, Int_t gl5, 
+              Int_t gl6,Int_t gl7, Int_t gl8, Int_t gl9, Int_t gl10,Int_t gl11,
+              Int_t gl12, Int_t gl13, Int_t gl14,Int_t gl15, Int_t gl16, 
+              Int_t gl17, Int_t gl18, Int_t numberofpoints=6);
+  Int_t SearchClusters(Int_t layer,Double_t phiwindow,Double_t lambdawindow, 
+                       AliITStrackSA* trs,Double_t zvertex,Int_t flagp); 
+
+  void GetCoorAngles(AliITSRecPoint* cl,Double_t &phi,Double_t &lambda,Double_t &x,Double_t &y,Double_t &z,Double_t* vertex);
+  void GetCoorErrors(AliITSRecPoint* cl,Float_t &sx,Float_t &sy, Float_t &sz);
+  AliITSclusterTable* GetClusterCoord(Int_t layer,Int_t n) const {return (AliITSclusterTable*)fCluCoord[layer]->UncheckedAt(n);}
+  void RemoveClusterCoord(Int_t layer, Int_t n) {fCluCoord[layer]->RemoveAt(n);fCluCoord[layer]->Compress();}
+  Bool_t RefitAtBase(Double_t x, AliITStrackMI *track,
+                 const Int_t *clusters);
+  Int_t UpdateMI(AliITStrackMI* track, const AliITSRecPoint* cl,Double_t chi2,Int_t layer) const;
+ Int_t CorrectForLayerMaterial(AliITStrackMI *t, Int_t layerindex, Double_t oldGlobXYZ[3], TString direction="inward");
+  Double_t GetPredictedChi2MI(AliITStrackMI* track, const AliITSRecPoint *cluster,Int_t layer);
+  static Int_t GetError(Int_t layer,const AliITSRecPoint*cl,
+                        Float_t tgl,Float_t tgphitr,Float_t expQ,
+                        Float_t &erry,Float_t &errz,Float_t &covyz,
+                        Bool_t addMisalErr=kTRUE);
+  
+  static Int_t GetErrorOrigRecPoint(const AliITSRecPoint*cl,
+                                    Float_t &erry,Float_t &errz,Float_t &covyz);
+  static void GetNTeor(Int_t layer,const AliITSRecPoint* cl,
+                       Float_t tgl,Float_t tgphitr,
+                       Float_t &ny,Float_t &nz);
+
+  Int_t fNLayer;//number of layer in ITSUpgrade
+  Double_t fPhiEstimate; //Estimation of phi angle on next layer
+  Bool_t fITSStandAlone; //Tracking is performed in the ITS alone if kTRUE
+  Float_t fPoint1[2];   //! coord. of 1-st point to evaluate the curvature
+  Float_t fPoint2[2];   //! coord. of 2-nd point to evaluate the curvature
+  Float_t fPoint3[2];   //! coord. of 3-rd point to evaluate the curvature
+  Float_t fPointc[2];   //! current point coord (for curvature eval.)
+  Double_t fLambdac;    //! current value of the Lambda angle in the window
+  Double_t fPhic;       //! current value of the Phi angle in the window
+  Float_t fCoef1;       //! param. of the equation of the circ. approx a layer
+  Float_t fCoef2;       //! param. of the equation of the circ. approx a layer
+  Float_t fCoef3;       //! param. of the equation of the circ. approx a layer
+  Int_t fNloop;         //  Number of iterqations on phi and lambda windows
+  Double_t *fPhiWin;    // phi window sizes
+  Double_t *fLambdaWin; // lambda window sizes
+  AliESDVertex *fVert;        //! primary vertex
+  AliITSVertexer *fVertexer;  //! vertexer 
+  TClonesArray *fListOfTracks;   //! container for found tracks 
+  TClonesArray *fListOfSATracks; //! container for found SA tracks 
+  TTree *fITSclusters;        //! pointer to ITS tree of clusters
+  Bool_t fInwardFlag;       // set to kTRUE for inward track finding
+  Int_t fOuterStartLayer;     // Outward search for tracks with <6 points: outer layer to start from
+  Int_t fInnerStartLayer;     // Inward search for tracks with <6 points: inner layer to start from
+  Int_t fMinNPoints;        // minimum number of clusters for a track
+  Float_t fMinQ;              // lower cut on cluster charge (SDD and SSD)
+  AliITSlayerUpgrade** fLayers;
+
+  TClonesArray** fCluLayer; //! array with clusters 
+  TClonesArray** fCluCoord; //! array with cluster info
+
+  ClassDef(AliITStrackerUpgrade,1)
+};
+
+#endif
+
+
diff --git a/ITS/UPGRADE/AliITSupgrade.cxx b/ITS/UPGRADE/AliITSupgrade.cxx
new file mode 100644 (file)
index 0000000..08dd451
--- /dev/null
@@ -0,0 +1,488 @@
+// **************************************************************************
+// * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
+// *                                                                        *
+// * Author: The ALICE Off-line Project.                                    *
+// * Contributors are mentioned in the code where appropriate.              *
+// *                                                                        *
+// * Permission to use, copy, modify and distribute this software and its   *
+// * documentation strictly for non-commercial purposes is hereby granted   *
+// * without fee, provided that the above copyright notice appears in all   *
+// * copies and that both the copyright notice and this permission notice   *
+// * appear in the supporting documentation. The authors make no claims     *
+// * about the suitability of this software for any purpose. It is          *
+// * provided "as is" without express or implied warranty.                  *
+// **************************************************************************
+
+/* $Id$ */
+
+#include <TArrayD.h>            //new constructor
+#include <TFile.h>  
+#include <TGeoManager.h>        //CreateGeometry()
+#include <TGeoVolume.h>         //CreateGeometry()
+#include <TVirtualMC.h>         //->gMC in StepManager
+#include <TPDGCode.h>           //StepHistory
+#include <TClonesArray.h>
+#include "AliRun.h"             //CreateMaterials()    
+#include "AliMC.h"             //CreateMaterials()    
+#include "AliMagF.h"            //CreateMaterials()
+#include "AliCDBManager.h"      //CreateMaterials()
+#include "AliCDBEntry.h"        //CreateMaterials()
+#include "AliITSupgrade.h"      //class header
+#include "AliITShit.h"           // StepManager()
+#include "AliITSDigitUpgrade.h"
+#include "AliTrackReference.h"   // StepManager()
+#include "AliITSDetTypeSim.h"
+ClassImp(AliITSupgrade) 
+//__________________________________________________________________________________________________
+  AliITSupgrade::AliITSupgrade():
+    AliITS(),
+    fWidths(0),
+    fRadii(0),
+    fRadiiCu(0),
+    fWidthsCu(0),
+    fCopper(0),
+    fBeampipe(0), 
+    fRadiusBP(0),
+    fWidthBP(0),
+    fHalfLengthBP(0),
+    fNlayers(0),
+    fHalfLength(0),
+    fSdigits(0),
+    fDigits(0),
+    fClusters(0),
+    fSegmentation(0x0)
+{
+  //
+  // default ctor
+}
+//__________________________________________________________________________________________________
+AliITSupgrade::AliITSupgrade(const char *name,const char *title, TArrayD widths, TArrayD radii,TArrayD halfLengths, TArrayD radiiCu, TArrayD widthsCu, TArrayS copper,Bool_t bp,Double_t radiusBP, Double_t widthBP, Double_t halfLengthBP):
+  AliITS(name,title),
+  fWidths(0),
+  fRadii(0),
+  fRadiiCu(radiiCu),
+  fWidthsCu(widthsCu),
+  fCopper(copper),
+  fBeampipe(bp),
+  fRadiusBP(radiusBP),
+  fWidthBP(widthBP),
+  fHalfLengthBP(halfLengthBP),
+  fNlayers(widths.GetSize()),
+  fHalfLength(halfLengths),
+  fSdigits(0),
+  fDigits(0),
+  fClusters(0),
+  fSegmentation(0x0)
+{
+
+  //
+  // constructor
+  for(Int_t i=0;i<fNlayers;i++){
+    fWidths.Set(i+1);
+    fWidths.AddAt(widths.At(i),i);
+    fRadii.Set(i+1);
+    fRadii.AddAt(radii.At(i),i);
+    AliDebug(1,"Creating Volume");
+  }
+  Init();
+
+}
+
+AliITSupgrade::~AliITSupgrade(){
+
+  if(fSdigits) {fSdigits->Delete(); delete fSdigits;}
+  if(fDigits)  {fDigits->Delete(); delete fDigits;}
+}
+
+
+//_________________________________________________________________________________________________
+void AliITSupgrade::AddAlignableVolumes()const
+{
+  //not needed
+  return;
+}
+
+//__________________________________________________________________________________________________
+
+void AliITSupgrade::CreateMaterials()
+{
+  //
+  // Definition of ITS materials  
+  //
+  
+  AliInfo("Start ITS materials");
+  //data from PDG booklet 2002     density [gr/cm^3] rad len [cm] abs len [cm]    
+  Float_t   aAir[4]={12,14,16,36} ,   zAir[4]={6,7,8,18} ,   wAir[4]={0.000124,0.755267,0.231781,0.012827} , dAir=0.00120479; Int_t nAir=4;//mixture
+  Float_t       aBe = 9.012 ,          zBe   = 4 ,            dBe   =  1.848    ,   radBe   =  65.19/dBe , absBe   = 77.8/dBe  ; // UPGRADE -> beryllium beampipe
+  Float_t       aSi = 28.085 ,         zSi   = 14 ,           dSi   =  2.329    ,   radSi   =  21.82/dSi , absSi   = 108.4/dSi  ; // UPGRADE -> Si tube
+  Float_t aCu = 63.54, zCu = 29 , dCu= 8.96 , radCu = 12.86/dCu, absCu= 137.3/dCu;//Upgrade -> Copper Tube
+
+  Int_t   matId=0;                           //tmp material id number
+  Int_t   unsens = 0, sens=1;                //sensitive or unsensitive medium
+  Int_t   itgfld = 3;                       //type of field intergration 0 no field -1 user in guswim 1 Runge Kutta 2 helix 3 const field along z
+  Float_t maxfld = 5.;                              //max field value
+  Float_t tmaxfd = -10.0;                    //max deflection angle due to magnetic field in one step
+  Float_t deemax = - 0.2;                    //max fractional energy loss in one step   
+  Float_t stemax = - 0.1;                    //max step allowed [cm]
+  Float_t epsil  =   0.001;                  //abs tracking precision [cm]   
+  Float_t stmin  = - 0.001;                  //min step size [cm] in continius process transport, negative value: choose it automatically
+  Float_t tmaxfdSi = 0.1; // .10000E+01; // Degree
+  Float_t stemaxSi = 0.0075; //  .10000E+01; // cm
+  Float_t deemaxSi = 0.1; // 0.30000E-02; // Fraction of particle's energy 0<deemax<=1
+  Float_t epsilSi  = 1.0E-4;// .10000E+01;
+  Float_t stminSi  = 0.0; // cm "Default value used"
+
+  Float_t epsilBe  = .001;    // Tracking precision,
+  Float_t stemaxBe = -0.01;   // Maximum displacement for multiple scat
+  Float_t tmaxfdBe = -20.;    // Maximum angle due to field deflection
+  Float_t deemaxBe = -.3;     // Maximum fractional energy loss, DLS
+  Float_t stminBe  = -.8;
+
+      
+  AliMixture(++matId,"UpgradeAir"  ,aAir  ,zAir  ,dAir  ,nAir  ,wAir  ); 
+  AliMedium(kAir  ,"UpgradeAir"  ,matId, unsens, itgfld, maxfld, tmaxfd, stemax, deemax, epsil, stmin);
+    
+  AliMaterial(++matId,"UpgradeSi"  ,aSi  ,zSi  ,dSi  ,radSi  ,absSi  );  
+  AliMedium(kSi  ,"UpgradeSi"  , matId, sens, itgfld, maxfld, tmaxfdSi, stemaxSi, deemaxSi, epsilSi, stminSi);
+    
+  AliMaterial(++matId,"UpgradeBe"  ,aBe  ,zBe  ,dBe  ,radBe  ,absBe  );  
+  AliMedium(kBe  ,"UpgradeBe"  , matId, unsens, itgfld, maxfld, tmaxfdBe, stemaxBe, deemaxBe, epsilBe, stminBe);
+
+  AliMaterial(++matId, "UpgradeCu", aCu, zCu, dCu, radCu, absCu);
+  AliMedium(kCu, "UpgradeCu", matId, unsens, itgfld, maxfld, tmaxfd, stemax, deemax, epsil, stmin);
+   
+  AliInfo("End ITS materials");
+          
+}//void AliITS::CreateMaterials()
+//__________________________________________________________________________________________________
+void AliITSupgrade::CreateGeometry()
+{
+  //
+  //Creates detailed geometry simulation (currently GEANT volumes tree)        
+  //
+  AliInfo("Start ITS upgrade preliminary version building");
+  if(!gMC->IsRootGeometrySupported()) return;                
+  TGeoVolumeAssembly *vol= CreateVol();
+  gGeoManager->GetVolume("ALIC")->AddNode(vol,0);
+  AliInfo("Stop ITS upgrade preliminary version building");
+} 
+//__________________________________________________________________________________________________
+void AliITSupgrade::Init()
+{
+  // This method defines ID for sensitive volumes, i.e. such geometry volumes for which there are if(gMC->CurrentVolID()==XXX) 
+  // statements in StepManager()
+  // Arguments: none
+  //   Returns: none      
+  AliDebug(1,"Init ITS upgrade preliminary version.");    
+}
+//__________________________________________________________________________________________________
+void AliITSupgrade::StepManager()
+{
+  // Full Step Manager.
+  // Arguments: none
+  //   Returns: none           
+  //  StepHistory(); return; //uncomment to print tracks history
+  //  StepCount(); return;   //uncomment to count photons
+  if(!(this->IsActive())) return;
+  if(!(gMC->TrackCharge())) return;
+  TString volumeName=gMC->CurrentVolName();
+  if(gMC->IsTrackExiting() && !volumeName.Contains("Cu") && !volumeName.Contains("Be")) {
+    AddTrackReference(gAlice->GetMCApp()->GetCurrentTrackNumber(), AliTrackReference::kITS);
+  } // if Outer ITS mother Volume
+
+  static TLorentzVector position, momentum; // Saves on calls to construtors
+  static AliITShit hit;// Saves on calls to constructors
+
+  
+  Int_t  status = 0;
+  
+  //
+  // Track status
+  if(gMC->IsTrackInside())      status +=  1;
+  if(gMC->IsTrackEntering())    status +=  2;
+  if(gMC->IsTrackExiting())     status +=  4;
+  if(gMC->IsTrackOut())         status +=  8;
+  if(gMC->IsTrackDisappeared()) status += 16;
+  if(gMC->IsTrackStop())        status += 32;
+  if(gMC->IsTrackAlive())       status += 64;
+
+  //
+  // Fill hit structure.
+  //
+  TString volname = gMC->CurrentVolName();
+  if(volname.Contains("Cu"))return;
+  if(volname.Contains("Be"))return; 
+  volname.Remove(0,5);          // remove letters to get the layer number
+  hit.SetModule(volname.Atoi()); // this will be the layer, not the module
+  hit.SetTrack(gAlice->GetMCApp()->GetCurrentTrackNumber());
+    
+  gMC->TrackPosition(position);
+  gMC->TrackMomentum(momentum);
+  hit.SetPosition(position);
+    
+  hit.SetTime(gMC->TrackTime());
+  hit.SetMomentum(momentum);
+  hit.SetStatus(status);
+  hit.SetEdep(gMC->Edep());
+  hit.SetShunt(GetIshunt());
+  if(gMC->IsTrackEntering()){
+    hit.SetStartPosition(position);
+    hit.SetStartTime(gMC->TrackTime());
+    hit.SetStartStatus(status);
+    return; // don't save entering hit.
+  } 
+    // Fill hit structure with this new hit.
+    
+  new((*fHits)[fNhits++]) AliITShit(hit); // Use Copy Construtor.
+  // Save old position... for next hit.
+  hit.SetStartPosition(position);
+  hit.SetStartTime(gMC->TrackTime());
+  hit.SetStartStatus(status);
+  return;
+
+}
+//__________________________________________________________________________________________________
+TGeoVolumeAssembly * AliITSupgrade::CreateVol()
+{
+  TGeoVolumeAssembly *vol = new TGeoVolumeAssembly("ITSupgrade");
+  TGeoMedium *si   =gGeoManager->GetMedium("ITS_UpgradeSi");
+  TGeoMedium *cu   =gGeoManager->GetMedium("ITS_UpgradeCu");
+  TGeoMedium *be   =gGeoManager->GetMedium("ITS_UpgradeBe");
+  for(Int_t ivol=0;ivol<fNlayers;ivol++){
+    TGeoVolume *layer=gGeoManager->MakeTube(Form("LayerSilicon%i",ivol),si   ,    fRadii.At(ivol)   ,   fRadii.At(ivol)+fWidths.At(ivol)  ,   fHalfLength.At(ivol)); //upgraded situation 
+    
+    TGeoVolume *layerCu=gGeoManager->MakeTube(Form("LayerCu%i",ivol),cu   ,    fRadiiCu.At(ivol)   ,   fRadiiCu.At(ivol)+fWidthsCu.At(ivol) ,  fHalfLength.At(ivol)  ); //upgraded situation 
+    
+
+    vol ->AddNode(layer,ivol);
+    if(fCopper.At(ivol)){
+      vol->AddNode(layerCu,ivol);
+    }
+  }
+  TGeoVolume *beampipe=gGeoManager->MakeTube("BeamPipe", be   ,    fRadiusBP   ,  fRadiusBP+ fWidthBP ,  fHalfLengthBP  ); //upgraded situation
+
+  if(fBeampipe) vol->AddNode(beampipe,0);
+  return vol; 
+  
+}
+//_________________________________________________________________________________________________
+void AliITSupgrade::SetFullSegmentation(TArrayD xsize,TArrayD zsize){
+  TFile *file= TFile::Open("Segmentation.root","recreate");
+  file->WriteObjectAny(&xsize,"TArrayD","CellSizeX");
+  file->WriteObjectAny(&zsize,"TArrayD","CellSizeZ");    
+  file->Close();
+}
+//_________________________________________________________________________________________________
+void AliITSupgrade::StepHistory()
+{
+  // This methode is invoked from StepManager() in order to print out
+  static Int_t iStepN;
+  const char *sParticle;
+  switch(gMC->TrackPid()){
+  case kProton:      sParticle="PROTON"    ;break;
+  case kNeutron:     sParticle="neutron"   ;break;
+  case kGamma:       sParticle="gamma"     ;break;
+  case kPi0:         sParticle="Pi0"       ;break;
+  case kPiPlus:      sParticle="Pi+"       ;break;
+  case kPiMinus:     sParticle="Pi-"       ;break;
+  case kElectron:    sParticle="electron"  ;break;
+  default:           sParticle="not known" ;break;
+  }
+
+  TString flag="fanny combination";
+  if(gMC->IsTrackAlive())
+    if(gMC->IsTrackEntering())      flag="enters to";
+    else if(gMC->IsTrackExiting())  flag="exits from";
+    else if(gMC->IsTrackInside())   flag="inside";
+    else if(gMC->IsTrackStop())     flag="stopped in";
+  
+  Int_t vid=0,copy=0;
+  TString path=gMC->CurrentVolName(); path.Prepend("-");path.Prepend(gMC->CurrentVolOffName(1));//current volume and his mother are always there
+  vid=gMC->CurrentVolOffID(2,copy);  if(vid) {path.Prepend("-");path.Prepend(gMC->VolName(vid));}
+  vid=gMC->CurrentVolOffID(3,copy);  if(vid) {path.Prepend("-");path.Prepend(gMC->VolName(vid));}
+
+  AliDebug(10, Form("Step %i: %s (%i) %s %s m=%.6f GeV q=%.1f dEdX=%.4f Etot=%.4f",iStepN,sParticle,gMC->TrackPid(),flag.Data(),path.Data(),gMC->TrackMass(),gMC->TrackCharge(),gMC->Edep()*1e9,gMC->Etot()));
+
+  Double_t gMcTrackPos[3]; gMC->TrackPosition(gMcTrackPos[0],gMcTrackPos[1],gMcTrackPos[2]);
+  Double_t  gMcTrackPosLoc[3]; gMC->Gmtod(gMcTrackPos,gMcTrackPosLoc,1);
+  AliDebug(10,Form("gMC Track Position (MARS) x: %5.3lf, y: %5.3lf, z: %5.3lf (r: %5.3lf) ---> (LOC) x: %5.3f, y: %5.3f, z: %5.3f",gMcTrackPos[0],gMcTrackPos[1],gMcTrackPos[2],TMath::Sqrt(gMcTrackPos[0]*gMcTrackPos[0]+gMcTrackPos[1]*gMcTrackPos[1]+gMcTrackPos[2]*gMcTrackPos[2]),gMcTrackPosLoc[0],gMcTrackPosLoc[1],gMcTrackPosLoc[2]));
+
+
+  AliDebug(10,Form("Step %i: tid=%i flags alive=%i disap=%i enter=%i exit=%i inside=%i out=%i stop=%i new=%i",
+                  iStepN, gAlice->GetMCApp()->GetCurrentTrackNumber(),
+                  gMC->IsTrackAlive(), gMC->IsTrackDisappeared(),gMC->IsTrackEntering(), gMC->IsTrackExiting(),
+                  gMC->IsTrackInside(),gMC->IsTrackOut(),        gMC->IsTrackStop(),     gMC->IsNewTrack()));
+
+  Float_t a,z,den,rad,abs; a=z=den=rad=abs=-1;
+  Int_t mid=gMC->CurrentMaterial(a,z,den,rad,abs);
+  AliDebug(10, Form("Step %i: mid=%i a=%7.2f z=%7.2f den=%9.4f rad=%9.2f abs=%9.2f\n\n",iStepN,mid,a,z,den,rad,abs));
+
+  TArrayI proc;  gMC->StepProcesses(proc);
+  AliDebug(1,"Processes in this step:");
+  for ( int i = 0 ; i < proc.GetSize(); i++)
+    {
+      AliDebug(10, Form("%s",TMCProcessName[proc.At(i)]));
+    }
+  AliDebug(1,"End process list");
+  iStepN++;
+}//StepHistory()
+//______________________________________________________
+void AliITSupgrade::Hits2SDigits(){
+  
+  // Interface method ivoked from AliSimulation to create a list of sdigits corresponding to list of hits. Every hit generates one or more sdigits.
+  // Arguments: none
+  //   Returns: none
+  AliDebug(1,"Start Hits2SDigits.");
+  
+  if(!fSegmentation)fSegmentation=new AliITSsegmentationUpgrade();
+  if(!GetLoader()->TreeH()) {GetLoader()->LoadHits();}
+  if(!GetLoader()->TreeS())
+
+    for(Int_t iEvt=0;iEvt < GetLoader()->GetRunLoader()->GetNumberOfEvents();iEvt++){//events loop
+      GetLoader()->GetRunLoader()->GetEvent(iEvt);                          //get next event
+      {
+       GetLoader()->MakeTree("S");
+       MakeBranch("S");
+      }
+      SetTreeAddress();
+      Int_t nSdigit[10]; for(Int_t i=0;i<10;i++)  nSdigit[i] =0; 
+      for(Int_t iEnt=0;iEnt<GetLoader()->TreeH()->GetEntries();iEnt++){//prims loop
+        GetLoader()->TreeH()->GetEntry(iEnt);     
+        Hit2SumDig(Hits(),SDigitsList(),nSdigit);//convert this hit to list of sdigits  
+      }//prims loop
+      GetLoader()->TreeS()->Fill();
+      GetLoader()->WriteSDigits("OVERWRITE");
+      SDigitsReset();
+    }//events loop
+  GetLoader()->UnloadHits();
+  GetLoader()->UnloadSDigits();
+  AliDebug(1,"Stop Hits2SDigits.");
+  
+}
+//____________________________
+void AliITSupgrade::Hit2SumDig(TClonesArray *hits,TObjArray *pSDig, Int_t *nSdigit)
+{
+  // Adds  sdigits of this hit to the list
+  //   Returns: none
+  
+  AliDebug(1,"Start Hit2SumDig");
+  
+  
+  if(!fSegmentation){    
+    AliDebug(1,"Segmentation Not inizialized!!");
+    return ;
+  }
+  
+  TClonesArray *pSdigList[10]; 
+  
+  for(Int_t i=0;i<fNlayers;i++){ 
+    pSdigList[i]=(TClonesArray*)(*pSDig)[i];
+    if(pSdigList[i]->GetEntries()!=0) AliErrorClass("Some of sdigits lists is not empty");         //in principle those lists should be empty 
+  }
+  
+  
+  for(Int_t iHit=0;iHit<hits->GetEntries();iHit++){         //hits loop
+    AliITShit *hit = (AliITShit*)hits->At(iHit);
+    Double_t xz[2];
+    if(!fSegmentation->GlobalToDet(hit->GetModule(),hit->GetXG(),hit->GetYG(),hit->GetZG(),xz[0],xz[1])) continue;
+    AliITSDigitUpgrade digit;
+    digit.SetSignal(hit->GetIonization());
+    digit.SetNelectrons(hit->GetIonization()/(3.62*1e-09));
+    digit.SetLayer(hit->GetModule()); 
+    digit.SetTrackID(hit->GetTrack()); 
+    
+    Int_t xpix = 999;
+    if(fSegmentation->GetCellSizeX(hit->GetModule())!=0) xpix =(Int_t) (xz[0]/ fSegmentation->GetCellSizeX(hit->GetModule()));
+    
+    Int_t zpix = 999; // shift at the next line to have zpix always positive. Such numbers are used to build the Pixel Id in the layer (> 0!) 
+    if(fSegmentation->GetCellSizeZ(hit->GetModule())!=0){
+      zpix =(Int_t)((xz[1]+fHalfLength.At(hit->GetModule())) / fSegmentation->GetCellSizeZ(hit->GetModule())); 
+    }
+    digit.SetPixId(xpix,zpix);
+
+    
+    new((*pSdigList[hit->GetModule()])[nSdigit[hit->GetModule()]++]) AliITSDigitUpgrade(digit);
+  }
+  
+  AliDebug(1,"Stop Hit2SumDig.");
+}
+//_______________________________________________________________________________________________
+void AliITSupgrade::MakeBranch(Option_t *option){
+  
+  //Create Tree branches 
+  AliDebug(1,Form("Start with option= %s.",option));
+  
+  const Int_t kBufSize = 4000;
+  
+  const char *cH = strstr(option,"H");
+  const char *cD = strstr(option,"D");
+  const char *cR = strstr(option,"R");
+  const char *cS = strstr(option,"S");
+
+  if(cH&&fLoader->TreeH()){
+
+    HitCreate();
+    MakeBranchInTree(fLoader->TreeH(),"ITSupgrade",&fHits,kBufSize,0);   
+  }
+
+    
+  if(cS&&fLoader->TreeS()){
+    SDigitsCreate();
+    for(Int_t i=0;i<fNlayers;i++) MakeBranchInTree(fLoader->TreeS(),Form("Layer%d",i),&((*fSdigits)[i]),kBufSize,0);
+  }
+
+
+  if(cD&&fLoader->TreeD()){
+    DigitsCreate();
+    for(Int_t i=0;i<fNlayers;i++) MakeBranchInTree(fLoader->TreeD(),Form("Layer%d",i),&((*fDigits)[i]),kBufSize,0);
+  }
+
+  if(cR&&fLoader->TreeR()){
+    ClustersCreate();
+    for(Int_t i=0;i<fNlayers;i++) MakeBranchInTree(fLoader->TreeR(),Form("Layer%d",i),&((*fClusters)[i]),kBufSize,0);
+  }
+
+  AliDebug(1,"Stop.");
+}
+//____________________________________________________________________________________________________ 
+void AliITSupgrade::SetTreeAddress()
+{
+  //Set branch address for the Hits and Digits Tree.
+  AliDebug(1,"Start.");
+  if(fLoader->TreeH() && fLoader->TreeH()->GetBranch("ITSupgrade" )){
+    HitCreate();
+    fLoader->TreeH()->SetBranchAddress("ITSupgrade",&fHits);
+
+  }
+
+
+    
+  if(fLoader->TreeS() && fLoader->TreeS()->GetBranch("Layer0" )){
+    SDigitsCreate();
+    for(int i=0;i<fNlayers;i++){
+      fLoader->TreeS()->SetBranchAddress(Form("Layer%d",i),&((*fSdigits)[i]));
+    }
+  }
+
+    
+  if(fLoader->TreeD() && fLoader->TreeD()->GetBranch("Layer0")){
+    DigitsCreate(); 
+    for(int i=0;i<fNlayers;i++){
+      fLoader->TreeD()->SetBranchAddress(Form("Layer%d",i),&((*fDigits)[i]));
+    }
+  }
+  if(fLoader->TreeR() && fLoader->TreeR()->GetBranch("Layer0")){
+    ClustersCreate(); 
+    for(int i=0;i<fNlayers;i++){
+      fLoader->TreeR()->SetBranchAddress(Form("Layer%d",i),&((*fClusters)[i]));
+    }
+  }
+  AliDebug(1,"Stop.");
+}
+
+
+
+
+
diff --git a/ITS/UPGRADE/AliITSupgrade.h b/ITS/UPGRADE/AliITSupgrade.h
new file mode 100644 (file)
index 0000000..7f2d453
--- /dev/null
@@ -0,0 +1,119 @@
+#ifndef ALIITSUPGRADE_H
+#define ALIITSUPGRADE_H
+
+/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
+ * See cxx source for full Copyright notice                               */
+
+/* $Id$ */
+
+//========================================================================
+//
+//      Geometry of the Inner Tracking System Upgrade based on TGeo
+//
+//
+//   Authors: A. Mastroserio
+//            C. Terrevoli
+//            annalisa.mastroserio@cern.ch
+//           cristina.terrevoli@ba.infn.it
+//
+//========================================================================
+
+//
+//ITS class for new geometry based on TGeo
+//
+
+#include "AliITS.h"             //base class 
+#include "AliITSsegmentationUpgrade.h"
+#include "AliITSupgradeDigitizer.h"
+#include <TArrayS.h>
+
+class TGeoVolume;
+class TGeoVolumeAssembly;
+class TArrayD;
+class TClonesArray;
+class TObjArray;
+class AiITShit;
+class AliITSupgrade : public AliITS //TObject-TNamed-AliModule-AliDetector-AliITS-AliITSupgrade
+{
+ public:
+  AliITSupgrade();                                                    //default ctor
+  AliITSupgrade(const char *name, const char *title, TArrayD widths, TArrayD radii,TArrayD halfLengths, TArrayD radiiCu, TArrayD widthsCu, TArrayS copper,Bool_t bp, Double_t radiusBP, Double_t widthPB, Double_t halfLengthsBP);  //ctor
+  virtual       ~AliITSupgrade();                                       //dtor
+  
+  //framework part+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 
+  void    AddAlignableVolumes() const;             //from AliModule invoked from AliMC           
+  void    CreateMaterials  ();                     //from AliModule invoked from AliMC
+  void    CreateGeometry   ();                     //from AliModule invoked from AliMC                     
+  void    Init             ();                     //from AliModule invoked from AliMC::InitGeometry()
+  void    StepManager      ();                     //from AliModule invoked from AliMC::Stepping()
+  void    Hits2SDigits();
+  void    MakeBranch      (Option_t *opt="");        //from AliModule invokde from AliRun::Tree2Tree() to make requested ITSupgrade branch
+  void    SetTreeAddress  (                );        //from AliModule invoked from AliRun::GetEvent(), AliLoader::SetTAddrInDet()
+          
+  //create containers++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+  void     HitCreate()            {if(fHits)return; fHits=new TClonesArray("AliITShit"); fNhits=0;     }//create hits list 
+
+  TObjArray*      SDigitsList()            const{return fSdigits;}//get digits list for all layers
+  TClonesArray*   SDigitsList(Int_t layer) const{return fSdigits ? (TClonesArray *)fSdigits->At(layer):0;}//get sdigits list for a layer
+  void            SDigitsCreate()            {if (fSdigits) return; 
+    fSdigits=new  TObjArray(fNlayers);
+    for(Int_t i=0;i<fNlayers;i++)fSdigits->AddAt(new TClonesArray("AliITSDigitUpgrade"),i);}//create digits list
+  void           SDigitsReset ()              {if(fSdigits) for(int i=0;i<fNlayers;i++)fSdigits->At(i)->Clear();                     }//clean sdigits list  
+     
+     
+     
+  TObjArray*      DigitsList()            const{return fDigits;}//get digits list for all layers
+  TClonesArray*   DigitsList(Int_t layer) const{return fDigits ? (TClonesArray *)fDigits->At(layer):0;}//get digits list for chamber
+  void            DigitsCreate()            {if (fDigits) return; 
+    fDigits=new TObjArray(fNlayers);
+    for(Int_t i=0;i<fNlayers;i++)fDigits->AddAt(new TClonesArray("AliITSDigitUpgrade"),i);}//create digits list
+  void          DigitsReset ()              {if(fDigits)for(int i=0;i<fNlayers;i++)fDigits->At(i)->Clear();                     }//clean digits list
+
+  TObjArray*    ClusterList()           const{return fClusters;}//get clusters list for all layers
+  TClonesArray* ClusterList(Int_t layer)const{return fClusters ? (TClonesArray *)fClusters->At(layer):0;}//get clusters list for chamber
+  void          ClustersCreate()             {if (fClusters) return; //PH do not recreate existing containers
+    fClusters=new TObjArray(fNlayers); 
+    for(Int_t i=0;i<fNlayers;i++)fClusters->AddAt(new TClonesArray("TObject"),i);}//create clusters list
+  void   ClusterReset ()             {if(fClusters)for(int i=0;i<fNlayers;i++)fClusters->At(i)->Clear();                     }//clean clusters list
+
+  AliDigitizer*   CreateDigitizer  (AliRunDigitizer *m) const {return new AliITSupgradeDigitizer(m);}  //from AliModule invoked from AliSimulation::RunDigitization()
+           
+  void Hit2SumDig(TClonesArray *hits,TObjArray *pSDig, Int_t *nSdigit);
+
+  enum EMedia {kAir=0,kSi=1,kBe=2, kCu=3};                         //media ids used in CreateMaterials  
+    
+
+  // Geometry/segmentation creation part
+  TGeoVolumeAssembly * CreateVol();
+  void SetFullSegmentation(TArrayD xsize, TArrayD zsize);
+
+
+  void StepHistory();
+
+ protected:
+  TArrayD fWidths;
+  TArrayD fRadii;
+  TArrayD fRadiiCu;
+  TArrayD fWidthsCu;
+  TArrayS fCopper;
+  Bool_t fBeampipe;
+  Double_t fRadiusBP;
+  Double_t fWidthBP;
+  Double_t fHalfLengthBP;
+  Int_t   fNlayers;
+  TArrayD fHalfLength;
+  TObjArray            *fSdigits;                 //![fNlayers] list of sdigits
+  TObjArray            *fDigits;                     //![fNlayers] list of digits per layer
+  TObjArray            *fClusters;                     //![fNlayers] list of clusters per layer
+  AliITSsegmentationUpgrade *fSegmentation;
+  
+ private:
+  AliITSupgrade(const AliITSupgrade& u);              //dummy copy constructor
+  AliITSupgrade &operator=(const AliITSupgrade& u);   //dummy assignment operator
+
+  ClassDef(AliITSupgrade,2)                                                                //ITS Upgrade full version for simulation
+  
+    };
+
+#endif
+
diff --git a/ITS/UPGRADE/AliITSupgradeDigitizer.cxx b/ITS/UPGRADE/AliITSupgradeDigitizer.cxx
new file mode 100644 (file)
index 0000000..99bf42c
--- /dev/null
@@ -0,0 +1,195 @@
+/**************************************************************************
+ * Copyright(c) 1998-2000, ALICE Experiment at CERN, All rights reserved. *
+ *                                                                        *
+ * Author: The ALICE Off-line Project.                                    *
+ * Contributors are mentioned in the code where appropriate.              *
+ *                                                                        *
+ * Permission to use, copy, modify and distribute this software and its   *
+ * documentation strictly for non-commercial purposes is hereby granted   *
+ * without fee, provided that the above copyright notice appears in all   *
+ * copies and that both the copyright notice and this permission notice   *
+ * appear in the supporting documentation. The authors make no claims     *
+ * about the suitability of this software for any purpose. It is          *
+ * provided "as is" without express or implied warranty.                  *
+ **************************************************************************/
+//.
+
+/* $Id$ */
+
+#include <AliRun.h>
+#include <AliRunLoader.h>
+#include "AliRunDigitizer.h"
+#include <AliLoader.h>
+#include <AliLog.h>
+#include "AliITSupgradeDigitizer.h"
+#include "AliITSDigitUpgrade.h"
+#include "AliITSupgrade.h"
+#include <TObjArray.h>
+#include <TClonesArray.h>
+
+extern TRandom *gRandom;
+
+ClassImp(AliITSupgradeDigitizer)
+    
+  void AliITSupgradeDigitizer::SetConfiguration(TArrayD xcell, TArrayD zcell)
+{
+  
+  if(xcell.GetSize()!=zcell.GetSize()) AliError(" !! The # of X cells and Z cells differ !!");
+  
+  fNlayers = xcell.GetSize();
+  
+  if(fNlayers > 9) {
+    AliError("*  Only 9 layers can be be filled  ...Exiting!!! *");
+    return;
+  }
+  
+  fNxCells.Set(fNlayers);
+  fNzCells.Set(fNlayers);
+  for(Int_t i=0; i<fNlayers; i++){
+    fNxCells.AddAt(xcell.At(i),i);
+    fNzCells.AddAt(zcell.At(i),i); 
+  }  
+}   
+//______________________________________________________________________________      
+void AliITSupgradeDigitizer::Exec(Option_t*)
+{
+  // This method is responsible for merging sdigits to a list of digits
+  //  Disintegration leeds to the fact that one hit affects several neighbouring pads, 
+  // which means that the same pad might be affected by few hits.     
+  
+  AliDebug(1,Form("Start with %i input(s) for event %i",fManager->GetNinputs(),fManager->GetOutputEventNr()));
+  
+  
+  AliITSsegmentationUpgrade *s = new AliITSsegmentationUpgrade();
+  SetConfiguration(s->GetFullCellSizeX(),s->GetFullCellSizeZ());
+  delete s;
+  //First we read all sdigits from all inputs  
+  AliRunLoader *pInRunLoader=0;//in and out Run loaders
+  AliLoader    *pITSLoader=0;//in and out ITS loaders  
+  
+  TClonesArray sdigits[10];
+  for(Int_t i=0; i<fNlayers; i++) sdigits[i].SetClass("AliITSDigitUpgrade");//tmp storage for sdigits sum up from all input files
+  
+  
+  Int_t total[10]={0,0,0,0,0,0,0,0,0,0};
+  for(Int_t inFileN=0;inFileN<fManager->GetNinputs();inFileN++){//files loop
+    
+    pInRunLoader  = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(inFileN));          //get run loader from current input 
+    pITSLoader = pInRunLoader->GetLoader("ITSLoader"); 
+    if(pITSLoader==0) {
+      continue;       //no ITS in this input, check the next input
+      AliDebug(1,"no ITS lodader, checking in the other input \n"); 
+    }
+    
+    if (!pInRunLoader->GetAliRun()) pInRunLoader->LoadgAlice();
+    AliITSupgrade* pITS=(AliITSupgrade*)pInRunLoader->GetAliRun()->GetDetector("ITS"); 
+    
+    pITSLoader->LoadSDigits();  
+    
+    pITSLoader->TreeS()->GetEntry(0);                          //take list of ITS sdigits from current input 
+    
+    for(Int_t is=0;is<pITS->SDigitsList()->GetEntries();is++){      
+      
+      //collect sdigits from current input
+      for(Int_t ientr =0; ientr < ((TClonesArray*)pITS->SDigitsList()->At(is))->GetEntries(); ientr++){
+       AliITSDigitUpgrade *pSDig=(AliITSDigitUpgrade*)((TClonesArray*)pITS->SDigitsList()->At(is))->At(ientr);
+       pSDig->AddTidOffset(fManager->GetMask(inFileN)); // -> To be introduced for merging (apply TID shift since all inputs count tracks independently starting from 0)
+       new((sdigits[is])[total[is]++]) AliITSDigitUpgrade(*pSDig);  
+      }
+    }
+    
+    pITSLoader->UnloadSDigits();   
+    pITS->SDigitsReset(); //close current input and reset 
+  }//files loop  
+  
+  AliRunLoader *pOutRunLoader  = AliRunLoader::GetRunLoader(fManager->GetOutputFolderName());  //open output stream (only 1 possible)
+  AliLoader    *pOutITSLoader = pOutRunLoader->GetLoader("ITSLoader");                        
+  AliRun *pArun = pOutRunLoader->GetAliRun();
+  AliITSupgrade      *pOutITS       = (AliITSupgrade*)pArun->GetDetector("ITS");      
+  pOutITSLoader->MakeTree("D");   pOutITS->MakeBranch("D");                                    //create TreeD in output stream
+  pOutITS->SetTreeAddress();
+  
+  Sdigits2Digits(sdigits,pOutITS->DigitsList());
+  
+  pOutITSLoader->TreeD()->Fill();              //fill the output tree with the list of digits
+  pOutITSLoader->WriteDigits("OVERWRITE");     //serialize them to file
+  
+  for(Int_t i=0; i< fNlayers; i++) sdigits[i].Clear();                      //remove all tmp sdigits
+  pOutITSLoader->UnloadDigits();   
+  pOutITS->DigitsReset(); 
+}//Exec()
+//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+void AliITSupgradeDigitizer::Sdigits2Digits(TClonesArray *pSDigitList,TObjArray *pDigitList)
+{   
+  TClonesArray *pLst[100]; Int_t iCnt[100];
+  for(Int_t i=0;i<fNlayers;i++){ 
+    pLst[i]=(TClonesArray*)(*pDigitList)[i];
+    iCnt[i]=0; if(pLst[i]->GetEntries()!=0) AliErrorClass("Some of digits lists is not empty");  //in principle those lists should be empty 
+  }
+   
+  AliInfo("starting loop over gli sdigits to create the digits");
+  Double_t eloss =0.;
+  Double_t nele = 0.;
+  ULong_t  pixid = 999;
+  Int_t tids[3]={-1,-1,-1};
+  
+  Float_t elossID[3]={-1.,-1.,-1.};
+  AliInfo("starting layers");
+  AliDebug(1,"starting loop over layers");
+   
+  for(Int_t ilay=0;ilay<fNlayers;ilay++){ 
+     
+    AliITSDigitUpgrade *tmpdig=0x0;
+    pSDigitList[ilay].Sort();
+     
+    Int_t iNdigPart=0; 
+    AliDebug(1,"starting loop over sdigits to create digits");
+    for(Int_t isdigentr=0; isdigentr<pSDigitList[ilay].GetEntries(); isdigentr++){
+      tmpdig = (AliITSDigitUpgrade*)(pSDigitList[ilay].At(isdigentr) )  ;
+      if(tmpdig->GetPixId()==pixid) { 
+       iNdigPart++; 
+       if(iNdigPart<=3) {
+          tids[iNdigPart] = tmpdig->GetTrack(0);
+          elossID[iNdigPart] = tmpdig->GetSignal();
+       }     
+       eloss+=tmpdig->GetSignal();
+       nele+=tmpdig->GetNelectrons();
+       continue;
+      }
+      AliITSDigitUpgrade digit(pixid,eloss);
+
+      digit.SetNelectrons(nele); 
+      digit.SetLayer(ilay);
+      digit.SetTids(tids);
+      digit.SetSignalID(elossID);       
+      if(isdigentr!=0) new((*pLst[ilay])[iCnt[ilay]++]) AliITSDigitUpgrade(digit);
+      eloss = tmpdig->GetSignal();
+      nele = tmpdig->GetNelectrons();
+      pixid=tmpdig->GetPixId(); 
+      tids[0]=tmpdig->GetTrack(0);
+      tids[1]=tids[2]=-1;      
+      elossID[0]=tmpdig->GetSignal();
+      elossID[1]=elossID[2]=-1;   
+    }
+     
+    if(!tmpdig) AliDebug(1,"\n \n---------> tmpdig is null...break is expected ! \n");
+    else AliDebug(1," tmpdig exists \n");
+     
+    if(tmpdig){
+      tmpdig->SetSignal(eloss);  
+      tmpdig->SetPixId(pixid); 
+      tmpdig->SetTids(tids); 
+      tmpdig->SetSignalID(elossID);
+      tmpdig->SetNelectrons(nele);  
+      tmpdig->SetLayer(ilay); 
+      //cout<<" tmpdigit : pixid "<< pixid<< "  tids "<< tids << " nele " << nele << " ilay "<<ilay<<endl;     
+      new((*pLst[ilay])[iCnt[ilay]++]) AliITSDigitUpgrade(*tmpdig);
+    }     
+    AliDebug(1,"ending loop over sdigits to create digits");
+
+  }
+  AliDebug(1,"ending loop over layers");  
+
+}
+
diff --git a/ITS/UPGRADE/AliITSupgradeDigitizer.h b/ITS/UPGRADE/AliITSupgradeDigitizer.h
new file mode 100644 (file)
index 0000000..8cb27e0
--- /dev/null
@@ -0,0 +1,49 @@
+#ifndef ALIITSUPGRADEDIGITIZER_H
+#define ALIITSUPGRADEDIGITIZER_H
+
+/* Copyright (c) 1998-2001, ALICE Experiment at CERN, All rights reserved *
+ * See cxx source for full Copyright notice                               */
+
+/* $Id$ */
+
+//////////////////////////////////////////////////////////////////
+//                                                             //
+//                  Digitizer class for ITS Upgrade            //
+//                                                             //
+//                                                             //
+//    Authors: A.Mastroserio, C.Terrevoli                      //
+//            annalisa.mastroserio@cern.ch                     //
+//            cristina.terrevoli@ba.infn.it                    //
+//                                                              //
+//////////////////////////////////////////////////////////////////
+
+
+#include <AliDigitizer.h>
+#include <TArrayD.h>
+
+class TClonesArray;
+class TObjArray;
+
+class AliITSupgradeDigitizer : public AliDigitizer //TObject-TNamed-TTask-AliDigitizer-AliITSupgradeDigitizer
+{
+ public:
+  AliITSupgradeDigitizer():AliDigitizer(),fNxCells(0),fNzCells(0),fNlayers(0)              {;}
+    AliITSupgradeDigitizer(AliRunDigitizer *pRunDig):AliDigitizer(pRunDig),fNxCells(0),fNzCells(0),fNlayers(0){;}
+      virtual ~AliITSupgradeDigitizer()                                                {;}
+      void   SetConfiguration(TArrayD xcell, TArrayD zcell);
+      void   Exec(Option_t* option=0);                //virtual
+   
+      void    Sdigits2Digits(TClonesArray *pSDigitList,TObjArray *pDigitLst);
+ protected:
+      TArrayD fNxCells;
+      TArrayD fNzCells;
+      Short_t fNlayers;    
+      ClassDef(AliITSupgradeDigitizer,0)
+       };    
+
+#endif
+
+
diff --git a/ITS/libITSUpgradebase.pkg b/ITS/libITSUpgradebase.pkg
new file mode 100644 (file)
index 0000000..ad6725c
--- /dev/null
@@ -0,0 +1,18 @@
+#-*- Mode: Makefile -*-
+
+SRCS = UPGRADE/AliITSDigitUpgrade.cxx UPGRADE/AliITSsegmentationUpgrade.cxx  
+
+
+HDRS:=  $(SRCS:.cxx=.h)
+
+DHDR=ITSUpgradeBaseLinkDef.h
+
+EINCLUDE:=$(GEANT3_ROOT)/TGeant3 TPC RAW ITS ITS/UPGRADE
+
+
+ifeq (win32gcc,$(ALICE_TARGET))
+PACKSOFLAGS:= $(SOFLAGS) -L$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET) \
+                         -lSTEER -lCDB -lSTEERBase \
+                         -lRAWDatasim -lRAWDatarec -lRAWDatabase \
+                         -L$(ROOTLIBDIR) -lGui -lGeom
+endif
diff --git a/ITS/libITSUpgraderec.pkg b/ITS/libITSUpgraderec.pkg
new file mode 100644 (file)
index 0000000..989c38c
--- /dev/null
@@ -0,0 +1,24 @@
+#-*- Mode: Makefile -*-
+
+SRCS = UPGRADE/AliITSUpgradeClusterFinder.cxx \
+               UPGRADE/AliITSUpgradeClusterList.cxx \
+               UPGRADE/AliITSUpgradeClusterListNode.cxx \
+               UPGRADE/AliITSlayerUpgrade.cxx \
+               UPGRADE/AliITStrackerUpgrade.cxx \
+               UPGRADE/AliITSUpgradeReconstructor.cxx 
+
+HDRS:=  $(SRCS:.cxx=.h)
+
+DHDR=ITSUpgradeRecLinkDef.h
+
+EINCLUDE:=TPC RAW ITS ITS/UPGRADE
+
+#  EXPORT:=AliITStrackV2.h                \
+#        AliITSVertexer.h AliITSRecoParam.h
+
+ifeq (win32gcc,$(ALICE_TARGET))
+PACKSOFLAGS:= $(SOFLAGS) -L$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET) \
+                         -lITSUpgradebase -lSTEER -lESD -lCDB -lSTEERBase \
+                         -lRAWDatarec \
+                         -L$(ROOTLIBDIR) -lEG -lGeom
+endif
diff --git a/ITS/libITSUpgradesim.pkg b/ITS/libITSUpgradesim.pkg
new file mode 100644 (file)
index 0000000..075288a
--- /dev/null
@@ -0,0 +1,18 @@
+#-*- Mode: Makefile -*-
+
+SRCS = UPGRADE/AliITSupgradeDigitizer.cxx UPGRADE/AliITSupgrade.cxx  
+
+
+HDRS:=  $(SRCS:.cxx=.h)
+
+DHDR=ITSUpgradeSimLinkDef.h
+
+EINCLUDE:=TPC RAW ITS ITS/UPGRADE
+
+ifeq (win32gcc,$(ALICE_TARGET))
+PACKSOFLAGS:= $(SOFLAGS) -L$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET) \
+                         -lITSUpgradebase -lSTEER -lCDB -lSTEERBase \
+                         -L$(ROOTLIBDIR) -lVMC -lEG -lGeom
+endif
+
+