-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrackAna_module.cc1July2021
858 lines (729 loc) · 40.2 KB
/
trackAna_module.cc1July2021
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
// Code developed for estimating charge from SpacePoint object with "reco3d" module but this object is not availble in MUSUN sample so it is not is use for the time being // So now going to developo code for calculating the tracklength using Space Point object :
// Date - 24/April/2020/
// LArSoft includes
#include "lardataobj/Simulation/SimChannel.h"
#include "lardataobj/RecoBase/Hit.h"
#include "lardataobj/RecoBase/Cluster.h"
#include "lardataobj/RecoBase/SpacePoint.h"
#include "lardata/DetectorInfoServices/DetectorPropertiesService.h"
#include "lardata/DetectorInfoServices/DetectorClocksService.h"
#include "larcore/Geometry/Geometry.h"
#include "larcorealg/Geometry/GeometryCore.h"
#include "larcoreobj/SimpleTypesAndConstants/geo_types.h"
#include "nusimdata/SimulationBase/MCParticle.h"
#include "nusimdata/SimulationBase/MCTruth.h"
#include "larsim/Simulation/LArG4Parameters.h"
// Framework includes
#include "art/Framework/Core/EDAnalyzer.h"
#include "art/Framework/Principal/Event.h"
#include "art/Framework/Principal/Handle.h"
#include "art/Framework/Services/Registry/ServiceHandle.h"
#include "art_root_io/TFileService.h"
#include "art/Framework/Core/ModuleMacros.h"
#include "canvas/Persistency/Common/FindManyP.h"
#include "canvas/Utilities/Exception.h"
#include "dune/AnaUtils/DUNEAnaSpacePointUtils.h"
// Utility libraries
#include "messagefacility/MessageLogger/MessageLogger.h"
#include "fhiclcpp/ParameterSet.h"
#include "fhiclcpp/types/Table.h"
#include "fhiclcpp/types/Atom.h"
#include "cetlib/pow.h" // cet::sum_of_squares()
// ROOT includes. Note: To look up the properties of the ROOT classes,
// use the ROOT web site; e.g.,
// <https://root.cern.ch/doc/master/annotated.html>
#include "TH1.h"
#include "TF2.h"
#include "TH2.h"
#include "TTree.h"
#include "TLorentzVector.h"
#include "TMath.h"
#include "TVector3.h"
#include "TVectorD.h"
#include "TMatrixD.h"
#include "TMatrixDSym.h"
#include "TGraph2D.h"
#include "TPolyLine3D.h"
#include"TFile.h"
#include"TCanvas.h"
#include"TLegend.h"
#include "TStyle.h"
#include <cassert>
// C++ inclu
//ides
#include <map>
#include <cmath>
using namespace std;
namespace lar {
namespace example {
class trackAna : public art::EDAnalyzer
{
public:
//
struct Config {
// Save some typing:
using Name = fhicl::Name;
using Comment = fhicl::Comment;
// One Atom for each parameter
fhicl::Atom<art::InputTag> SimulationLabel {
Name("SimulationLabel"),
Comment("tag of the input data product with the detector simulation information")
};
fhicl::Atom<art::InputTag> HitLabel {
Name("HitLabel"),
Comment("tag of the input data product with reconstructed hits")
};
fhicl::Atom<art::InputTag> ClusterLabel {
Name("ClusterLabel"),
Comment("tag of the input data product with reconstructed clusters")
};
fhicl::Atom<art::InputTag> SpacePointLabel {
Name("SpacePointLabel"),
Comment("tag of the input data product with reconstructed Space Point ")
};
fhicl::Atom<int> PDGcode1 {
Name("PDGcode1"),
Comment("particle type (PDG ID) of the primary particle to be selected")
};
fhicl::Atom<int> PDGcode2 {
Name("PDGcode2"),
Comment("particle type (PDG ID) of the primary particle to be selected")
};
fhicl::Atom<double> BinSize {
Name("BinSize"),
Comment("dx [cm] used for the dE/dx calculation")
};
}; // Config
//
using Parameters = art::EDAnalyzer::Table<Config>;
explicit trackAna(Parameters const& config);
virtual void beginJob() override;
virtual void beginRun(const art::Run& run) override;
virtual void analyze (const art::Event& event) override;
private:
// The parameters we'll read from the .fcl file.
art::InputTag fSimulationProducerLabel; ///< The name of the producer that tracked simulated particles through the detector
art::InputTag fHitProducerLabel; ///< The name of the producer that created hits
art::InputTag fClusterProducerLabel; ///< The name of the producer that created clusters
art::InputTag fSpacePointProducerLabel;
int fSelectedPDG1;
int fSelectedPDG2; ///< PDG code of particle we'll focus on
double fBinSize; ///< For dE/dx work: the value of dx.
// Pointers to the histograms we'll create.
TH1D* fPDGCodeHist; ///< PDG code of all particles
TH1D* fMomentumHist; ///< momentum [GeV] of all selected particles
TH1D* fTrackLengthHist; ///< true length [cm] of all selected particles
TH1D* fHitIntegralHist; ///< Hit ADC Integral
// The n-tuples we'll create.
TTree* fSimulationNtuple; ///< tuple with simulated data
TTree* fSimulationTrackTree;
TTree* fReconstructionNtuple; ///< tuple with reconstructed data
geo::GeometryCore const *fGeometry;
// The comment lines with the @ symbols define groups in doxygen.
/// @name The variables that will go into both n-tuples.
/// @{
int fEvent; ///< number of the event being processed
int fRun; ///< number of the run being processed
int fSubRun; ///< number of the sub-run being processed
/// @}
/// @name The variables that will go into the simulation n-tuple.
/// @{
int fSimPDG; ///< PDG ID of the particle being processed
int fSimTrackID; ///< GEANT ID of the particle being processed
int wireNumber;
// Arrays for 4-vectors: (x,y,z,t) and (Px,Py,Pz,E).
// Note: old-style C++ arrays are considered obsolete. However,
// to create simple n-tuples, we still need to use them.
double fStartXYZT[4]; ///< (x,y,z,t) of the true start of the particle
double fEndXYZT[4]; ///< (x,y,z,t) of the true end of the particle
double fStartPE[4]; ///< (Px,Py,Pz,E) at the true start of the particle
double fEndPE[4]; ///< (Px,Py,Pz,E) at the true end of the particle
const double lineXM = -720; const double lineYM = -600; const double lineZM = 0;
const double lineXP = +720; const double lineYP = +600; const double lineZP = 6500; /// Detector planes position on XYZ axis
int tmx, tmy, tmz, tpx, tpy, tpz;
bool cmx, dmx, cmy, dmy, cmz, dmz;
bool cpx, dpx, cpy, dpy, cpz, dpz;
/// Number of dE/dx bins in a given track.
int fSimNdEdxBins;
double RecTrackExitXposmx;
double RecTrackExitYposmy;
double RecTrackExitZposmz;
double RecTrackExitXpospx;
double RecTrackExitYpospy;
double RecTrackExitZpospz;
double Extpl_track_length1=0.0;
double Stp_muon_track_len=0.0;
double Extpl_track_length=0.0;
double trackLength=0.0;
double SPHitCharge =0.0;
/// The vector that will be used to accumulate dE/dx values as a function of range.
std::vector<double> fSimdEdxBins;
std::vector<double> fSimWireEnergy; ///< vector for dE/dx values
std::vector<int> fSimWireNumber;
/// @}
std::vector<double> fTrackLength;
std::vector<double> fStp_muon_Trj_TrackLength;
std::vector<double> fStp_muon_TrackLen;
std::vector<double> fTrackStartXpos;
std::vector<double> fTrackStartYpos;
std::vector<double> fTrackStartZpos;
std::vector<double> fTrackEndXpos;
std::vector<double> fTrackEndYpos;
std::vector<double> fTrackEndZpos;
std::vector<double >fTrackExitXpos;
std::vector<double >fTrackExitYpos;
std::vector<double >fTrackExitZpos;
std::vector<double>fExtpl_track_length;
std::vector<double >fRTrackExitXpos;
std::vector<double >fRTrackExitYpos;
std::vector<double >fRTrackExitZpos;
/// @name Variables used in the reconstruction n-tuple
/// @{
int fRecoPDG; ///< PDG ID of the particle being processed
int fRecoTrackID; ///< GEANT ID of the particle being processed
/// Number of dE/dx bins in a given track.
int fRecoNdEdxBins;
/// The vector that will be used to accumulate dE/dx values as a function of range.
std::vector<double> fRecodEdxBins;
std::vector<double> fRecoChargeInt;
std::vector<double> fRecoChargeTrue;
std::vector<double> fRecoWireNumber;
std::vector<double> fRecoHitCharge;
std::vector<double> fRecoPeakTime;
std::vector<double> fRec_SpacePoint_X;std::vector<double> fRec_SpacePoint_Y; std::vector<double> fRec_SpacePoint_Z;
std::vector<double> SPLPd_X;std::vector<double> SPLPd_Y; std::vector<double> SPLPd_Z;
std::vector<double> fHitCharge_SP;std::vector<double> SPLPd_HitdQ;
std::vector<double> fHitdQ_track_segment;std::vector<double>muonDir;
/// @}
// Other variables that will be shared between different methods.
geo::GeometryCore const* fGeometryService; ///< pointer to Geometry provider
// detinfo::DetectorClocks const* fTimeService; ///< pointer to detector clock time service provider
double fElectronsToGeV; ///< conversion factor
int fTriggerOffset; ///< (units of ticks) time of expected neutrino event
}; // class EnergyAna
trackAna::trackAna(Parameters const& config)
: EDAnalyzer(config)
, fSimulationProducerLabel(config().SimulationLabel())
, fHitProducerLabel (config().HitLabel())
, fClusterProducerLabel (config().ClusterLabel())
, fSpacePointProducerLabel (config().SpacePointLabel())
, fSelectedPDG1 (config().PDGcode1())
, fSelectedPDG2 (config().PDGcode2())
, fBinSize (config().BinSize())
{
// Get a pointer to the geometry service provider.
fGeometryService = lar::providerFrom<geo::Geometry>();
// The same for detector TDC clock services.
// fTimeService = lar::providerFrom<detinfo::DetectorClocksService>();
// Access to detector properties.
// const detinfo::DetectorProperties* detprop = lar::providerFrom<detinfo::DetectorPropertiesService>();
// fTriggerOffset = detprop->TimeOffsetU();
consumes<std::vector<simb::MCParticle>>(fSimulationProducerLabel);
consumes<std::vector<sim::SimChannel>>(fSimulationProducerLabel);
consumes<art::Assns<simb::MCTruth, simb::MCParticle>>(fSimulationProducerLabel);
consumes<std::vector<recob::Hit>>(fHitProducerLabel);
consumes<std::vector<recob::Cluster>>(fClusterProducerLabel);
consumes<art::Assns<recob::Cluster, recob::Hit>>(fHitProducerLabel);
consumes<std::vector<recob::SpacePoint>>(fSpacePointProducerLabel);
}
//-----------------------------------------------------------------------
void trackAna::beginJob()
{
art::ServiceHandle<art::TFileService const> tfs;
fPDGCodeHist = tfs->make<TH1D>("pdgcodes",";PDG Code;", 5000, -2500, 2500);
fMomentumHist = tfs->make<TH1D>("mom", ";particle Momentum (GeV);", 100, 0., 10.);
fTrackLengthHist = tfs->make<TH1D>("length", ";particle track length (cm);", 200, 0, 5000);
fHitIntegralHist = tfs->make<TH1D>("hitintegral", ";Hit Integral (sumadc);", 200, 0, 1000.);
// hdl_TrueVsRec = tfs->make<TH2F>("hdl_TrueVsRec", "TrueVsRec", 100, 0, 100, 100, 0, 100);
fSimulationNtuple = tfs->make<TTree>("EnergyAnaSimulation", "EnergyAna Simulation");
fSimulationTrackTree = tfs->make<TTree>("TrackExtrapolation", "EnergyAna Extrapolation");
fReconstructionNtuple = tfs->make<TTree>("EnergyAnaReconstruction","EnergyAna Reconstruction");
fSimulationNtuple->Branch("Event", &fEvent, "Event/I");
fSimulationNtuple->Branch("SubRun", &fSubRun, "SubRun/I");
fSimulationNtuple->Branch("Run", &fRun, "Run/I");
fSimulationNtuple->Branch("TrackID", &fSimTrackID, "TrackID/I");
fSimulationNtuple->Branch("PDG", &fSimPDG, "PDG/I");
fSimulationNtuple->Branch("StartXYZT", fStartXYZT, "StartXYZT[4]/D");
fSimulationNtuple->Branch("EndXYZT", fEndXYZT, "EndXYZT[4]/D");
fSimulationNtuple->Branch("StartPE", fStartPE, "StartPE[4]/D");
fSimulationNtuple->Branch("EndPE", fEndPE, "EndPE[4]/D");
fSimulationNtuple->Branch("WireEnergy", &fSimWireEnergy);
fSimulationNtuple->Branch("WireNumber", &fSimWireNumber);
fSimulationTrackTree->Branch("TrackLength", &fTrackLength);
fSimulationTrackTree->Branch("Stp_muon_TrackLength", &fStp_muon_Trj_TrackLength);
fSimulationTrackTree->Branch("TrackExitXpos", &fTrackExitXpos);
fSimulationTrackTree->Branch("TrackExitYpos", &fTrackExitYpos);
fSimulationTrackTree->Branch("TrackExitZpos", &fTrackExitZpos);
fSimulationTrackTree->Branch("SpacePoint_X", &fRec_SpacePoint_X);
fSimulationTrackTree->Branch("SpacePoint_Y", &fRec_SpacePoint_Y);
fSimulationTrackTree->Branch("SpacePoint_Z", &fRec_SpacePoint_Z);
fSimulationTrackTree->Branch("SPExtpl_track_length", &fExtpl_track_length);
fSimulationTrackTree->Branch("Stp_muon_tracklen", &fStp_muon_TrackLen);
fSimulationTrackTree->Branch("RTrackExitXpos", &fRTrackExitXpos);
fSimulationTrackTree->Branch("RTrackExitYpos", &fRTrackExitYpos);
fSimulationTrackTree->Branch("RTrackExitZpos", &fRTrackExitZpos);
fSimulationTrackTree->Branch("RecoChargeInt", &fRecoChargeInt);
fSimulationTrackTree->Branch("RecoChargeTrue", &fRecoChargeTrue);
fSimulationTrackTree->Branch("RecoWireNumber", &fRecoWireNumber);
fSimulationTrackTree->Branch("RecoHitCharge", &fRecoHitCharge);
fSimulationTrackTree->Branch("RecoPeakTime", &fRecoPeakTime);
fSimulationTrackTree->Branch("WireEnergy", &fSimWireEnergy);
fSimulationTrackTree->Branch("WireNumber", &fSimWireNumber);
// fSimulationTrackTree->Branch("SPhitCharge", &fHitCharge_SP);
fSimulationTrackTree->Branch("SPhit_dQ", &SPLPd_HitdQ);
fSimulationTrackTree->Branch("hitdQ_track_segment", &fHitdQ_track_segment);
fSimulationTrackTree->Branch("muon_directon", &muonDir);
fReconstructionNtuple->Branch("Event", &fEvent, "Event/I");
fReconstructionNtuple->Branch("SubRun", &fSubRun, "SubRun/I");
fReconstructionNtuple->Branch("Run", &fRun, "Run/I");
fReconstructionNtuple->Branch("TrackID", &fRecoTrackID, "TrackID/I");
fReconstructionNtuple->Branch("PDG", &fRecoPDG, "PDG/I");
}
void trackAna::beginRun(const art::Run& /*run*/)
{
// How to convert from number of electrons to GeV. The ultimate
// source of this conversion factor is
// ${LARCOREOBJ_INC}/larcoreobj/SimpleTypesAndConstants/PhysicalConstants.h.
// But sim::LArG4Parameters might in principle ask a database for it.
art::ServiceHandle<sim::LArG4Parameters const> larParameters;
fElectronsToGeV = 1./larParameters->GeVToElectrons();
}
//-----------------------------------------------------------------------
void trackAna::analyze(const art::Event& event)
{
// Start by fetching some basic event information for our n-tuple.
fEvent = event.id().event();
fRun = event.run();
fSubRun = event.subRun();
auto const clockData = art::ServiceHandle<detinfo::DetectorClocksService>()->DataFor(event);
auto const detProp = art::ServiceHandle<detinfo::DetectorPropertiesService>()->DataFor(event, clockData);
art::Handle< std::vector<simb::MCParticle> > particleHandle;
if (!event.getByLabel(fSimulationProducerLabel, particleHandle))
{
throw cet::exception("trackAna")
<< " No simb::MCParticle objects in this event - "
<< " Line " << __LINE__ << " in file " << __FILE__ << std::endl;
}
art::Handle< std::vector<recob::Hit> > hitHandle;
if (!event.getByLabel(fHitProducerLabel, hitHandle)) return;
TGraph2D * SP_gr = new TGraph2D();
TGraph2D * Traj_gr = new TGraph2D();
// TGraph2D * SP_AvePos_gr = new TGraph2D();
TGraph2D *SP_TracePoint_gr = new TGraph2D();
// TGraph2D *SPLPd_gr = new TGraph2D();
// Clearing All the vectors here
fTrackLength.clear();fStp_muon_Trj_TrackLength.clear();fTrackExitXpos.clear();fTrackExitYpos.clear();fTrackExitZpos.clear();
fRec_SpacePoint_X.clear();fRec_SpacePoint_Y.clear(); fRec_SpacePoint_Z.clear();
SPLPd_X.clear();SPLPd_Y.clear();SPLPd_Z.clear();fExtpl_track_length.clear();fStp_muon_TrackLen.clear();
fRTrackExitXpos.clear(); fRTrackExitYpos.clear(); fRTrackExitZpos.clear();
fSimWireEnergy.clear();fSimWireNumber.clear();fRecoChargeInt.clear(); fRecoChargeTrue.clear();fRecoPeakTime.clear(); fRecoHitCharge.clear();
fHitdQ_track_segment.clear(); SPLPd_HitdQ.clear(); fHitCharge_SP.clear(); // clearing hits charge associated with Spacepoint
muonDir.clear();
// Clearing Vectors End here :
art::Handle< std::vector<recob::SpacePoint> > recobspacepoints;
event.getByLabel(fSpacePointProducerLabel, recobspacepoints);
if (!recobspacepoints->empty())
{
auto simChannelHandle = event.getValidHandle<std::vector<sim::SimChannel>>(fSimulationProducerLabel);
std::map< int, const simb::MCParticle* > particleMap;
for ( auto const& particle : (*particleHandle) )
{
fSimTrackID = particle.TrackId();
particleMap[fSimTrackID] = &particle;
fSimPDG = particle.PdgCode();
fPDGCodeHist->Fill( fSimPDG );
trackLength=0.0;
// For this example, we want to fill the n-tuples and histograms
// only with information from the primary particles in the
// event, whose PDG codes match a value supplied in the .fcl file.
if( particle.Process() != "primary" && ( fSimPDG != fSelectedPDG1 || fSimPDG != fSelectedPDG2 ))
continue;
// A particle has a trajectory, consisting of a set of
// 4-positions and 4-mommenta.
const size_t numberTrajectoryPoints = particle.NumberTrajectoryPoints();
// For trajectories, as for vectors and arrays, the first
// point is #0, not #1.
const int last = numberTrajectoryPoints - 1;
const TLorentzVector& positionStart = particle.Position(0);
const TLorentzVector& positionEnd = particle.Position(last);
const TLorentzVector& momentumStart = particle.Momentum(0);
const TLorentzVector& momentumEnd = particle.Momentum(last);
fMomentumHist->Fill( momentumStart.P() );
positionStart.GetXYZT( fStartXYZT );
positionEnd.GetXYZT( fEndXYZT );
momentumStart.GetXYZT( fStartPE );
momentumEnd.GetXYZT( fEndPE );
TVector3 dirVMC = momentumStart.Vect();
double dmv = dirVMC.Mag();
if (dmv==0) continue;
TVector3 udir = dirVMC*(1.0/dmv);
TVector3 lastpos(0,0,0);
bool first = true;
int tpn = 0;
for(size_t tp=1; tp<numberTrajectoryPoints; ++tp)
{
TVector3 pos = particle.Position(tp).Vect();
if (pos.X()<lineXP && pos.X()>lineXM && pos.Y()<lineYP && pos.Y()>lineYM && pos.Z()<lineZP && pos.Z()>lineZM)
{ if (!first)
{
trackLength +=(pos-lastpos).Mag();
Traj_gr->SetPoint(tpn,pos.X(),pos.Y(),pos.Z());
tpn++;
}
else
{
first = false;
}
lastpos = pos;
}
}
// const double trackLength = ( positionEnd - positionStart ).Rho();
fTrackLength.push_back(trackLength);
cout<< "Track length of Particle is : : " << trackLength << " cm"<<endl;
fTrackLengthHist->Fill(trackLength);
} // MC particle for loop new
// i ############################################## END of TRUE TRACK EXTRAPOLATION ############################################
// ########## Reconstructed Space Point and Track Length Estimation ###############
art::ServiceHandle<geo::Geometry> geom;
// dune_ana::DUNEAnaSpacePointUtils SPcharge;
art::Handle< std::vector<recob::SpacePoint> > recobspacepoints;
event.getByLabel(fSpacePointProducerLabel, recobspacepoints);
for(size_t isp=0;isp<recobspacepoints->size(); ++isp)
{
art::Ptr<recob::SpacePoint> recSPoint(recobspacepoints, isp);
const recob::SpacePoint& RecSP = *recSPoint;
// std::vector<art::Ptr<recob::Hit>> spacePointHits = ::dune_ana::DUNEAnaSpacePointUtils::GetHits(recSPoint, event, "pandora");
// std::vector<art::Ptr<recob::Hit>> spacePointHits = SPcharge.GetHits(recSPoint, event, "pandora");
// for ( auto const& SPhits : (spacePointHits) )
// {
// auto hitChannelNumber = hit.Channel();
// auto HitCharge = SPhits->Integral();
// SPHitCharge = SPHitCharge + HitCharge;
// if ( fGeometryService->SignalType( SPhits->Channel() ) != geo::kCollection)
// continue;
// fHitCharge_SP.push_back(SPhits->Integral());
// double SP_hit_x = detProp.ConvertTicksToX(SPhits->PeakTime(), SPhits->WireID().Plane, SPhits->WireID().TPC, SPhits->WireID().Cryostat );
// double SP_hit_z = geom->Wire(SPhits->WireID()).GetCenter().Z();
// cout<<"Hits and Spacepoint Z and X coordinate is : "<< SP_hit_z<<"\t"<<RecSP.XYZ()[2]<<"\t X => "<<SP_hit_x<<"\t"<<RecSP.XYZ()[0]<<"\n";
// }
// fHitCharge_SP.push_back(spacePointHits.Integral());
SP_gr->SetPoint(isp,RecSP.XYZ()[0],RecSP.XYZ()[1],RecSP.XYZ()[2]);
fRec_SpacePoint_X.push_back(RecSP.XYZ()[0]);
fRec_SpacePoint_Y.push_back(RecSP.XYZ()[1]);
fRec_SpacePoint_Z.push_back(RecSP.XYZ()[2]);
} // for ()
// fHitCharge_SP.push_back(SPHitCharge);
// SPHitCharge = 0.0;
// $$i$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ PCA ##########################################
double* xyz[3];
TVector3 pos(0,0,0);
TVector3 dir;
xyz[0] = fRec_SpacePoint_X.data();
xyz[1] = fRec_SpacePoint_Y.data();
xyz[2] = fRec_SpacePoint_Z.data();
size_t npts = fRec_SpacePoint_X.size();
if (npts < 2)
{
throw cet::exception("tpcvechitfinder2_module.cc: too few TPCClusters to fit a line in linefit");
}
TMatrixDSym covmat(3); // covariance matrix (use symmetric version)
// position is just the average of the coordinates
double psum[3] = {0,0,0};
for (size_t ipoint=0; ipoint<npts; ++ipoint)
{
for(size_t j=0; j<3; j++)
{
psum[j] += xyz[j][ipoint];
}
}
for (size_t j=0; j<3; ++j)
{
psum[j] /= npts;
}
pos.SetXYZ(psum[0],psum[1],psum[2]);
for(size_t i=0; i<3; ++i)
{
for (size_t j=0; j<= i; ++j)
{
double csum=0;
for (size_t ipoint=0; ipoint<npts; ++ipoint)
{
csum += (xyz[i][ipoint] - psum[i]) * (xyz[j][ipoint] - psum[j]);
}
csum /= (npts-1);
covmat[i][j] = csum;
covmat[j][i] = csum;
}
}
TVectorD eigenvalues(3);
TMatrixD eigenvectors = covmat.EigenVectors(eigenvalues);
double dirv[3] = {0,0,0};
for (size_t i=0; i<3; ++i)
{
dirv[i]=eigenvectors[i][0];
}
dir.SetXYZ(dirv[0],dirv[1],dirv[2]);
// cout<<"Ave Space Point Position P =(\t "<<pos[0]<<",\t"<<pos[1]<<",\t"<<pos[2]<<"\t)"<<endl;
// $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ PCA END ################################################
// $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ Track Length Estimation from Space Point $$$$$
double dm = dir.Mag();
// if (dm == 0) continue;
dir *= (1.0/dm);
tmx=(lineXM - pos[0])/(dir[0]); tmy=(lineYM- pos[1])/(dir[1]); tmz=(lineZM- pos[2])/(dir[2]);
tpx=(lineXP - pos[0])/(dir[0]); tpy=(lineYP- pos[1])/(dir[1]); tpz=(lineZP- pos[2])/(dir[2]);
RecTrackExitXposmx = lineXM; RecTrackExitYposmy = lineYM; RecTrackExitZposmz = lineZM;
RecTrackExitXpospx = lineXP; RecTrackExitYpospy = lineYP; RecTrackExitZpospz = lineZP;
double RecTrackExitYposmx=pos[1]+dir[1]*tmx; double RecTrackExitXposmy=pos[0]+dir[0]*tmy; double RecTrackExitXposmz=pos[0]+dir[0]*tmz;
double RecTrackExitZposmx=pos[2]+dir[2]*tmx; double RecTrackExitZposmy=pos[2]+dir[2]*tmy; double RecTrackExitYposmz=pos[1]+dir[1]*tmz;
double RecTrackExitYpospx=pos[1]+dir[1]*tpx; double RecTrackExitXpospy=pos[0]+dir[0]*tpy; double RecTrackExitXpospz=pos[0]+dir[0]*tpz;
double RecTrackExitZpospx=pos[2]+dir[2]*tpx; double RecTrackExitZpospy=pos[2]+dir[2]*tpy; double RecTrackExitYpospz=pos[1]+dir[1]*tpz;
if((RecTrackExitYposmx >= -600. && RecTrackExitYposmx <= 600.) && (RecTrackExitZposmx >= 0. && RecTrackExitZposmx <= 6500.) )
{ fRTrackExitXpos.push_back( RecTrackExitXposmx ); fRTrackExitYpos.push_back( RecTrackExitYposmx );fRTrackExitZpos.push_back(RecTrackExitZposmx);
}
if((RecTrackExitXposmy >= -720. && RecTrackExitXposmy <= 720.) && (RecTrackExitZposmy >= 0. && RecTrackExitZposmy <= 6500.))
{fRTrackExitXpos.push_back( RecTrackExitXposmy);fRTrackExitYpos.push_back(RecTrackExitYposmy);fRTrackExitZpos.push_back(RecTrackExitZposmy);
}
if((RecTrackExitXposmz >= -720. && RecTrackExitXposmz <= 720.) && (RecTrackExitYposmz >= -600. && RecTrackExitYposmz <= 600.))
{fRTrackExitXpos.push_back(RecTrackExitXposmz);fRTrackExitYpos.push_back(RecTrackExitYposmz);fRTrackExitZpos.push_back(RecTrackExitZposmz);
}
if((RecTrackExitYpospx >= -600. && RecTrackExitYpospx <= 600.) && (RecTrackExitZpospx >= 0. && RecTrackExitZpospx <= 6500.))
{fRTrackExitXpos.push_back( RecTrackExitXpospx );fRTrackExitYpos.push_back( RecTrackExitYpospx );fRTrackExitZpos.push_back( RecTrackExitZpospx );
}
if((RecTrackExitXpospy >= -720. && RecTrackExitXpospy <= 720.) && (RecTrackExitZpospy >= 0. && RecTrackExitZpospy <= 6500.))
{fRTrackExitXpos.push_back( RecTrackExitXpospy );fRTrackExitYpos.push_back(RecTrackExitYpospy);fRTrackExitZpos.push_back(RecTrackExitZpospy);
}
if( (RecTrackExitXpospz >= -720. && RecTrackExitXpospz <= 720.) && (RecTrackExitYpospz >= -600. && RecTrackExitYpospz <= 600.) )
{ fRTrackExitXpos.push_back(RecTrackExitXpospz);fRTrackExitYpos.push_back( RecTrackExitYpospz );fRTrackExitZpos.push_back(RecTrackExitZpospz);
}
for(size_t i=0; i<2; ++i)
{ std::cout<<"End point of the Tracks P = (\t "<<fRTrackExitXpos[i]<< ",\t"<<fRTrackExitYpos[i]<<",\t"<<fRTrackExitZpos[i]<<")\t"<<std::endl;
}
Extpl_track_length1 =sqrt(pow(fRTrackExitXpos[0]-fRTrackExitXpos[1], 2)+pow(fRTrackExitYpos[0]-fRTrackExitYpos[1], 2)+pow(fRTrackExitZpos[0]-fRTrackExitZpos[1], 2) * 1.0);
fExtpl_track_length.push_back(Extpl_track_length1);
std::cout<<"Extrapolated Track Length from Space-Point is = \t "<< Extpl_track_length1<< "\t cm "<<std::endl;
int const tl(500.); // Track segment size set here ex 500 cm . take R = 250 cm
TVector3 V = dir.Unit();
TVector3 P0,P1,P2,PEnd, p1, p2, p;
P0.SetXYZ(fRTrackExitXpos[0],fRTrackExitYpos[0],fRTrackExitZpos[0]);
PEnd.SetXYZ(fRTrackExitXpos[1],fRTrackExitYpos[1],fRTrackExitZpos[1]); // any end point can be used either
P1 = P0 + tl*V;
P2 = P0 - tl*V;
double d01 = (PEnd - P1).Mag();
double d02 = (PEnd - P2).Mag();
double tl_trace = (P1 - P0).Mag();double dqdl=0.0;
double d0 = tl_trace;
int n= 0;
if(d01 < d02 )
{
while( tl_trace < Extpl_track_length1)
{ SP_TracePoint_gr->SetPoint(n,P0.X(),P0.Y(),P0.Z());
cout<< "Point at the line (Forward Dir ) is : (\t"<<P0(0)<<",\t"<<P0(1)<<",\t"<<P0(2)<<"\t"<<"distance = \t"<<d0<<"\n";
p1.SetXYZ(P0.X(),P0.Z(),0);
p2.SetXYZ((P0+tl*V).X(),(P0+tl*V).Z(),0);
for( auto const& hit : (*hitHandle) )
{
if ( fGeometryService->SignalType( hit.Channel() ) != geo::kCollection) continue;
p.SetXYZ(detProp.ConvertTicksToX(hit.PeakTime(), hit.WireID().Plane, hit.WireID().TPC, hit.WireID().Cryostat ), geom->Wire(hit.WireID()).GetCenter().Z(), 0 );
if(((p-p1).Dot(p2-p1) > 0.0) && ((p-p2).Dot(p1-p2) > 0.0)) { dqdl=dqdl+ hit.Integral();} // here * is Dot product
// if(p1.Dot(p2)){cout<<"Dot product syntex "<<"\n";}
}
// cout<< "Totale Charge from Track Segment : "<<TMath::Log(dqdl) <<"\n";
// break;
if(dqdl!=0) { fHitdQ_track_segment.push_back(dqdl/tl);}
P0 = P0 + tl*V;
dqdl=0.0;
n++;
tl_trace = tl_trace + 500;
} // while loop
} // if (d01 or d02)
else // (d01 not less than d02)
{
while( tl_trace < Extpl_track_length1)
{ SP_TracePoint_gr->SetPoint(n,P0.X(),P0.Y(),P0.Z());
cout<< "Point at the line (Reverse dir ) is : (\t"<<P0(0)<<",\t"<<P0(1)<<",\t"<<P0(2)<<")"<<"distance = \t"<<d0<<"\n";
p1.SetXYZ(P0.X(),P0.Z(),0);
p2.SetXYZ((P0-tl*V).X(),(P0-tl*V).Z(),0);
for( auto const& hit : (*hitHandle) )
{
if (fGeometryService->SignalType( hit.Channel() ) != geo::kCollection) continue;
p.SetXYZ(detProp.ConvertTicksToX(hit.PeakTime(), hit.WireID().Plane, hit.WireID().TPC, hit.WireID().Cryostat ), geom->Wire(hit.WireID()).GetCenter().Z(),0 );
if(((p-p1).Dot(p2-p1) > 0.0) && ((p-p2).Dot(p1-p2) > 0.0)) { dqdl=dqdl+ hit.Integral();}
}
// cout<< "Totale Charge from Track Segment : "<<TMath::Log(dqdl) <<"\n";
// dqdl=dqdl+HitCharge;
// break;
if(dqdl!=0) { fHitdQ_track_segment.push_back(dqdl/tl);}
P0 = P0 - tl*V;
dqdl=0.0; n++; tl_trace = tl_trace + 500;
} // while loop
} // else // // End estimation dQ/dl here ...
// Estimating Direction
/* int spd=0, End1_Vote(0),End2_Vote(0);
bool sp_flag = true;
double dq=0.0, SPLPd_HitCharge = 0.0,t = 1.0;
TVector3 last_sp, P_PCA, normal, Pxyz_l;
for (size_t i=0; i<npts; ++i)
{
TVector3 pt(fRec_SpacePoint_X[i],fRec_SpacePoint_Y[i],fRec_SpacePoint_Z[i]);
double dist = ((pt - pos).Cross(dir)).Mag(); // no uncertainties for now -- set all to 1
art::Ptr<recob::SpacePoint> recSPLPd(recobspacepoints,i);
std::vector<art::Ptr<recob::Hit>> spacePointHits = SPcharge.GetHits(recSPLPd, event, "pandora");
if( dist > 5.00) // looking Space points 5 cm away from line
{
SPLPd_X.push_back(pt.X());SPLPd_Y.push_back(pt.Y());SPLPd_Z.push_back(pt.Z());//}
SPLPd_gr->SetPoint(spd,pt.X(),pt.Y(),pt.Z());
if(!sp_flag)
{
P_PCA = pt + t*(pt - last_sp); // L1 & L2 made by Eigen Vector Space point direction vector (pt - last_sp) //
// double Skew_d = ((pt - pos).Dot(dir.Cross(pt - last_sp)))/(dir.Cross(pt - last_sp)).Mag();
TVector3 normal = (pt - last_sp).Cross((pt - last_sp).Cross(dir));// https://en.wikipedia.org/wiki/Skew_lines
TVector3 L2_P1 = pos + ((pt - pos).Dot(normal)/dir.Dot(normal))*dir; //point on the muon fit path line that is closest to this line
// Started estimation of point on muon fit line from point
// Equation of plane => N.r = N.p (N is normal P is point )
double T = (dir.Dot(last_sp) - dir.Dot(pos))/(dir.Dot(dir));
Pxyz_l.SetXYZ(dir.X()*T+pos.X(), dir.Y()*T+pos.Y(), dir.Z()*T+pos.Z()); // Point at the muon track from one of the
if((pt - last_sp).Mag() > 0.5 && (pt - last_sp).Mag() < 2.0 )
{//cout << "Pairs of Spacepoint found here = \t"<<Skew_d<<L2_P1.X()<<"\n";
// cout << "Plane Normal and Scaler = \t"<<Pxyz_l.X()<<"\t"<<"\n";
if ((Pxyz_l - P0).Mag() > (L2_P1 - P0).Mag()) {End1_Vote++;}
if ((Pxyz_l - P0).Mag() < (L2_P1 - P0).Mag()) {End2_Vote++;}
}
}
else
{
sp_flag = false;
}
last_sp = pt;
for ( auto const& SPLPdhits : (spacePointHits) )
{
SPLPd_HitCharge = SPLPdhits->Integral();
dq=dq+SPLPd_HitCharge;
}
SPLPd_HitdQ.push_back(dq);
dq= 0.0;
// chi2ndf += dist*dist;
spd++;
} // if (dist )
}
if(End1_Vote > End2_Vote)
{cout<< "Particle is End1 Upstream \t (\t"<<P0.Z()<<"\t)\n";
muonDir.push_back(1);
}
else
{cout<<"Particle is End2 Upstream \t (\t"<<P0.Z()<<"\t)\n";
muonDir.push_back(-1);
}
*/
//Direction End block
// if(Extpl_track_length1 >= 1200 && trackLength <= 500 )
/* // {
TCanvas *tc1 = new TCanvas("tc1","Rec Space-Point",0,20,800,800);
TH2D *h = new TH2D("h","Space",100,-720,720,100,-600,600);
// TH2D *h1 = new TH2D("h1","Space",100,-720,720,100,-600,600);
gStyle->SetOptStat(0);
h->GetZaxis()->SetLimits(0.0,6500);
SP_gr->SetHistogram(h);
SP_gr->Draw("p0");
SP_gr->SetTitle("DUNE-FD ; X (cm); Y (cm); Z (cm)");
SP_gr->GetXaxis()->CenterTitle();SP_gr->GetYaxis()->CenterTitle();SP_gr->GetZaxis()->CenterTitle();
SP_gr->GetXaxis()->SetTitleOffset(1.5);SP_gr->GetYaxis()->SetTitleOffset(1.5);SP_gr->GetZaxis()->SetTitleOffset(1.3);
// SP_gr->SetMinimum(0.0);SP_gr->SetMaximum(6500);
SP_gr->GetXaxis()->SetTitleSize(0.04);SP_gr->GetYaxis()->SetTitleSize(0.04);SP_gr->GetZaxis()->SetTitleSize(0.04);
SP_gr->GetXaxis()->SetLabelSize(0.025); SP_gr->GetYaxis()->SetLabelSize(0.025); SP_gr->GetZaxis()->SetLabelSize(0.025);
Traj_gr->SetMarkerColor(kGreen);
Traj_gr->SetMarkerStyle(10);
Traj_gr->SetMarkerSize(0.5);
Traj_gr->Draw("p0 same");
SP_AvePos_gr->SetPoint(0,pos[0],pos[1],pos[2]);
SP_AvePos_gr->SetPoint(1,fRTrackExitXpos[0],fRTrackExitYpos[0],fRTrackExitZpos[0]);
SP_AvePos_gr->SetPoint(2,fRTrackExitXpos[1],fRTrackExitYpos[1],fRTrackExitZpos[1]);
// SP_AvePos_gr->SetPoint(3,P1(0),P1(1),P1(2));
// SP_AvePos_gr->SetPoint(4,P2(0),P2(1),P2(2));
SP_AvePos_gr->SetMarkerColor(kRed);
SP_AvePos_gr->SetMarkerStyle(20);
SP_AvePos_gr->SetMarkerSize(1.5);
SP_AvePos_gr->Draw("pLINE same");
SP_AvePos_gr->SetLineColor(kRed);
// h1->GetZaxis()->SetRangeUser(0.0, 6500);
SP_TracePoint_gr->SetMarkerColor(kBlue);
SP_TracePoint_gr->SetMarkerStyle(20);
SP_TracePoint_gr->SetMarkerSize(1.5);
SP_TracePoint_gr->Draw("p same");
// h1->GetZaxis()->SetRangeUser(0.0,6500);
SP_TracePoint_gr->SetMinimum(0.0);
SP_TracePoint_gr->SetMaximum(6500);
SPLPd_gr->SetMarkerColor(kYellow);
SPLPd_gr->SetMarkerStyle(20);
SPLPd_gr->SetMarkerSize(1.5);
SPLPd_gr->Draw("p same");
SPLPd_gr->SetMinimum(0.0);
SPLPd_gr->SetMaximum(6500);
TLegend *leg = new TLegend(0.15,0.9,0.35,0.7);
// leg->SetHeader("Track Length");
leg->AddEntry(SP_AvePos_gr,"Reco(Line)","l");
leg->AddEntry(SP_TracePoint_gr,"Sphere Centers","p");
leg->AddEntry(Traj_gr,"Traj","p");
leg->AddEntry(SP_gr,"Space Points","p0");
leg->AddEntry(SPLPd_gr,"Space Points at d = 5 cm from line","p0");
leg->Draw();
tc1->Print("SpacePoint_location.root");
tc1->SaveAs("/dune/app/users/jdsingh/DUNE_SP2020Work/DUNEWork/MUSUNWork/myplot/SpacePointMC.pdf");
// }// if(TGraph2D)
// else continue;
// }//stopping else */
// *********************************8 Charge and Energy Deposite Analysis **********************************//
for( auto const& channel : (*simChannelHandle) )
{
float energyDepositA = 0; //jd
wireNumber = (int)channel.Channel();//jd ///< Set wire number
if ( fGeometryService->SignalType( channel.Channel() ) != geo::kCollection )
continue;
auto const& timeSlices = channel.TDCIDEMap();
for ( auto const& timeSlice : timeSlices )
{
auto const& chargeDeposits = timeSlice.second; //jd
for (auto const& chargeDeposit : chargeDeposits) //jd
{
energyDepositA += chargeDeposit.numElectrons * fElectronsToGeV; // jd
} // End chargeDeposit loop
} // For each time slice
fSimWireEnergy.push_back(energyDepositA); //jd // old filling place
fSimWireNumber.push_back(wireNumber); //jd // old filling place
// fSimulationNtuple->Fill();
} // For each SimChannel
double hitCharge = 0; //jd
// double LifeTimeCurrection = 0;
for ( auto const& hit : (*hitHandle) )
{
// fHitIntegralHist->Fill(hit.Integral());
if ( fGeometryService->SignalType( hit.Channel() ) != geo::kCollection) continue;
MF_LOG_DEBUG("EnergyAna") << "Hit in collection plane"<<"JD \t "<<hitCharge<< std::endl;
hitCharge += (hit.Integral());
MF_LOG_DEBUG("EnergyAna")
<< std::endl;
fRecoChargeInt.push_back(hit.Integral()); // We should work with this quantity ,
fRecoChargeTrue.push_back(hit.PeakAmplitude()); // this have noise .....
fRecoWireNumber.push_back(hit.Channel());
fRecoPeakTime.push_back(hit.PeakTime());
MF_LOG_DEBUG("EnergyAna")
<< "Hit index = " << hit.LocalIndex()
<< " channel number = " << hit.Channel()
<< " start TDC tick = " << hit.StartTick()
<< " end TDC tick = " << hit.EndTick()
<< " peak TDC tick = " << hit.PeakTime()
<< " sigma peak time = " << hit.SigmaPeakTime()
// << " adjusted start TDC tick = " << fTimeService->TPCTick2TDC(hit.StartTick())
// << " adjusted end TDC tick = " << fTimeService->TPCTick2TDC(hit.EndTick())
// << " adjusted peak TDC tick = " << fTimeService->TPCTick2TDC(hit.PeakTime())
<< " time = " << time
<< std::endl;
} //// for each Hit
// cout<< "Total hit Charge from Raw Hit = "<< TMath::Log(hitCharge) <<"\n";
fRecoHitCharge.push_back(hitCharge); // old
// *************************************** Charge and Energy Deposite Analysis **************************//
fSimulationTrackTree->Fill();
} // if(SpacePoint)
} // EnergyAna::analyze()
DEFINE_ART_MODULE(trackAna)
} // namespace example
} // namespace lar