diff --git a/doc/branches.md b/doc/branches.md index f496126..9a03218 100644 --- a/doc/branches.md +++ b/doc/branches.md @@ -62,6 +62,24 @@ Within each Kalman fit element, there is a vector describing the track segment p | trksegpars_ch | Vector-of-vector branch | CentralHelix track parameters at each trkseg surface (used for field-on cosmic tracks)| [see CentralHelixInfo.hh](../inc/CentralHelixInfo.hh) | trksegpars_kl | Vector-of-vector branch | KinematicLine track parameters for each trkseg surface (used for field-off cosmics)| [see KinematicLineInfo.hh](../inc/KinematicLineInfo.hh) | trksegsmc | Vector-of-vector branch | MC-truth information of the SurfaceSteps taken by a particle through passive elements, or virtual detectors| [see SurfaceStepInfo.hh](../inc/SurfaceStepInfo.hh) +## Track-CRV association Branches + +These branches hold the association of each track with CRV coincidence clusters (Offline ```TrkCrvMatch```, and ```TrkCrvMatchMC``` for MC). +They are filled for track branches configured with ```trkCrvMatchTags``` (and ```trkCrvMatchMCTags```), and are named after the track branch, e.g. ```trkcrv``` for ```trk```. + +Reco files made with the association in Production's reco paths already hold these collections: there, set the tags to the reco labels (```TrkCrvMatchLine```, ```TrkCrvMatchCHmu```, ```TrkCrvMatchDe```, ... and their ```...MC```; ```TrkCrvMatchRecoTagsAll``` and ```TrkCrvMatchRecoMCTagsAll``` in ```fcl/prolog.fcl``` for the LoopHelix fits) and run no producer. Older files need the ntuple job to make them, with the ```TrkCrvMatchProducers``` and paths of ```fcl/prolog.fcl```, labelled ```TrkCrvMatchNtuple``` (```TrkCrvMatchTagsAll```), as ```from_mcs-extracted.fcl``` does. The stored records are the better ones: their layer probe saw every CRV pulse (```probe``` 3), and their truth has the CRV deposits, which reco output drops. + +```crv``` has one element per track. The other branches hold, per track, a vector of CRV sector crossings (```crvxings```, with the per-layer probe) or of associated clusters (```crvcands```). +```crvcands.crvcoinc``` is the index of the cluster in ```crvcoincs```; ```crvcandsmc``` and ```crvxingsmc``` are parallel to ```crvcands``` and ```crvxings```. See ```utils/trkcrv_example.py```. + +| branch | structure | explanation | leaf information | +|--------|-----------|-------------|------------------| +| trkcrv | Vector branch | track-CRV association summary of one track, from Offline TrkCrvMatch| [see TrkCrvInfo.hh](../inc/TrkCrvInfo.hh) +| trkcrvxings | Vector-of-vector branch | one CRV sector crossing of a track's extrapolation, with the layer probe of that sector| [see TrkCrvXingInfo.hh](../inc/TrkCrvXingInfo.hh) +| trkcrvcands | Vector-of-vector branch | one CRV coincidence cluster associated with a track (candidates ordered geometric by chi2, then time-only)| [see TrkCrvCandInfo.hh](../inc/TrkCrvCandInfo.hh) +| trkcrvcandsmc | Vector-of-vector branch | truth of one track-CRV candidate, parallel to crvcands| [see TrkCrvCandInfoMC.hh](../inc/TrkCrvCandInfoMC.hh) +| trkcrvxingsmc | Vector-of-vector branch | truth of one reco CRV crossing, parallel to crvxings| [see TrkCrvXingInfoMC.hh](../inc/TrkCrvXingInfoMC.hh) +| trkcrvtruexingsmc | Vector-of-vector branch | one true CRV sector crossing by the track's particle or one of its ancestors| [see TrkCrvTrueXingInfoMC.hh](../inc/TrkCrvTrueXingInfoMC.hh) ## Straw Branches These branches contain a vector in which each element lists the properties of a straw hits in the tracker. diff --git a/fcl/from_mcs-extracted.fcl b/fcl/from_mcs-extracted.fcl index 81d1a72..d5f3701 100644 --- a/fcl/from_mcs-extracted.fcl +++ b/fcl/from_mcs-extracted.fcl @@ -8,3 +8,8 @@ physics.analyzers.EventNtuple.subruns.genEventCount.include : true physics.analyzers.EventNtuple.subruns.cosmicLivetime.include : true services.GeometryService.inputFile: "Production/JobConfig/cosmic/geom_cosmic_extracted.txt" + +# Track-CRV association of the line fits, with truth: crv, crvxings, crvcands and their mc branches +physics.EventNtuplePath : [ @sequence::EventNtuple.PathExt, @sequence::TrkCrvMatchNoFieldMCPath ] +physics.analyzers.EventNtuple.trk.fits[0].trkCrvMatchTags : [ "TrkCrvMatchLineNtuple" ] +physics.analyzers.EventNtuple.trk.fits[0].trkCrvMatchMCTags : [ "TrkCrvMatchLineNtupleMC" ] diff --git a/fcl/from_mcs-mockdata_trkcrv.fcl b/fcl/from_mcs-mockdata_trkcrv.fcl new file mode 100644 index 0000000..d737301 --- /dev/null +++ b/fcl/from_mcs-mockdata_trkcrv.fcl @@ -0,0 +1,7 @@ +# from_mcs-mockdata.fcl plus the track-CRV association of the "trk" branch (MergeKKAll: KKDe, KKUe, KKDmu, KKUmu). +# LoopHelix fits do not extrapolate to the CRV, so the association is time only (trkcrvcands.time, dtref, dtreftof). +#include "EventNtuple/fcl/from_mcs-mockdata.fcl" + +physics.EventNtuplePath : [ @sequence::EventNtuple.PathOnline, @sequence::TrkCrvMatchAllMCPath ] +physics.analyzers.EventNtuple.trk.fits[0].trkCrvMatchTags : @local::TrkCrvMatchTagsAll +physics.analyzers.EventNtuple.trk.fits[0].trkCrvMatchMCTags : @local::TrkCrvMatchMCTagsAll diff --git a/fcl/from_rec-combined.fcl b/fcl/from_rec-combined.fcl index 43f7813..7be4fdf 100644 --- a/fcl/from_rec-combined.fcl +++ b/fcl/from_rec-combined.fcl @@ -1,6 +1,6 @@ #include "EventNtuple/fcl/from_mcs-mockdata_noMC.fcl" -physics.EventNtuplePath : [ @sequence::EventNtuple.PathExt ] # path for extracted position cosmics +physics.EventNtuplePath : [ @sequence::EventNtuple.PathExt, @sequence::TrkCrvMatchNoFieldPath ] # path for extracted position cosmics, with the track-CRV association physics.analyzers.EventNtuple.FillTriggerInfo: true # trigger results of the event builder process (e.g. to identify calo laser events) physics.analyzers.EventNtuple.TriggerProcessName : "EvB" @@ -40,3 +40,9 @@ physics.analyzers.EventNtuple.calo.fillDigis : false # MSD info physics.analyzers.EventNtuple.msd.fill : true physics.analyzers.EventNtuple.msd.hitsTag : "MSDHitMaker" + +# Track-CRV association of the line fits (crv, crvxings, crvcands); pass 1 keeps every CRV pulse, so the layer probe is complete +physics.producers.TrkCrvMatchLineNtuple.CrvCoincidenceClusterCollection : "CrvCoincidenceClusterFinder" +physics.producers.TrkCrvMatchLineNtuple.CrvRecoPulseCollection : "CrvRecoPulses" +physics.producers.TrkCrvMatchLineNtuple.ProbeAllPulses : true +physics.analyzers.EventNtuple.trk.fits[0].trkCrvMatchTags : [ "TrkCrvMatchLineNtuple" ] diff --git a/fcl/prolog.fcl b/fcl/prolog.fcl index d262fc0..a28966a 100644 --- a/fcl/prolog.fcl +++ b/fcl/prolog.fcl @@ -2,6 +2,7 @@ #include "Offline/Compression/fcl/prolog.fcl" #include "Offline/CommonMC/fcl/prolog.fcl" #include "Offline/fcl/TrkCaloDt.fcl" +#include "Offline/CRVResponse/fcl/prolog.fcl" #include "EventNtuple/fcl/prolog_mc_reweighters.fcl" @@ -198,6 +199,44 @@ MergeKKProducers : { } MergeKKProducersPath : [ MergeKKAll ] +################################# +# Track-CRV association (Offline TrkCrvMatcher and TrkCrvMatchMCMaker), run on existing reco in the ntuple job. +# One matcher per KalSeedCollection; a fit branch lists the matchers behind its input in trkCrvMatchTags. +# Reco output keeps only the clustered CRV pulses (SelectReco), so there the layer probe sees no unclustered pulses. +# DtRefCenter per fit: the values of Production JobConfig/reco/prolog.fcl (KKLine uses the Offline default). +# Labels end in Ntuple so they never shadow the reco products (TrkCrvMatchLine, ...): files with those set the tags alone. +################################# +TrkCrvMatchNtuple : { @table::TrkCrvMatcher CrvRecoPulseCollection : "SelectReco" ProbeAllPulses : false } +TrkCrvMatchMCNtuple : { @table::TrkCrvMatchMC RequireCrvSteps : false } # reco output drops the digi-stage CrvSteps: no deposits +TrkCrvMatchLH : { @table::TrkCrvMatchNtuple DoGeometric : false LayerProbe : false } # LoopHelix fits do not reach the CRV: time only +TrkCrvMatchProducers : { + TrkCrvMatchLineNtuple : { @table::TrkCrvMatchNtuple KalSeedCollection : "KKLine" } + # KKCHmu runs on the Run1 geometries, whose T1 and T2 are both CRV sector type 1: SigmaV of Production JobConfig/reco/prolog.fcl + TrkCrvMatchCHmuNtuple : { @table::TrkCrvMatchNtuple KalSeedCollection : "KKCHmu" DtRefCenter : 27 SigmaV : [ 13 ] } + TrkCrvMatchDeNtuple : { @table::TrkCrvMatchLH KalSeedCollection : "KKDe" DtRefCenter : 32 } + TrkCrvMatchUeNtuple : { @table::TrkCrvMatchLH KalSeedCollection : "KKUe" DtRefCenter : 28 } + TrkCrvMatchDmuNtuple : { @table::TrkCrvMatchLH KalSeedCollection : "KKDmu" DtRefCenter : 30 } + TrkCrvMatchUmuNtuple : { @table::TrkCrvMatchLH KalSeedCollection : "KKUmu" DtRefCenter : 26 } + TrkCrvMatchLineNtupleMC : { @table::TrkCrvMatchMCNtuple TrkCrvMatchCollection : "TrkCrvMatchLineNtuple" } + TrkCrvMatchCHmuNtupleMC : { @table::TrkCrvMatchMCNtuple TrkCrvMatchCollection : "TrkCrvMatchCHmuNtuple" } + TrkCrvMatchDeNtupleMC : { @table::TrkCrvMatchMCNtuple TrkCrvMatchCollection : "TrkCrvMatchDeNtuple" } + TrkCrvMatchUeNtupleMC : { @table::TrkCrvMatchMCNtuple TrkCrvMatchCollection : "TrkCrvMatchUeNtuple" } + TrkCrvMatchDmuNtupleMC : { @table::TrkCrvMatchMCNtuple TrkCrvMatchCollection : "TrkCrvMatchDmuNtuple" } + TrkCrvMatchUmuNtupleMC : { @table::TrkCrvMatchMCNtuple TrkCrvMatchCollection : "TrkCrvMatchUmuNtuple" } +} +TrkCrvMatchNoFieldPath : [ TrkCrvMatchLineNtuple ] +TrkCrvMatchNoFieldMCPath : [ TrkCrvMatchLineNtuple, TrkCrvMatchLineNtupleMC ] +TrkCrvMatchOffSpillPath : [ TrkCrvMatchCHmuNtuple ] +TrkCrvMatchOffSpillMCPath : [ TrkCrvMatchCHmuNtuple, TrkCrvMatchCHmuNtupleMC ] +TrkCrvMatchAllPath : [ TrkCrvMatchDeNtuple, TrkCrvMatchUeNtuple, TrkCrvMatchDmuNtuple, TrkCrvMatchUmuNtuple ] +TrkCrvMatchAllMCPath : [ @sequence::TrkCrvMatchAllPath, TrkCrvMatchDeNtupleMC, TrkCrvMatchUeNtupleMC, TrkCrvMatchDmuNtupleMC, TrkCrvMatchUmuNtupleMC ] +# trkCrvMatchTags / trkCrvMatchMCTags for the fit branches whose input is made from these collections +TrkCrvMatchTagsAll : [ "TrkCrvMatchDeNtuple", "TrkCrvMatchUeNtuple", "TrkCrvMatchDmuNtuple", "TrkCrvMatchUmuNtuple" ] +TrkCrvMatchMCTagsAll : [ "TrkCrvMatchDeNtupleMC", "TrkCrvMatchUeNtupleMC", "TrkCrvMatchDmuNtupleMC", "TrkCrvMatchUmuNtupleMC" ] +# the same for files whose reco ran the association (Production JobConfig/reco): no producers needed +TrkCrvMatchRecoTagsAll : [ "TrkCrvMatchDe", "TrkCrvMatchUe", "TrkCrvMatchDmu", "TrkCrvMatchUmu" ] +TrkCrvMatchRecoMCTagsAll : [ "TrkCrvMatchDeMC", "TrkCrvMatchUeMC", "TrkCrvMatchDmuMC", "TrkCrvMatchUmuMC" ] + # Cluster the fits behind MergeKKAll made from the same hits (any direction or particle hypothesis): fills .id and .rank TrackMatchingAll : { module_type : TrackMatching @@ -510,6 +549,7 @@ EventNtuple : { @table::TrkPIDProducers @table::MergeKKProducers @table::TrkGroupProducers + @table::TrkCrvMatchProducers } analyzers : { diff --git a/helper/ntuplehelper.py b/helper/ntuplehelper.py index 7111fe3..fe2f162 100644 --- a/helper/ntuplehelper.py +++ b/helper/ntuplehelper.py @@ -3,12 +3,13 @@ class nthelper: single_object_branches = ['evtinfo', 'evtinfomc', 'hitcount', 'tcnt', 'crvsummary', 'crvsummarymc', 'lumistream'] - vector_object_branches = ['trk', 'trkmc', 'trkdtdt', 'trkcalohit', 'trkcalohitmc', 'timeclusters', 'lineseeds', 'caloclustersmc', 'calohitsmc', 'calodigismc', 'calomcsim', 'calodigisim', 'caloclusters', 'calohits', 'calorecodigis', 'calodigis', 'crvcoincs', 'crvcoincsmc', 'crvcoincsmcplane', 'crvpulses', 'crvdigis', 'crvpulsesmc', 'msdhits', 'helices', 'trkqual', 'trkpid', 'trkpid_trk', 'mcsteps', 'primary'] - vector_vector_object_branches = ['trksegs', 'trksegpars_lh', 'trksegpars_ch', 'trksegpars_kl', 'trkmcsim', 'trkhits', 'trkhitsmc', 'trkmats', 'trkhitcalibs', 'trkmcsci', 'trkmcssi', 'trksegsmc', 'timeclustershits', 'lineseedshits', 'heliceshits' ] + vector_object_branches = ['trk', 'trkmc', 'trkdtdt', 'trkcalohit', 'trkcalohitmc', 'timeclusters', 'lineseeds', 'caloclustersmc', 'calohitsmc', 'calodigismc', 'calomcsim', 'calodigisim', 'caloclusters', 'calohits', 'calorecodigis', 'calodigis', 'crvcoincs', 'crvcoincsmc', 'crvcoincsmcplane', 'crvpulses', 'crvdigis', 'crvpulsesmc', 'msdhits', 'helices', 'trkqual', 'trkpid', 'trkpid_trk', 'mcsteps', 'primary', 'trkcrv'] + vector_vector_object_branches = ['trksegs', 'trksegpars_lh', 'trksegpars_ch', 'trksegpars_kl', 'trkmcsim', 'trkhits', 'trkhitsmc', 'trkmats', 'trkhitcalibs', 'trkmcsci', 'trkmcssi', 'trksegsmc', 'timeclustershits', 'lineseedshits', 'heliceshits', 'trkcrvxings', 'trkcrvcands', 'trkcrvcandsmc', 'trkcrvxingsmc', 'trkcrvtruexingsmc' ] evt_branches = ['evtinfo','evtinfomc','hitcount','tcnt', 'lumistream', 'msdhits', 'primary'] trk_branches = ['trk', 'trkmc', 'trkcalohit', 'trkcalohitmc', 'trkdtdt', 'trkqual', 'trkpid', 'trkpid_trk'] trksegs_branches = ['trksegs', 'trksegpars_lh', 'trksegpars_ch', 'trksegpars_kl', 'trksegsmc'] + trkcrv_branches = ['trkcrv', 'trkcrvxings', 'trkcrvcands', 'trkcrvcandsmc', 'trkcrvxingsmc', 'trkcrvtruexingsmc'] straw_branches = ['trkhits', 'trkmats', 'trkhitsmc', 'trkhitcalibs'] trk_mc_branches = [ 'trkmcsim' ] general_mc_branches = [ 'mcsteps' ] @@ -83,7 +84,13 @@ class nthelper: "mcsteps" : "MCStepInfo", "crvpulses" : "CrvPulseInfoReco", "crvdigis" : "CrvWaveformInfo", - "crvpulsesmc" : "CrvPulseInfoReco" + "crvpulsesmc" : "CrvPulseInfoReco", + "trkcrv" : "TrkCrvInfo", + "trkcrvxings" : "TrkCrvXingInfo", + "trkcrvcands" : "TrkCrvCandInfo", + "trkcrvcandsmc" : "TrkCrvCandInfoMC", + "trkcrvxingsmc" : "TrkCrvXingInfoMC", + "trkcrvtruexingsmc" : "TrkCrvTrueXingInfoMC" } # Map a configured helix seed branch name (and its hits branch) onto the default helices branches @@ -186,6 +193,28 @@ def list_all_branches(self, export_to_md=False): tokens=explanation.split(":") print("| " + tokens[0] + " | " + tokens[1] + " | " + tokens[2] + "| [see " + struct_file + "](../inc/"+struct_file+")") + if not export_to_md: + print("\nTrack-CRV association Branches") + print("================") + else: + print("## Track-CRV association Branches\n") + print("These branches hold the association of each track with CRV coincidence clusters (Offline ```TrkCrvMatch```, and ```TrkCrvMatchMC``` for MC).") + print("They are filled for track branches configured with ```trkCrvMatchTags``` (and ```trkCrvMatchMCTags```), and are named after the track branch, e.g. ```trkcrv``` for ```trk```.\n") + print("Reco files made with the association in Production's reco paths already hold these collections: there, set the tags to the reco labels (```TrkCrvMatchLine```, ```TrkCrvMatchCHmu```, ```TrkCrvMatchDe```, ... and their ```...MC```; ```TrkCrvMatchRecoTagsAll``` and ```TrkCrvMatchRecoMCTagsAll``` in ```fcl/prolog.fcl``` for the LoopHelix fits) and run no producer. Older files need the ntuple job to make them, with the ```TrkCrvMatchProducers``` and paths of ```fcl/prolog.fcl```, labelled ```TrkCrvMatchNtuple``` (```TrkCrvMatchTagsAll```), as ```from_mcs-extracted.fcl``` does. The stored records are the better ones: their layer probe saw every CRV pulse (```probe``` 3), and their truth has the CRV deposits, which reco output drops.\n") + print("```crv``` has one element per track. The other branches hold, per track, a vector of CRV sector crossings (```crvxings```, with the per-layer probe) or of associated clusters (```crvcands```).") + print("```crvcands.crvcoinc``` is the index of the cluster in ```crvcoincs```; ```crvcandsmc``` and ```crvxingsmc``` are parallel to ```crvcands``` and ```crvxings```. See ```utils/trkcrv_example.py```.\n") + print("| branch | structure | explanation | leaf information |") + print("|--------|-----------|-------------|------------------|") + for branch in self.trkcrv_branches: + explanation = self.get_branch_explanation(branch) + struct = self.branch_struct_dict[branch] + struct_file = struct + ".hh"; + if not export_to_md: + print(explanation) + else: + tokens=explanation.split(":") + print("| " + tokens[0] + " | " + tokens[1] + " | " + tokens[2] + "| [see " + struct_file + "](../inc/"+struct_file+")") + if not export_to_md: print("\nStraw Branches") print("================") diff --git a/inc/InfoMCStructHelper.hh b/inc/InfoMCStructHelper.hh index 151cba5..61ba8b2 100644 --- a/inc/InfoMCStructHelper.hh +++ b/inc/InfoMCStructHelper.hh @@ -24,6 +24,10 @@ #include "EventNtuple/inc/MCStepSummaryInfo.hh" #include "EventNtuple/inc/SurfaceStepInfo.hh" #include "EventNtuple/inc/CrvHitInfoMC.hh" +#include "EventNtuple/inc/TrkCrvCandInfoMC.hh" +#include "EventNtuple/inc/TrkCrvXingInfoMC.hh" +#include "EventNtuple/inc/TrkCrvTrueXingInfoMC.hh" +#include "Offline/MCDataProducts/inc/TrkCrvMatchMC.hh" #include "Offline/RecoDataProducts/inc/KalSeed.hh" #include "Offline/MCDataProducts/inc/KalSeedMC.hh" #include "Offline/MCDataProducts/inc/PrimaryParticle.hh" @@ -67,6 +71,9 @@ namespace mu2e { void updateEvent(const art::Event& event); void fillTrkInfoMC(const KalSeed& kseed, const KalSeedMC& kseedmc, art::Handle surfaceStepsHandle, std::vector& all_trkinfomcs); + // truth of one track's CRV association (null: no record); crvPid is the collection crvcoincs is filled from + void fillTrkCrvInfoMC(const TrkCrvMatchMC* mc, const art::ProductID& crvPid, std::vector>& cands, + std::vector>& xings, std::vector>& trues); void fillTrkInfoMCDigis(const KalSeed& kseed, const KalSeedMC& kseedmc, TrkInfoMC& trkinfomc); void fillHitInfoMC(const KalSeedMC& kseedmc, TrkStrawHitInfoMC& tshinfomc, const TrkStrawHitMC& tshmc); void fillAllSimInfos(const KalSeedMC& kseedmc, const PrimaryParticle& primary, std::vector>& all_siminfos, int n_generations, int n_match); diff --git a/inc/InfoStructHelper.hh b/inc/InfoStructHelper.hh index 8f7e938..66e5c16 100644 --- a/inc/InfoStructHelper.hh +++ b/inc/InfoStructHelper.hh @@ -7,6 +7,7 @@ #include "Offline/RecoDataProducts/inc/StrawHitIndex.hh" #include "Offline/RecoDataProducts/inc/KalSeed.hh" #include "Offline/RecoDataProducts/inc/KalSeedDtDt.hh" +#include "Offline/RecoDataProducts/inc/TrkCrvMatch.hh" #include "Offline/RecoDataProducts/inc/StrawHitFlag.hh" #include "Offline/RecoDataProducts/inc/RecoCount.hh" #include "Offline/RecoDataProducts/inc/HelixSeed.hh" @@ -32,6 +33,9 @@ #include "EventNtuple/inc/CentralHelixInfo.hh" #include "EventNtuple/inc/KinematicLineInfo.hh" #include "EventNtuple/inc/TrkDtDtInfo.hh" +#include "EventNtuple/inc/TrkCrvInfo.hh" +#include "EventNtuple/inc/TrkCrvXingInfo.hh" +#include "EventNtuple/inc/TrkCrvCandInfo.hh" #include "EventNtuple/inc/TrkStrawHitInfo.hh" #include "EventNtuple/inc/TrkStrawHitCalibInfo.hh" #include "EventNtuple/inc/TrkStrawMatInfo.hh" @@ -80,6 +84,9 @@ namespace mu2e { void fillKinematicLineInfo(const KalSeed& kseed, std::vector>& klis); void fillMVAResultInfo(const MVAResult& mva, std::vector& all_mvas); void fillTrkDtDtInfo(const KalSeedDtDt& dtdt,std::vector& trkinfo); + // track-CRV association of one track (null: no record); crvPid is the collection crvcoincs is filled from + void fillTrkCrvInfo(const TrkCrvMatch* match, const art::ProductID& crvPid, std::vector& infos, + std::vector>& xings, std::vector>& cands); void fillHitInfo(const KalSeed& kseed, std::vector>& all_tshinfos, std::vector>& all_tshcinfos, bool saveCalib ); void fillMatInfo(const KalSeed& kseed, std::vector>& tminfos ); void fillTrkCaloHitInfo(const KalSeed& kseed, std::vector& tchinfo ); diff --git a/inc/TrkCrvCandInfo.hh b/inc/TrkCrvCandInfo.hh new file mode 100644 index 0000000..7e11487 --- /dev/null +++ b/inc/TrkCrvCandInfo.hh @@ -0,0 +1,40 @@ +// +// TrkCrvCandInfo: one CRV coincidence cluster associated with a track (candidates ordered geometric by chi2, then time-only) +// +#ifndef TrkCrvCandInfo_HH +#define TrkCrvCandInfo_HH + +namespace mu2e +{ + struct TrkCrvCandInfo { + int crvcoinc = -1; // index into crvcoincs, -1 if the cluster is not in the collection crvcoincs was filled from + int xing = -1; // index into crvxings of the reference crossing, -1 for a time-only candidate + int sector = -1; // dominant CRV sector of the cluster (largest PE sum) + float dtref = 0; // track reference time - cluster average hit time (ns) + float dtreftof = 0; // dtref - straight-line flight time between the reference point and the cluster (ns) + float dtxing = 0; // cluster time - track time at the cluster plane (ns), geometric candidates only + float du = 0; // cluster - track along the bars at the cluster plane (mm), geometric candidates only + float dv = 0; // cluster - track across the bars at the cluster plane (mm), geometric candidates only + float sigu = 0; // track error on du (mm) + float sigv = 0; // track error on dv (mm) + float rhouv = 0; // correlation of the track errors on du and dv + float chi2 = -1; // space + time chi2, -1 for time-only candidates + int ndof = 0; // chi2 degrees of freedom (2 single-ended, 3 two-ended) + int nshare = 0; // tracks of the same collection holding this cluster as a candidate + unsigned flags = 0; // TrkCrvCandidate::Flag bits, decoded in the bools below + bool geom = false; // kept by the geometric test + bool time = false; // kept by the time test + bool best = false; // the track's best candidate (bestgeom, else besttime) + bool bestforcluster = false; // this track is the cluster's best track + bool exclusive = false; // chosen by the one-to-one assignment + bool bestinsector = false; // lowest-chi2 geometric candidate of the track in this sector + bool samesector = false; // the reference crossing is in the cluster's own sector + bool outofbounds = false; // the projected point is outside the cluster's sector rectangle + bool singleended = false; // no along-bar measurement (du not in the chi2) + bool multisector = false; // the cluster spans sectors + bool usedinfit = false; // the cluster is a constraint in this track's fit + + void reset() { *this = TrkCrvCandInfo(); } + }; +} +#endif diff --git a/inc/TrkCrvCandInfoMC.hh b/inc/TrkCrvCandInfoMC.hh new file mode 100644 index 0000000..255266b --- /dev/null +++ b/inc/TrkCrvCandInfoMC.hh @@ -0,0 +1,20 @@ +// +// TrkCrvCandInfoMC: truth of one track-CRV candidate, parallel to crvcands +// +#ifndef TrkCrvCandInfoMC_HH +#define TrkCrvCandInfoMC_HH + +namespace mu2e +{ + struct TrkCrvCandInfoMC { + bool hasmc = false; // the cluster has MC information (false: background or no MC) + int rel = -1; // closest MCRelationship of the cluster's deposit particles to the track's particle: -1 none, 0 same, 1 daughter, 2 mother, 3 sibling, 4 udaughter, 5 umother, 6 usibling + int rem = -1; // generational removal of that relation (0 for same) + float edep_same = 0; // cluster energy from the track's particle (MeV) + float edep_related = 0; // cluster energy from any related particle, the track's particle included (MeV) + float edep_total = 0; // cluster energy with MC information (MeV) + + void reset() { *this = TrkCrvCandInfoMC(); } + }; +} +#endif diff --git a/inc/TrkCrvInfo.hh b/inc/TrkCrvInfo.hh new file mode 100644 index 0000000..192531d --- /dev/null +++ b/inc/TrkCrvInfo.hh @@ -0,0 +1,24 @@ +// +// TrkCrvInfo: track-CRV association summary of one track, from Offline TrkCrvMatch +// +#ifndef TrkCrvInfo_HH +#define TrkCrvInfo_HH + +namespace mu2e +{ + struct TrkCrvInfo { + bool matched = false; // a TrkCrvMatch record exists for this track (false: the other leaves are defaults) + int nxings = 0; // CRV sector crossings of the track's extrapolation (entries of crvxings) + int ncands = 0; // associated CRV coincidence clusters (entries of crvcands) + int ngeom = 0; // candidates kept by the geometric test + int bestgeom = -1; // index into crvcands of the lowest-chi2 geometric candidate, -1 if none + int besttime = -1; // index into crvcands of the time candidate closest to the configured dtref centre, -1 if none + int refsid = -1; // SurfaceId of the surface that defined tref, -1 if the KalSeed t0 was used + float tref = 0; // track reference time used by dtref: by default the track's entry into the tracker (ns) + int probe = 0; // pulses the layer probe saw: 0 not run, 1 none (predicted bars only), 2 clustered pulses only, 3 all pulses + float timeoffset = 0; // CRV - tracker time offset the matcher applied to cluster times (ns) + + void reset() { *this = TrkCrvInfo(); } + }; +} +#endif diff --git a/inc/TrkCrvTrueXingInfoMC.hh b/inc/TrkCrvTrueXingInfoMC.hh new file mode 100644 index 0000000..961710b --- /dev/null +++ b/inc/TrkCrvTrueXingInfoMC.hh @@ -0,0 +1,34 @@ +// +// TrkCrvTrueXingInfoMC: one true CRV sector crossing by the track's particle or one of its ancestors +// +#ifndef TrkCrvTrueXingInfoMC_HH +#define TrkCrvTrueXingInfoMC_HH +#include "EventNtuple/inc/RootVectors.hh" + +namespace mu2e +{ + struct TrkCrvTrueXingInfoMC { + int sid = -1; // SurfaceId of the sector + int sector = -1; // CRV sector (CRSScintillatorShield index) + int rel = -1; // MCRelationship of the crossing particle to the track's particle: 0 same, 2 mother (its parent), 5 umother (further up) + int rem = -1; // generations between them (0 for same), simulation-stage copies not counted + int pdg = 0; // PDG code of the crossing particle + bool geom = false; // the trajectory crosses the sector mid-plane rectangle (gap-inclusive); pos, dir, time, mom are valid + XYZVectorF pos; // mid-plane crossing, detector frame (mm) + XYZVectorF dir; // unit direction of the trajectory at the crossing + float time = 0; // crossing time (ns) + float mom = 0; // momentum at the crossing (MeV/c) + float dedgeu = 0; // distance inside the sector edge along the bars (mm) + float dedgev = 0; // distance inside the sector edge across the bars (mm) + bool hasdeposits = false; // CrvSteps were available, so edep, nlayers and deppos are filled + float edep = 0; // visible energy deposited by the particle in the sector's bars (MeV) + int nlayers = 0; // layers with a deposit from the particle + XYZVectorF deppos; // energy-weighted position of those deposits, detector frame (mm) + int crvcoinc = -1; // index into crvcoincs of the cluster with most energy from the particle in this sector, -1 if none or not in that collection + int cand = -1; // index into crvcands of that cluster, -1 if it is not a candidate + int recoxing = -1; // index into crvxings of the reco crossing of this sector, -1 if not extrapolated there + + void reset() { *this = TrkCrvTrueXingInfoMC(); } + }; +} +#endif diff --git a/inc/TrkCrvXingInfo.hh b/inc/TrkCrvXingInfo.hh new file mode 100644 index 0000000..ae29c84 --- /dev/null +++ b/inc/TrkCrvXingInfo.hh @@ -0,0 +1,43 @@ +// +// TrkCrvXingInfo: one CRV sector crossing of a track's extrapolation, with the layer probe of that sector +// +#ifndef TrkCrvXingInfo_HH +#define TrkCrvXingInfo_HH +#include "Offline/DataProducts/inc/CRVId.hh" +#include "EventNtuple/inc/RootVectors.hh" +#include +#include + +namespace mu2e +{ + struct TrkCrvXingInfo { + int sid = -1; // SurfaceId of the crossed CRV sector + int sector = -1; // CRV sector (CRSScintillatorShield index) + XYZVectorF pos; // crossing position on the sector mid-plane, detector frame (mm) + XYZVectorF dir; // unit track direction at the crossing + float time = 0; // crossing time (ns) + float sigu = 0; // track position error along the bars, error model applied (mm) + float sigv = 0; // track position error across the bars, error model applied (mm) + float rhouv = 0; // correlation of the track position errors along and across the bars + float sigt = 0; // track time error (ns) + float mom = 0; // track momentum at the crossing (MeV/c) + float momerr = 0; // its error (MeV/c) + bool inbounds = false; // crossing inside the sector rectangle + float dedgeu = 0; // distance inside the sector edge along the bars (mm), negative outside + float dedgev = 0; // distance inside the sector edge across the bars (mm), negative outside + float edgesig = 0; // edge distance in units of the track error + int best = -1; // index into crvcands of the best geometric candidate in this sector, -1 if none + int nlayers = 0; // layers probed, 0 if the layer probe did not run + std::array probe_bar = {-1, -1, -1, -1}; // predicted bar index per layer, -1 if the line misses the layer + std::array probe_dbar = {127, 127, 127, 127}; // bar of the selected pulse - predicted bar, 127 if no pulse in the windows + std::array probe_upred = {0, 0, 0, 0}; // predicted position along the bar from its centre (mm) + std::array probe_tpred = {0, 0, 0, 0}; // track time at the layer (ns) + std::array probe_pe = {0, 0, 0, 0}; // PEs of the selected bar's in-window pulses + std::array probe_dt = {0, 0, 0, 0}; // pulse time - predicted pulse time (ns) + std::array probe_incluster = {false, false, false, false}; // the selected pulse belongs to a coincidence cluster + std::array probe_utdiv = {NAN, NAN, NAN, NAN}; // position along the bar from the two-end time difference (mm), NaN if one-ended + + void reset() { *this = TrkCrvXingInfo(); } + }; +} +#endif diff --git a/inc/TrkCrvXingInfoMC.hh b/inc/TrkCrvXingInfoMC.hh new file mode 100644 index 0000000..c9d0c4f --- /dev/null +++ b/inc/TrkCrvXingInfoMC.hh @@ -0,0 +1,16 @@ +// +// TrkCrvXingInfoMC: truth of one reco CRV crossing, parallel to crvxings +// +#ifndef TrkCrvXingInfoMC_HH +#define TrkCrvXingInfoMC_HH + +namespace mu2e +{ + struct TrkCrvXingInfoMC { + int truexing = -1; // index into crvtruexingsmc of the true crossing of the same sector, -1 if none (a fake crossing) + int nbrxing = -1; // for a fake: index into crvtruexingsmc of the particle's crossing of a coplanar neighbour, -1 if none + + void reset() { *this = TrkCrvXingInfoMC(); } + }; +} +#endif diff --git a/src/EventNtupleMaker_module.cc b/src/EventNtupleMaker_module.cc index 009fa42..bd0f502 100644 --- a/src/EventNtupleMaker_module.cc +++ b/src/EventNtupleMaker_module.cc @@ -18,6 +18,8 @@ #include "Offline/RecoDataProducts/inc/KalSeed.hh" #include "Offline/RecoDataProducts/inc/KalSeedAssns.hh" #include "Offline/RecoDataProducts/inc/KalSeedDtDt.hh" +#include "Offline/RecoDataProducts/inc/TrkCrvMatch.hh" +#include "Offline/MCDataProducts/inc/TrkCrvMatchMC.hh" #include "Offline/RecoDataProducts/inc/CaloCluster.hh" #include "Offline/RecoDataProducts/inc/CaloHit.hh" #include "Offline/RecoDataProducts/inc/CaloRecoDigi.hh" @@ -157,6 +159,8 @@ namespace mu2e { fhicl::Atom input{Name("input"), Comment("KalSeedCollection input tag")}; fhicl::Atom branchname{Name("branchname"), Comment("Name of output branch")}; fhicl::Atom trkDtDtTag{Name("trkDtDtTag"), Comment("Input tag for KalSeedDtDtCollection")}; + fhicl::Sequence trkCrvMatchTags{Name("trkCrvMatchTags"), Comment("TrkCrvMatchCollections covering the KalSeeds behind input (one per KalSeedCollection); empty: no crv* branches"), std::vector{}}; + fhicl::Sequence trkCrvMatchMCTags{Name("trkCrvMatchMCTags"), Comment("TrkCrvMatchMCCollections, one per entry of trkCrvMatchTags in the same order; empty: no crv*mc branches"), std::vector{}}; fhicl::Atom trkGroupTag{Name("trkGroupTag"), Comment("Input tag for KalSeedClusterCollection (from TrackMatching) used to fill the id and rank leaves; empty to disable"), ""}; fhicl::Atom fill{Name("fill"), Comment("Set false to skip this branch entirely (no collection reads, no output branches)")}; fhicl::Sequence mvaTags{Name("mvaTags"), Comment("Input tags of the MVAResultCollections (one result per track, e.g. TrkQual or TrkPID) to store for this fit"), std::vector{}}; @@ -189,6 +193,7 @@ namespace mu2e { Comment("Global enable for hit-level branches; per-branch options.fillHits also required")}; fhicl::Atom fillHitCalibs{Name("fillHitCalibs"), Comment("Fill hit calibration branches")}; fhicl::Atom fillTrkDtDt{Name("fillTrkDtDt"), Comment("Fill TrkDtDt branches")}; + fhicl::Atom fillTrkCrv{Name("fillTrkCrv"), Comment("Fill the track-CRV association branches of fits with trkCrvMatchTags"), true}; // per-branch configurations fhicl::Sequence> fits{Name("fits"), Comment("KalSeed collections to write into a single track branch")}; // tracker MC sub-config @@ -444,6 +449,9 @@ namespace mu2e { float rank = -1; // fit consistency normalised to sum to 1 over the cluster }; std::vector> _allTrkGroups; + // track-CRV association of each fit: the TrkCrvMatch (and its truth) of every KalSeed, found by Ptr + std::vector>> _allTrkCrvs; + art::ProductID _crvCoincPid; // collection the crvcoincs branch is filled from, for the candidate indices // track branches (outputs) std::map> _allTIs; std::map>> _allTSIs; @@ -452,6 +460,12 @@ namespace mu2e { std::map>> _allKLIs; std::map> _allTCHIs; std::map> _allTDtDtIs; + std::map> _allTCrvIs; + std::map>> _allTCrvXIs; + std::map>> _allTCrvCIs; + std::map>> _allTCrvCMCIs; + std::map>> _allTCrvXMCIs; + std::map>> _allTCrvTXMCIs; // quality branches (inputs) std::vector > > _allRQCHs; std::vector >> _allMVACHs; @@ -602,6 +616,16 @@ namespace mu2e { return _conf.trk().fillTrkDtDt() && !_allTrkFitBranches.at(i_trk_fit_branch).trkDtDtTag().empty(); } + // Track-CRV association: the global flag, plus TrkCrvMatch collections configured for this fit + bool fillTrkCrv(TrkFitBranchIndex i_trk_fit_branch) const { + return _conf.trk().fillTrkCrv() && !_allTrkFitBranches.at(i_trk_fit_branch).trkCrvMatchTags().empty(); + } + // its truth: tracker MC for this fit, plus TrkCrvMatchMC collections + bool fillTrkCrvMC(TrkFitBranchIndex i_trk_fit_branch) const { + auto const& cfg = _allTrkFitBranches.at(i_trk_fit_branch); + return fillTrkCrv(i_trk_fit_branch) && fillTrkMC(cfg.options()) && !cfg.trkCrvMatchMCTags().empty(); + } + // Track grouping (id and rank leaves): filled when a KalSeedCluster collection is configured for this fit bool fillTrkGroup(TrkFitBranchIndex i_trk_fit_branch) const { return !_allTrkFitBranches.at(i_trk_fit_branch).trkGroupTag().empty(); @@ -781,6 +805,12 @@ namespace mu2e { _allCHIs[i_trk_fit_branch] = {}; _allKLIs[i_trk_fit_branch] = {}; _allTDtDtIs[i_trk_fit_branch] = {}; + _allTCrvIs[i_trk_fit_branch] = {}; + _allTCrvXIs[i_trk_fit_branch] = {}; + _allTCrvCIs[i_trk_fit_branch] = {}; + _allTCrvCMCIs[i_trk_fit_branch] = {}; + _allTCrvXMCIs[i_trk_fit_branch] = {}; + _allTCrvTXMCIs[i_trk_fit_branch] = {}; _allMCVDInfos[i_trk_fit_branch] = {}; _allTCHIs[i_trk_fit_branch] = {}; _allMCTIs[i_trk_fit_branch] = {}; @@ -819,7 +849,7 @@ namespace mu2e { _ntuple=tfs->make("ntuple","Mu2e Event Ntuple"); _hVersion = tfs->make("version", "version number",3,0,3); _hVersion->GetXaxis()->SetBinLabel(1, "major"); _hVersion->SetBinContent(1, 6); - _hVersion->GetXaxis()->SetBinLabel(2, "minor"); _hVersion->SetBinContent(2, 16); + _hVersion->GetXaxis()->SetBinLabel(2, "minor"); _hVersion->SetBinContent(2, 17); _hVersion->GetXaxis()->SetBinLabel(3, "patch"); _hVersion->SetBinContent(3, 0); // MVA results configured with a model version are recorded in trkqual_metadata size_t nMVAModels = 0; @@ -868,6 +898,18 @@ namespace mu2e { if(fillTrkDtDt(i_trk_fit_branch)) { _ntuple->Branch((branch+"dtdt.").c_str(),&_allTDtDtIs.at(i_trk_fit_branch),_buffsize,_splitlevel); } + if(fillTrkCrv(i_trk_fit_branch)) { + if(i_trkFitConfig.trkCrvMatchMCTags().size() > 0 && i_trkFitConfig.trkCrvMatchMCTags().size() != i_trkFitConfig.trkCrvMatchTags().size()) + throw cet::exception("EventNtuple") << "branch " << branch << ": trkCrvMatchMCTags must have one entry per trkCrvMatchTags entry"; + _ntuple->Branch((branch+"crv.").c_str(),&_allTCrvIs.at(i_trk_fit_branch),_buffsize,_splitlevel); + _ntuple->Branch((branch+"crvxings.").c_str(),&_allTCrvXIs.at(i_trk_fit_branch),_buffsize,_splitlevel); + _ntuple->Branch((branch+"crvcands.").c_str(),&_allTCrvCIs.at(i_trk_fit_branch),_buffsize,_splitlevel); + if(fillTrkCrvMC(i_trk_fit_branch)) { + _ntuple->Branch((branch+"crvcandsmc.").c_str(),&_allTCrvCMCIs.at(i_trk_fit_branch),_buffsize,_splitlevel); + _ntuple->Branch((branch+"crvxingsmc.").c_str(),&_allTCrvXMCIs.at(i_trk_fit_branch),_buffsize,_splitlevel); + _ntuple->Branch((branch+"crvtruexingsmc.").c_str(),&_allTCrvTXMCIs.at(i_trk_fit_branch),_buffsize,_splitlevel); + } + } // TrkCaloHit: currently only 1 _ntuple->Branch((branch+"calohit.").c_str(),&_allTCHIs.at(i_trk_fit_branch)); @@ -1207,6 +1249,13 @@ namespace mu2e { _allMVACHs.clear(); _allKSDtDtHs.clear(); _allTrkGroups.clear(); + _allTrkCrvs.clear(); + _crvCoincPid = art::ProductID(); + if(_conf.crv().fill() && _conf.crv().fillCoincs()) { + art::Handle crvh; + event.getByLabel(_conf.crv().coincidencesTag(), crvh); + if(crvh.isValid()) _crvCoincPid = crvh.id(); + } if (_conf.trk().fill()) { for (TrkFitBranchIndex i_trk_fit_branch = 0; i_trk_fit_branch < _allTrkFitBranches.size(); ++i_trk_fit_branch) { @@ -1218,6 +1267,7 @@ namespace mu2e { _allRQCHs.push_back({}); _allKSDtDtHs.push_back(art::Handle()); _allTrkGroups.emplace_back(); + _allTrkCrvs.emplace_back(); continue; } art::Handle kalSeedPtrCollHandle; @@ -1232,6 +1282,23 @@ namespace mu2e { } _allKSDtDtHs.push_back(kalSeedDtDtCollHandle); + _allTrkCrvs.emplace_back(); + if(fillTrkCrv(i_trk_fit_branch)) { // map every KalSeed of the matcher collections to its record + auto& crvmap = _allTrkCrvs.back(); + auto const& mtags = i_trkFitConfig.trkCrvMatchTags(); + auto const& mctags = i_trkFitConfig.trkCrvMatchMCTags(); + bool wantMC = fillTrkCrvMC(i_trk_fit_branch); + for(size_t itag = 0; itag < mtags.size(); ++itag) { + auto const& mh = event.getValidHandle(art::InputTag(mtags[itag])); + const TrkCrvMatchMCCollection* mcs = nullptr; + if(wantMC) { + mcs = event.getValidHandle(art::InputTag(mctags.at(itag))).product(); + if(mcs->size() != mh->size()) throw cet::exception("EventNtuple") << mctags.at(itag) << " is not parallel to " << mtags[itag]; + } + for(size_t im = 0; im < mh->size(); ++im) crvmap[mh->at(im).track_] = {&mh->at(im), mcs ? &mcs->at(im) : nullptr}; + } + } + if(fillTrkGroup(i_trk_fit_branch)) { // if not filling, leave the map empty auto kalSeedClusterCollHandle = event.getValidHandle(i_trkFitConfig.trkGroupTag()); _allTrkGroups.push_back(makeTrkGroups(*kalSeedClusterCollHandle)); @@ -1346,6 +1413,12 @@ namespace mu2e { _allKLIs.at(i_trk_fit_branch).clear(); _allTCHIs.at(i_trk_fit_branch).clear(); _allTDtDtIs.at(i_trk_fit_branch).clear(); + _allTCrvIs.at(i_trk_fit_branch).clear(); + _allTCrvXIs.at(i_trk_fit_branch).clear(); + _allTCrvCIs.at(i_trk_fit_branch).clear(); + _allTCrvCMCIs.at(i_trk_fit_branch).clear(); + _allTCrvXMCIs.at(i_trk_fit_branch).clear(); + _allTCrvTXMCIs.at(i_trk_fit_branch).clear(); _allTSHIs.at(i_trk_fit_branch).clear(); _allTSHCIs.at(i_trk_fit_branch).clear(); @@ -1842,6 +1915,17 @@ namespace mu2e { } } + if(fillTrkCrv(i_trk_fit_branch)) { // one entry per track, also for tracks with no record + auto const& crvmap = _allTrkCrvs.at(i_trk_fit_branch); + auto icrv = crvmap.find(kseedptr); + const TrkCrvMatch* crvmatch = icrv != crvmap.end() ? icrv->second.first : nullptr; + _infoStructHelper.fillTrkCrvInfo(crvmatch, _crvCoincPid, _allTCrvIs.at(i_trk_fit_branch), _allTCrvXIs.at(i_trk_fit_branch), _allTCrvCIs.at(i_trk_fit_branch)); + if(fillTrkCrvMC(i_trk_fit_branch)) { + const TrkCrvMatchMC* crvmc = icrv != crvmap.end() ? icrv->second.second : nullptr; + _infoMCStructHelper.fillTrkCrvInfoMC(crvmc, _crvCoincPid, _allTCrvCMCIs.at(i_trk_fit_branch), _allTCrvXMCIs.at(i_trk_fit_branch), _allTCrvTXMCIs.at(i_trk_fit_branch)); + } + } + _infoStructHelper.fillTrkCaloHitInfo(kseed, _allTCHIs.at(i_trk_fit_branch)); if(kseed.hasCaloCluster()) { _tcnt._ndec = 1; diff --git a/src/InfoMCStructHelper.cc b/src/InfoMCStructHelper.cc index afee11b..dc2c586 100644 --- a/src/InfoMCStructHelper.cc +++ b/src/InfoMCStructHelper.cc @@ -637,4 +637,54 @@ namespace mu2e { mcstepinfos.emplace_back(mcstepinfo); } } + + void InfoMCStructHelper::fillTrkCrvInfoMC(const TrkCrvMatchMC* mc, const art::ProductID& crvPid, std::vector>& cands, + std::vector>& xings, std::vector>& trues) { + cands.emplace_back(); + xings.emplace_back(); + trues.emplace_back(); + if(mc == nullptr) return; + for(auto const& c : mc->cands_) { + TrkCrvCandInfoMC ci; + ci.hasmc = c.hasMC_; + ci.rel = c.rel_.relationship(); + ci.rem = c.rel_.removal(); + ci.edep_same = c.edepSame_; + ci.edep_related = c.edepRelated_; + ci.edep_total = c.edepTotal_; + cands.back().push_back(ci); + } + for(size_t ir = 0; ir < mc->recoXingTruth_.size(); ++ir) { + TrkCrvXingInfoMC xi; + xi.truexing = mc->recoXingTruth_[ir]; + if(ir < mc->recoXingNeighbor_.size()) xi.nbrxing = mc->recoXingNeighbor_[ir]; + xings.back().push_back(xi); + } + // the matcher's cluster collection, from any candidate of the reco record + art::ProductID clusterPid; + if(mc->match_.isNonnull() && mc->match_.isAvailable() && !mc->match_->cands_.empty()) clusterPid = mc->match_->cands_.front().cluster_.id(); + for(auto const& x : mc->xings_) { + TrkCrvTrueXingInfoMC ti; + ti.sid = x.sid_.id().id(); + ti.sector = x.sector_; + ti.rel = x.rel_.relationship(); + ti.rem = x.rel_.removal(); + if(x.sim_.isNonnull() && x.sim_.isAvailable()) ti.pdg = x.sim_->pdgId(); + ti.geom = x.geom_; + ti.pos = XYZVectorF(x.pos_.X(), x.pos_.Y(), x.pos_.Z()); + ti.dir = XYZVectorF(x.dir_.X(), x.dir_.Y(), x.dir_.Z()); + ti.time = x.time_; + ti.mom = x.mom_; + ti.dedgeu = x.dEdgeU_; + ti.dedgev = x.dEdgeV_; + ti.hasdeposits = mc->hasDeposits_; + ti.edep = x.edep_; + ti.nlayers = x.nLayers_; + ti.deppos = XYZVectorF(x.depPos_.X(), x.depPos_.Y(), x.depPos_.Z()); + ti.crvcoinc = (x.trueCluster_ >= 0 && crvPid.isValid() && clusterPid == crvPid) ? x.trueCluster_ : -1; + ti.cand = x.trueCand_; + ti.recoxing = x.recoXing_; + trues.back().push_back(ti); + } + } } diff --git a/src/InfoStructHelper.cc b/src/InfoStructHelper.cc index bcc14c2..90a9739 100644 --- a/src/InfoStructHelper.cc +++ b/src/InfoStructHelper.cc @@ -17,6 +17,9 @@ #include #include +#include +#include + namespace mu2e { // TODO: Propose to delete this function since it is unused void InfoStructHelper::fillHitCount(StrawHitFlagCollection const& shfC, HitCount& hitcount) { @@ -723,4 +726,86 @@ namespace mu2e { msdhitinfo.tot = hit.tot(); msdhitinfos.push_back(msdhitinfo); } + + void InfoStructHelper::fillTrkCrvInfo(const TrkCrvMatch* match, const art::ProductID& crvPid, std::vector& infos, + std::vector>& xings, std::vector>& cands) { + infos.emplace_back(); + xings.emplace_back(); + cands.emplace_back(); + if(match == nullptr) return; + auto const& m = *match; + auto& info = infos.back(); + info.matched = true; + info.nxings = m.xings_.size(); + info.ncands = m.cands_.size(); + info.bestgeom = m.bestGeom_; + info.besttime = m.bestTime_; + info.refsid = m.refSurface_.id().id() == SurfaceIdDetail::unknown ? -1 : static_cast(m.refSurface_.id().id()); + info.tref = m.tRef_; + info.probe = m.probe_; + info.timeoffset = m.timeOffset_; + for(auto const& x : m.xings_) { + TrkCrvXingInfo xi; + xi.sid = x.sid_.id().id(); + xi.sector = x.sector_; + xi.pos = XYZVectorF(x.pos_.X(), x.pos_.Y(), x.pos_.Z()); + xi.dir = XYZVectorF(x.dir_.X(), x.dir_.Y(), x.dir_.Z()); + xi.time = x.time_; + xi.sigu = x.sigU(); + xi.sigv = x.sigV(); + xi.rhouv = (xi.sigu > 0 && xi.sigv > 0) ? x.cov_(0,1) / (xi.sigu * xi.sigv) : 0.f; + xi.sigt = x.sigT_; + xi.mom = x.mom_; + xi.momerr = x.momErr_; + xi.inbounds = x.inBounds_; + xi.dedgeu = x.dEdgeU_; + xi.dedgev = x.dEdgeV_; + xi.edgesig = x.edgeSig_; + xi.best = x.best_; + xi.nlayers = std::min(x.layers_.size(), CRVId::nLayers); + for(int L = 0; L < xi.nlayers; ++L) { + auto const& p = x.layers_[L]; + xi.probe_bar[L] = p.bar_; + xi.probe_dbar[L] = p.dBar_ == INT8_MAX ? 127 : p.dBar_; + xi.probe_upred[L] = p.uPred_; + xi.probe_tpred[L] = p.tPred_; + xi.probe_pe[L] = p.pe_; + xi.probe_dt[L] = p.dt_; + xi.probe_incluster[L] = p.inCluster_; + xi.probe_utdiv[L] = p.uTdiv_; + } + xings.back().push_back(xi); + } + for(auto const& c : m.cands_) { + TrkCrvCandInfo ci; + ci.crvcoinc = (crvPid.isValid() && c.cluster_.id() == crvPid) ? static_cast(c.cluster_.key()) : -1; + ci.xing = c.xing_; + ci.sector = c.sector_; + ci.dtref = c.dtRef_; + ci.dtreftof = c.dtRefToF_; + ci.dtxing = c.dtXing_; + ci.du = c.du_; + ci.dv = c.dv_; + ci.sigu = c.sigU(); + ci.sigv = c.sigV(); + ci.rhouv = (ci.sigu > 0 && ci.sigv > 0) ? c.cov_(0,1) / (ci.sigu * ci.sigv) : 0.f; + ci.chi2 = c.chi2_; + ci.ndof = c.ndof_; + ci.nshare = c.nShare_; + ci.flags = c.flags_; + ci.geom = c.hasFlag(TrkCrvCandidate::geomCand); + ci.time = c.hasFlag(TrkCrvCandidate::timeCand); + ci.best = c.hasFlag(TrkCrvCandidate::bestForTrack); + ci.bestforcluster = c.hasFlag(TrkCrvCandidate::bestForCluster); + ci.exclusive = c.hasFlag(TrkCrvCandidate::exclusive); + ci.bestinsector = c.hasFlag(TrkCrvCandidate::bestInSector); + ci.samesector = c.hasFlag(TrkCrvCandidate::sameSector); + ci.outofbounds = c.hasFlag(TrkCrvCandidate::outOfBounds); + ci.singleended = c.hasFlag(TrkCrvCandidate::singleEnded); + ci.multisector = c.hasFlag(TrkCrvCandidate::multiSector); + ci.usedinfit = c.hasFlag(TrkCrvCandidate::usedInFit); + if(ci.geom) ++info.ngeom; + cands.back().push_back(ci); + } + } } diff --git a/src/classes.h b/src/classes.h index 06b297b..a020d39 100644 --- a/src/classes.h +++ b/src/classes.h @@ -14,6 +14,12 @@ #include "EventNtuple/inc/CentralHelixInfo.hh" #include "EventNtuple/inc/KinematicLineInfo.hh" #include "EventNtuple/inc/TrkDtDtInfo.hh" +#include "EventNtuple/inc/TrkCrvInfo.hh" +#include "EventNtuple/inc/TrkCrvXingInfo.hh" +#include "EventNtuple/inc/TrkCrvCandInfo.hh" +#include "EventNtuple/inc/TrkCrvCandInfoMC.hh" +#include "EventNtuple/inc/TrkCrvXingInfoMC.hh" +#include "EventNtuple/inc/TrkCrvTrueXingInfoMC.hh" #include "EventNtuple/inc/TimeClusterInfo.hh" #include "EventNtuple/inc/LumiStreamInfo.hh" #include "EventNtuple/inc/LineSeedInfo.hh" diff --git a/src/classes_def.xml b/src/classes_def.xml index 287a78e..840fef2 100644 --- a/src/classes_def.xml +++ b/src/classes_def.xml @@ -24,6 +24,23 @@ + + + + + + + + + + + + + + + + + diff --git a/utils/trkcrv_example.py b/utils/trkcrv_example.py new file mode 100644 index 0000000..529a706 --- /dev/null +++ b/utils/trkcrv_example.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python3 +"""Example: the track-CRV association branches of the EventNtuple. + +For a track branch (e.g. "trk") configured with trkCrvMatchTags, the ntuple holds, per track: + crv one TrkCrvInfo: counts, bestgeom / besttime indices into crvcands, reference times + crvxings TrkCrvXingInfo per CRV sector crossing of the extrapolation, with the 4-layer probe + crvcands TrkCrvCandInfo per associated CRV cluster: residuals, chi2, flags, and crvcoinc, the index into crvcoincs +and, with MC, crvcandsmc (parallel to crvcands), crvxingsmc (parallel to crvxings) and crvtruexingsmc. + +This script shows the common operations, all vectorised with awkward (no event loops): + 1. the best candidate of each track (bestgeom), and its residuals; + 2. the join from a candidate to its cluster in crvcoincs (PEs, layers); + 3. a simple veto-style selection: tracks with a geometric candidate inside |dtxing| < 20 ns; + and, for fits that do not reach the CRV (LoopHelix, time only), the best time candidate and a dtref window; + 4. the layer probe: per-layer pulse-finding fraction on crossed sectors; + 5. with MC: the truth relation of the best geometric and best time candidates (purity). + +Run in the Mu2e analysis environment (mu2einit; pyenv ana) or any env with uproot, awkward, numpy, matplotlib: + python3 trkcrv_example.py nts.root [--trk trk] [--entries 10000] [--plots outdir] +""" +import argparse +import os + +import awkward as ak +import numpy as np +import uproot + +REL_NAMES = ["no MC", "unrelated", "same", "daughter", "mother", "sibling", "udaughter", "umother", "usibling"] # rel + 2, or no MC + + +def load(path, trk, entries): + """Read the association branches and crvcoincs into one awkward array. + + Per-track branches (crv, crvcoincs) are split: their leaves are fields 'branch.leaf'. The per-candidate and + per-crossing branches are vectors of vectors, which ROOT does not split: each is one field holding records.""" + tree = uproot.open(path)["EventNtuple/ntuple"] + wanted = {trk + "crv", trk + "crvxings", trk + "crvcands", "crvcoincs", trk + "crvcandsmc", trk + "crvtruexingsmc"} + if trk + "crvcands" not in tree.keys(recursive=False): + raise SystemExit("no %scrvcands branch: was the ntuple made with trkCrvMatchTags for this branch?" % trk) + keys = [b.name for b in tree.itervalues(recursive=True) if b.name.split(".")[0] in wanted and len(b.branches) == 0] + arrays = tree.arrays(keys, entry_stop=entries) + return arrays, (trk + "crvcandsmc") in keys + + +def leaf(arrays, branch, name): + """The leaf 'name' of 'branch', split (field 'branch.name') or not (record field of 'branch').""" + key = branch + "." + name + if key in arrays.fields: + return arrays[key] + if branch in arrays.fields: + return arrays[branch][name] + raise KeyError(key) + + +def pick(per_cand, index): + """per_cand: [event][track][cand]; index: [event][track], -1 = none. Returns [event][track], None where index < 0.""" + safe = ak.mask(index, index >= 0) + return ak.firsts(per_cand[ak.singletons(safe, axis=1)], axis=2) + + +def per_track_coincs(coinc_leaf, ntrk_like): + """Repeat the event's crvcoincs leaf ([event][coinc]) for every track: [event][track][coinc].""" + counts = ak.num(ntrk_like, axis=1) + event_of_track = np.repeat(np.arange(len(counts)), ak.to_numpy(counts)) + return ak.unflatten(coinc_leaf[event_of_track], counts) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("ntuple") + ap.add_argument("--trk", default="trk", help="track branch name (default trk)") + ap.add_argument("--entries", type=int, default=None, help="read only the first N events") + ap.add_argument("--plots", default=None, help="directory for PNG plots (needs matplotlib)") + args = ap.parse_args() + + a, has_mc = load(args.ntuple, args.trk, args.entries) + crv, cands, xings = args.trk + "crv", args.trk + "crvcands", args.trk + "crvxings" + + # --- 1. best candidate per track --------------------------------------------------------------------------- + matched = leaf(a, crv, "matched") + bestgeom = leaf(a, crv, "bestgeom") + ntracks = int(ak.sum(ak.num(matched, axis=1))) + nxing = leaf(a, crv, "nxings") + has_xing = nxing > 0 + has_geom = bestgeom >= 0 + print("tracks %d, with a TrkCrvMatch record %d, crossing the CRV %d, with a geometric candidate %d" + % (ntracks, ak.sum(matched), ak.sum(has_xing), ak.sum(has_geom))) + best_dv = pick(leaf(a, cands, "dv"), bestgeom) + best_dtxing = pick(leaf(a, cands, "dtxing"), bestgeom) + best_chi2 = pick(leaf(a, cands, "chi2"), bestgeom) + best_ndof = pick(leaf(a, cands, "ndof"), bestgeom) + best_sector = pick(leaf(a, cands, "sector"), bestgeom) + dv = ak.to_numpy(ak.flatten(ak.drop_none(best_dv), axis=None)) + if len(dv): + print("best geometric candidate: median dv %.1f mm, median dtxing %.2f ns, median chi2/ndof %.2f" + % (np.median(dv), np.median(ak.to_numpy(ak.flatten(ak.drop_none(best_dtxing), axis=None))), + np.median(ak.to_numpy(ak.flatten(ak.drop_none(best_chi2 / best_ndof), axis=None))))) + + # --- 2. join candidates to crvcoincs ----------------------------------------------------------------------- + if "crvcoincs.PEs" in a.fields: + coinc_idx = leaf(a, cands, "crvcoinc") # [event][track][cand] + pes_by_trk = per_track_coincs(a["crvcoincs.PEs"], bestgeom) # [event][track][coinc] + cand_pes = pes_by_trk[ak.mask(coinc_idx, coinc_idx >= 0)] # [event][track][cand], None if not in crvcoincs + best_pes = pick(cand_pes, bestgeom) + pes = ak.to_numpy(ak.flatten(ak.drop_none(best_pes), axis=None)) + if len(pes): + print("PEs of the best geometric candidate's cluster: median %.0f" % np.median(pes)) + n_unindexed = ak.sum(coinc_idx < 0) + if n_unindexed: + print("note: %d candidates are not in crvcoincs (the matcher used another cluster collection)" % n_unindexed) + + # --- 3. a veto-style selection ------------------------------------------------------------------------------- + in_time = leaf(a, cands, "geom") & (abs(leaf(a, cands, "dtxing")) < 20.0) + vetoed = ak.any(in_time, axis=2) # [event][track] + print("tracks with a geometric candidate within |dtxing| < 20 ns: %d" % ak.sum(vetoed)) + + # time only (e.g. LoopHelix fits): dtref = track reference time - cluster time, at every candidate + besttime = leaf(a, crv, "besttime") + dtref_best = ak.to_numpy(ak.flatten(ak.drop_none(pick(leaf(a, cands, "dtref"), besttime)), axis=None)) + print("tracks with a time candidate: %d" % ak.sum(besttime >= 0)) + if len(dtref_best): + print("best time candidate: median dtref %.1f ns" % np.median(dtref_best)) + dtref = leaf(a, cands, "dtref") + in_window = ak.any(leaf(a, cands, "time") & (dtref > 0) & (dtref < 150), axis=2) # an example veto window + print("tracks with a time candidate at 0 < dtref < 150 ns: %d" % ak.sum(in_window)) + + # --- 4. layer probe ------------------------------------------------------------------------------------------- + pbar = leaf(a, xings, "probe_bar") # [event][track][xing][layer] + pdbar = leaf(a, xings, "probe_dbar") + predicted = pbar >= 0 + found = predicted & (pdbar != 127) + pred_per_layer = np.array([ak.sum(predicted[..., L]) for L in range(4)]) + found_per_layer = np.array([ak.sum(found[..., L]) for L in range(4)]) + if pred_per_layer.sum(): + frac = np.divide(found_per_layer, pred_per_layer, out=np.zeros(4), where=pred_per_layer > 0) + print("layer probe, pulse found per predicted layer: " + ", ".join("L%d %.3f" % (L, f) for L, f in enumerate(frac))) + + # --- 5. truth of the best candidate --------------------------------------------------------------------------- + rel_counts = None + if has_mc: + relbin = ak.where(leaf(a, args.trk + "crvcandsmc", "hasmc"), leaf(a, args.trk + "crvcandsmc", "rel") + 2, 0) + r = ak.to_numpy(ak.flatten(ak.drop_none(pick(relbin, bestgeom)), axis=None)) + if len(r): + rel_counts = np.bincount(r.astype(int), minlength=len(REL_NAMES))[:len(REL_NAMES)] + print("best geometric candidate truth: " + ", ".join("%s %.3f" % (n, c / len(r)) for n, c in zip(REL_NAMES, rel_counts))) + rt = ak.to_numpy(ak.flatten(ak.drop_none(pick(relbin, besttime)), axis=None)) + if len(rt): + counts = np.bincount(rt.astype(int), minlength=len(REL_NAMES))[:len(REL_NAMES)] + print("best time candidate truth: " + ", ".join("%s %.3f" % (n, c / len(rt)) for n, c in zip(REL_NAMES, counts))) + + if args.plots: + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + os.makedirs(args.plots, exist_ok=True) + sectors = ak.to_numpy(ak.flatten(ak.drop_none(best_sector), axis=None)) + fig, ax = plt.subplots(1, 3, figsize=(15, 4)) + for s in np.unique(sectors): + ax[0].hist(dv[sectors == s], bins=100, range=(-200, 200), histtype="step", label="sector %d" % s) + ax[0].set_xlabel("dv, best geometric candidate [mm]") + ax[0].legend(fontsize=7) + ax[1].hist(ak.to_numpy(ak.flatten(ak.drop_none(best_dtxing), axis=None)), bins=100, range=(-50, 50), histtype="step") + ax[1].set_xlabel("dtxing, best geometric candidate [ns]") + if pred_per_layer.sum(): + ax[2].bar(range(4), frac) + ax[2].set_xlabel("CRV layer") + ax[2].set_ylabel("pulse found / predicted") + fig.tight_layout() + out = os.path.join(args.plots, "trkcrv_example.png") + fig.savefig(out, dpi=120) + print("wrote " + out) + + +if __name__ == "__main__": + main() diff --git a/validation/ntuplehelper-test.py b/validation/ntuplehelper-test.py index eec4192..416ff2b 100644 --- a/validation/ntuplehelper-test.py +++ b/validation/ntuplehelper-test.py @@ -4,7 +4,7 @@ print("Testing a leaf from each branch") print("=========") -nthelp.whatis(['evtinfomc.pbtime', 'evtinfo.event', 'hitcount.nbkg', 'tcnt.ndem', 'lumistream.nTrackerHits', 'trkmcsim.pdg', 'trkcalohit.trkdepth', 'trkcalohitmc.nsim', 'trkhits.ptoca', 'trkhitsmc.edep', 'trkmats.tlen', 'crvsummary.totalPEs', 'crvsummarymc.sectorNumber', 'crvcoincs.time', 'crvcoincsmc.primaryE', 'crvcoincsmcplane.dir', 'trkmcsci.dp', 'trkmcssi.dp', 'trk.nactive', 'trkmc.ndigigood', 'trksegs.mom', 'trksegpars_lh.cx', 'trksegpars_ch.omega', 'trksegpars_kl.phi0', 'trkqual.result', 'helices.chi2xy', 'trksegsmc.path']) +nthelp.whatis(['evtinfomc.pbtime', 'evtinfo.event', 'hitcount.nbkg', 'tcnt.ndem', 'lumistream.nTrackerHits', 'trkmcsim.pdg', 'trkcalohit.trkdepth', 'trkcalohitmc.nsim', 'trkhits.ptoca', 'trkhitsmc.edep', 'trkmats.tlen', 'crvsummary.totalPEs', 'crvsummarymc.sectorNumber', 'crvcoincs.time', 'crvcoincsmc.primaryE', 'crvcoincsmcplane.dir', 'trkmcsci.dp', 'trkmcssi.dp', 'trk.nactive', 'trkmc.ndigigood', 'trksegs.mom', 'trksegpars_lh.cx', 'trksegpars_ch.omega', 'trksegpars_kl.phi0', 'trkqual.result', 'helices.chi2xy', 'trksegsmc.path', 'trkcrv.bestgeom', 'trkcrvxings.probe_dbar', 'trkcrvcands.dv', 'trkcrvcandsmc.rel', 'trkcrvxingsmc.truexing', 'trkcrvtruexingsmc.pdg']) print("Testing a few leaves from a single branch (should only print the branch description once)") print("=========")