Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-15 09:24:49

0001 #!/usr/bin/env python3
0002 
0003 import argparse
0004 import pathlib
0005 
0006 import acts
0007 import acts.examples
0008 from acts.examples.simulation import (
0009     addPythia8,
0010     ParticleSelectorConfig,
0011     addGenParticleSelection,
0012     addFatras,
0013     addDigitization,
0014     addDigiParticleSelection,
0015 )
0016 
0017 from acts.examples.reconstruction import (
0018     addSeeding,
0019     addCKFTracks,
0020     TrackSelectorConfig,
0021     SeedingAlgorithm,
0022 )
0023 
0024 from acts.examples.root import (
0025     RootSpacePointWriter,
0026 )
0027 from pathlib import Path
0028 
0029 from typing import Optional
0030 from enum import Enum
0031 
0032 DetectorName = Enum("DetectorName", "ODD generic")
0033 
0034 HashingMetric = Enum("HashingMetric", "dphi dR")
0035 
0036 
0037 class Config:
0038     def __init__(
0039         self,
0040         mu: int = None,
0041         bucketSize: int = 100,
0042         maxSeedsPerSpM: int = 10,
0043         detector: DetectorName = DetectorName.generic,
0044         seedingAlgorithm: SeedingAlgorithm = SeedingAlgorithm.HashingPrototype,
0045         metric: str = HashingMetric.dphi,
0046         annoySeed: int = 123456789,
0047         zBins: int = 0,
0048         phiBins: int = 100,
0049     ):
0050         self.mu = mu
0051         self.bucketSize = bucketSize
0052         self.maxSeedsPerSpM = maxSeedsPerSpM
0053         self.detector = detector
0054         self.seedingAlgorithm = (
0055             seedingAlgorithm
0056             if type(seedingAlgorithm) == SeedingAlgorithm
0057             else SeedingAlgorithm[seedingAlgorithm]
0058         )
0059         self.metric = metric if type(metric) == HashingMetric else HashingMetric[metric]
0060         self.annoySeed = annoySeed
0061         self.zBins = zBins
0062         self.phiBins = phiBins
0063 
0064         if seedingAlgorithm == SeedingAlgorithm.GridTriplet:
0065             self.bucketSize = 0
0066             self.metric = HashingMetric.dphi
0067             self.annoySeed = 123456789
0068             self.zBins = 0
0069             self.phiBins = 0
0070 
0071     def __str__(self):
0072         return (
0073             f"mu={self.mu}, bucketSize={self.bucketSize}, maxSeedsPerSpM={self.maxSeedsPerSpM}, "
0074             f"detector={self.detector}, seedingAlgorithm={self.seedingAlgorithm}, metric={self.metric}, "
0075             f"annoySeed={self.annoySeed}, zBins={self.zBins}, phiBins={self.phiBins}"
0076         )
0077 
0078     def __repr__(self):
0079         return self.__str__()
0080 
0081     def save(self, path: pathlib.Path):
0082         with open(path, "w") as f:
0083             f.write(str(self))
0084 
0085     @property
0086     def doHashing(self):
0087         return self.bucketSize > 0
0088 
0089     @property
0090     def directory(self):
0091         outDir = f"detector_{extractEnumName(self.detector)}"
0092         outDir += "_output"
0093         doHashing = self.bucketSize > 0
0094         if doHashing:
0095             outDir += "_hashing"
0096 
0097         outDir += f"_mu_{self.mu}"
0098         if doHashing:
0099             outDir += f"_bucket_{self.bucketSize}"
0100 
0101         outDir += f"_maxSeedsPerSpM_{self.maxSeedsPerSpM}"
0102 
0103         outDir += f"_seedFinderConfig_{'TrackML' if self.detector == DetectorName.generic else 'ODD'}"
0104 
0105         outDir += f"_seedingAlgorithm_{extractEnumName(self.seedingAlgorithm)}Seeding"
0106         if doHashing:
0107             if self.metric != "angular":
0108                 outDir += f"_metric_{extractEnumName(self.metric)}"
0109             outDir += f"_annoySeed_{self.annoySeed}"
0110             if self.zBins != 0:
0111                 outDir += f"_zBins_{self.zBins}"
0112             if self.phiBins != 0:
0113                 outDir += f"_phiBins_{self.phiBins}"
0114 
0115         return outDir
0116 
0117     def getDetectorInfo(self):
0118         actsExamplesDir = Path(__file__).parent.parent.parent
0119 
0120         if self.detector == DetectorName.ODD:
0121             from acts.examples.odd import (
0122                 getOpenDataDetector,
0123                 getOpenDataDetectorDirectory,
0124             )
0125 
0126             geoDir = getOpenDataDetectorDirectory()
0127 
0128             oddMaterialMap = geoDir / "data/odd-material-maps.root"
0129             oddDigiConfig = actsExamplesDir / "Configs/odd-digi-smearing-config.json"
0130             oddSeedingSel = actsExamplesDir / "Configs/odd-seeding-config.json"
0131             oddMaterialDeco = acts.root.RootMaterialDecorator(
0132                 fileName=str(oddMaterialMap), level=acts.logging.INFO
0133             )
0134 
0135             detector = getOpenDataDetector(
0136                 odd_dir=geoDir, materialDecorator=oddMaterialDeco
0137             )
0138             trackingGeometry = detector.trackingGeometry()
0139 
0140             digiConfig = oddDigiConfig
0141 
0142             geoSelectionConfigFile = oddSeedingSel
0143 
0144         elif self.detector == DetectorName.generic:
0145             print("Create detector and tracking geometry")
0146 
0147             detector = acts.examples.GenericDetector()
0148             trackingGeometry = detector.trackingGeometry()
0149             digiConfig = actsExamplesDir / "Configs/generic-digi-smearing-config.json"
0150             geoSelectionConfigFile = (
0151                 actsExamplesDir / "Configs/generic-seeding-config.json"
0152             )
0153         else:
0154             exit("Detector not supported")
0155 
0156         return detector, trackingGeometry, digiConfig, geoSelectionConfigFile
0157 
0158 
0159 def extractEnumName(enumvar):
0160     return str(enumvar).split(".")[-1]
0161 
0162 
0163 def runHashingSeeding(
0164     nevents: int,
0165     trackingGeometry: acts.TrackingGeometry,
0166     field: acts.MagneticFieldProvider,
0167     outputDir: pathlib.Path,
0168     saveFiles: bool,
0169     npileup: int,
0170     seedingAlgorithm: SeedingAlgorithm,
0171     maxSeedsPerSpM: int,
0172     digiConfig: pathlib.Path,
0173     geoSelectionConfigFile: pathlib.Path,
0174     eta=4,
0175     rnd: acts.examples.RandomNumbers = acts.examples.RandomNumbers(seed=42),
0176     config: Config = None,
0177     s=None,
0178 ):
0179     from acts.examples.reconstruction import (
0180         SeedFinderConfigArg,
0181         SeedFinderOptionsArg,
0182         HashingTrainingConfigArg,
0183         HashingAlgorithmConfigArg,
0184     )
0185 
0186     u = acts.UnitConstants
0187 
0188     outputDir = Path(outputDir)
0189 
0190     s = s or acts.examples.Sequencer(
0191         events=nevents,
0192         numThreads=1,
0193         outputDir=str(outputDir),
0194         trackFpes=False,
0195     )
0196 
0197     addPythia8(
0198         s,
0199         hardProcess=["Top:qqbar2ttbar=on"],
0200         npileup=npileup,
0201         vtxGen=acts.examples.GaussianVertexGenerator(
0202             stddev=acts.Vector4(0, 0, 50 * u.mm, 0),
0203             mean=acts.Vector4(0, 0, 0, 0),
0204         ),
0205         rnd=rnd,
0206     )
0207 
0208     addGenParticleSelection(
0209         s,
0210         ParticleSelectorConfig(
0211             rho=(0.0, 24 * u.mm),
0212             absZ=(0.0, 1.0 * u.m),
0213         ),
0214     )
0215 
0216     addFatras(
0217         s,
0218         trackingGeometry,
0219         field,
0220         enableInteractions=True,
0221         # outputDirRoot=outputDir,  # RootParticle ERROR when setting the outputDirRoot
0222         outputDirCsv=outputDir if saveFiles else None,
0223         rnd=rnd,
0224     )
0225 
0226     addDigitization(
0227         s,
0228         trackingGeometry,
0229         field,
0230         digiConfigFile=digiConfig,
0231         outputDirRoot=outputDir,
0232         outputDirCsv=outputDir if saveFiles else None,
0233         rnd=rnd,
0234     )
0235 
0236     addDigiParticleSelection(
0237         s,
0238         ParticleSelectorConfig(
0239             pt=(1.0 * u.GeV, None),
0240             eta=(-eta, eta),
0241             measurements=(9, None),
0242             removeNeutral=True,
0243         ),
0244     )
0245 
0246     import numpy as np
0247 
0248     cotThetaMax = 1 / (np.tan(2 * np.arctan(np.exp(-eta))))  # =1/tan(2Ă—atan(e^(-eta)))
0249     seedFinderConfigArg = SeedFinderConfigArg(
0250         r=(None, 200 * u.mm),  # rMin=default, 33mm
0251         deltaR=(1 * u.mm, 300 * u.mm),
0252         collisionRegion=(-250 * u.mm, 250 * u.mm),
0253         z=(-2000 * u.mm, 2000 * u.mm),
0254         maxSeedsPerSpM=maxSeedsPerSpM,
0255         sigmaScattering=5,
0256         radLengthPerSeed=0.1,
0257         minPt=500 * u.MeV,
0258         impactMax=3 * u.mm,
0259         cotThetaMax=cotThetaMax,
0260     )
0261 
0262     seedFinderOptionsArg: SeedFinderOptionsArg = SeedFinderOptionsArg(bFieldInZ=2 * u.T)
0263     hashingTrainingConfigArg: HashingTrainingConfigArg = HashingTrainingConfigArg(
0264         annoySeed=config.annoySeed, f=2 if config.metric == HashingMetric.dR else 1
0265     )
0266     hashingAlgorithmConfigArg: HashingAlgorithmConfigArg = HashingAlgorithmConfigArg(
0267         bucketSize=config.bucketSize,
0268         zBins=config.zBins,
0269         phiBins=config.phiBins,
0270     )
0271     initialSigmas: Optional[list] = [
0272         1 * u.mm,
0273         1 * u.mm,
0274         1 * u.degree,
0275         1 * u.degree,
0276         0.1 / u.GeV,
0277         1 * u.ns,
0278     ]
0279 
0280     initialVarInflation: Optional[list] = [1.0] * 6
0281 
0282     addSeeding(
0283         s,
0284         trackingGeometry,
0285         field,
0286         seedFinderConfigArg,
0287         seedFinderOptionsArg,
0288         hashingTrainingConfigArg,
0289         hashingAlgorithmConfigArg,
0290         seedingAlgorithm=seedingAlgorithm,
0291         geoSelectionConfigFile=geoSelectionConfigFile,
0292         initialSigmas=initialSigmas,
0293         initialVarInflation=initialVarInflation,
0294         outputDirRoot=outputDir,
0295         outputDirCsv=outputDir if saveFiles else None,
0296     )
0297 
0298     return s
0299 
0300 
0301 if __name__ == "__main__":
0302     eta = 3
0303 
0304     parser = argparse.ArgumentParser(
0305         description="Example script to run seed finding with hashing"
0306     )
0307     parser.add_argument("--mu", type=int, default=50)
0308     parser.add_argument("--bucketSize", type=int, default=100)
0309     parser.add_argument(
0310         "--nevents",
0311         type=int,
0312         default=20,
0313     )
0314     parser.add_argument("--maxSeedsPerSpM", type=int, default=10)
0315     parser.add_argument("--seedingAlgorithm", type=str, default="HashingPrototype")
0316     parser.add_argument("--saveFiles", type=bool, default=True)
0317     parser.add_argument("--annoySeed", type=int, default=123456789)
0318     parser.add_argument("--zBins", type=int, default=0)
0319     parser.add_argument("--phiBins", type=int, default=100)
0320     parser.add_argument("--metric", type=str, default="dphi")
0321     args = parser.parse_args()
0322 
0323     print(args)
0324 
0325     mu = args.mu
0326     bucketSize = args.bucketSize
0327     nevents = args.nevents
0328     saveFiles = args.saveFiles
0329     annoySeed = args.annoySeed
0330     zBins = args.zBins
0331     phiBins = args.phiBins
0332     maxSeedsPerSpM = args.maxSeedsPerSpM
0333 
0334     metric = HashingMetric[args.metric]
0335 
0336     seedingAlgorithm = SeedingAlgorithm[args.seedingAlgorithm]
0337 
0338     detector = DetectorName.generic
0339 
0340     u = acts.UnitConstants
0341 
0342     config = Config(
0343         mu=mu,
0344         bucketSize=bucketSize,
0345         maxSeedsPerSpM=maxSeedsPerSpM,
0346         detector=detector,
0347         seedingAlgorithm=seedingAlgorithm,
0348         metric=metric,
0349         annoySeed=annoySeed,
0350         zBins=zBins,
0351         phiBins=phiBins,
0352     )
0353 
0354     doHashing = config.doHashing
0355     bucketSize = config.bucketSize
0356     npileup = config.mu
0357     maxSeedsPerSpM = config.maxSeedsPerSpM
0358 
0359     outputDir = pathlib.Path.cwd() / config.directory
0360 
0361     if not outputDir.exists():
0362         outputDir.mkdir(parents=True)
0363 
0364     config.save(outputDir / "config_file.txt")
0365 
0366     field = acts.ConstantBField(acts.Vector3(0.0, 0.0, 2.0 * u.T))
0367     rnd = acts.examples.RandomNumbers(seed=42)
0368 
0369     _, trackingGeometry, digiConfig, geoSelectionConfigFile = config.getDetectorInfo()
0370 
0371     s = runHashingSeeding(
0372         nevents,
0373         trackingGeometry,
0374         field,
0375         outputDir,
0376         saveFiles,
0377         npileup,
0378         seedingAlgorithm,
0379         maxSeedsPerSpM,
0380         digiConfig,
0381         geoSelectionConfigFile,
0382         rnd=rnd,
0383         eta=eta,
0384         config=config,
0385     )
0386 
0387     logLevel = acts.logging.VERBOSE
0388     rootSpacePointsWriter = RootSpacePointWriter(
0389         level=logLevel,
0390         inputSpacePoints="spacepoints",
0391         filePath=str(outputDir / "spacepoints.root"),
0392     )
0393     s.addWriter(rootSpacePointsWriter)
0394 
0395     rootSeedsWriter = acts.examples.root.RootSeedWriter(
0396         level=logLevel,
0397         inputSeeds="seeds",
0398         filePath=str(outputDir / "seeds.root"),
0399     )
0400     s.addWriter(rootSeedsWriter)
0401 
0402     addCKFTracks(
0403         s,
0404         trackingGeometry,
0405         field,
0406         TrackSelectorConfig(
0407             pt=(1.0 * u.GeV, None),
0408             absEta=(None, eta),
0409             nMeasurementsMin=6,
0410         ),
0411         twoWay=False,
0412         outputDirRoot=outputDir,
0413     )
0414 
0415     s.run()