FairShip
Loading...
Searching...
No Matches
UpstreamTaggerDetector.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2# SPDX-FileCopyrightText: Copyright CERN for the benefit of the SHiP Collaboration
3
4import math
5import re
6from dataclasses import dataclass, field
7from typing import Any
8
9import global_variables
10import ROOT
11from BaseDetector import BaseDetector
12
13
14@dataclass
16 """MC points collected in one constituent tile."""
17
18 first: Any # earliest UpstreamTaggerPoint in the tile
19 position: ROOT.TVector3 # tile center
20 points: list[int] = field(default_factory=list) # indices of its MC points
21 signals: list[float] = field(default_factory=list) # unrounded ADC signal of each point
22
23
24class UBTGeometryMismatch(Exception):
25 """The UBT points of a geometry cannot be digitized with its UBT map."""
26
27
29 # The UBT assembly: its daughter nodes are the regions, with the region ID
30 # as copy number, in volumes named UpstreamTaggerRegion_<tile size>cm_<shape>
31 # (see UpstreamTagger::ConstructGeometry). Geometry files with one volume
32 # per region name them UpstreamTaggerRegion<id>_<tile size>cm.
33 ASSEMBLY_VOLUME = "Upstream_Tagger"
34 REGION_VOLUME_PATTERN = re.compile(r"UpstreamTaggerRegion\d*_(\d+)cm(?:_|$)")
35
36 def __init__(self, name, intree, outtree=None, mcBranchName=None) -> None:
37 # Before creating any output branch, so that a UBT that cannot be
38 # digitized leaves none.
39 self.validate_stored_geometry(ROOT.gGeoManager, global_variables.ShipGeo.UpstreamTagger)
40 super().__init__(name, intree, mcBranchName=mcBranchName, outtree=outtree)
41 # Parallel to the MC link: for each hit, the unrounded ADC signal of
42 # each of its MC points, in the same order as the point indices.
43 self.MCadc = None
44 if mcBranchName:
45 self.MCadc = ROOT.std.vector("std::vector<float>")()
46 self.outtree.Branch(f"{mcBranchName}ADC", self.MCadc)
47
48 # The UBT parameters are the same for every MC point of the run: read
49 # them once here.
50 ubt_geo = global_variables.ShipGeo.UpstreamTagger
51 # Region ID -> constituent tile side. Some ROOT/Python serialization
52 # paths stringify the dictionary keys.
53 self._tile_sizes = {int(region): float(size) for region, size in ubt_geo.RegionTileSize.items()}
54 self._grid_x = (ubt_geo.TileGridOriginX, ubt_geo.TileGridEndX)
55 self._grid_y = (ubt_geo.TileGridOriginY, ubt_geo.TileGridEndY)
56 self._z = ubt_geo.z
57 self._time_res = ubt_geo.TimeResolution
58 self._trigger_threshold = ubt_geo.ADCTriggerThreshold
59
60 # Tile-ID grid: cells of the smallest tile side over the tile grid, and
61 # for each tile side the offset of its ID namespace (see tile_id).
62 self._grid_size = min(self._tile_sizes.values())
63 if self._grid_size <= 0.0:
64 raise ValueError(f"Invalid UBT tile-ID grid size: {self._grid_size}")
65 self._columns = round((self._grid_x[1] - self._grid_x[0]) / self._grid_size)
66 self._rows = round((self._grid_y[1] - self._grid_y[0]) / self._grid_size)
67 self._id_offsets = {}
68 for tile_size in set(self._tile_sizes.values()):
69 multiple = round(tile_size / self._grid_size)
70 if multiple <= 0 or not math.isclose(tile_size, multiple * self._grid_size, rel_tol=0.0, abs_tol=1.0e-9):
71 raise ValueError(
72 f"UBT tile size {tile_size} cm is not an integer multiple of the tile-ID base cell size"
73 f" {self._grid_size} cm"
74 )
75 self._id_offsets[tile_size] = (multiple - 1) * self._columns * self._rows
76 # For each tile side, the number of its tiles along x and y
77 self._tile_counts = {
78 tile_size: (self._tile_count(*self._grid_x, tile_size), self._tile_count(*self._grid_y, tile_size))
79 for tile_size in set(self._tile_sizes.values())
80 }
81
83 ubt_geo.ADCResponseMapFile, set(self._tile_sizes.values())
84 )
85
86 @classmethod
87 def validate_stored_geometry(cls, geo_manager, ubt_geo) -> None:
88 """Raise UBTGeometryMismatch if the UBT points of this geometry cannot be digitized.
89
90 The decision is taken from the simulated geometry, not from the
91 configuration, which configure replaces for old geometry files. A
92 geometry without any UBT region predates the scintillator UBT: its UBT
93 was a vacuum box, whose detector IDs are not region IDs. Otherwise
94 every region of the UBT map must be placed, with the same tile size.
95 """
96 if not geo_manager:
97 raise RuntimeError("Load the geometry of the simulation (FAIRGeom) before digitizing the UBT")
98 volumes = {} # region ID -> tile size suffix, e.g. "4cm"
99 assembly = geo_manager.GetVolume(cls.ASSEMBLY_VOLUME)
100 nodes = assembly.GetNodes() if assembly else None
101 for node in nodes or []:
102 match = cls.REGION_VOLUME_PATTERN.match(node.GetVolume().GetName())
103 if match:
104 volumes[node.GetNumber()] = f"{match.group(1)}cm"
105 if not volumes:
107 "the geometry has no UBT regions: it predates the scintillator UBT (a vacuum box)"
108 )
109 expected = {int(region): f"{round(float(size))}cm" for region, size in ubt_geo.RegionTileSize.items()}
110 differing = sorted(r for r in expected.keys() | volumes.keys() if expected.get(r) != volumes.get(r))
111 if differing:
113 f"{len(differing)} UBT regions of the geometry differ from the UBT map, e.g. {differing[:5]}"
114 )
115
116 def delete(self) -> None:
117 """Clear the hit, MC link and per-point ADC containers."""
118 super().delete()
119 if self.MCadc is not None:
120 self.MCadc.clear()
121
122 @staticmethod
123 def _load_adc_response_maps(path: str, tile_sizes: set[float]) -> dict[float, ROOT.TH2D]:
124 """Load the ADC/MeV vs local position (mm) TH2D for each tile size (cm)."""
125 # PyROOT raises OSError when the file cannot be opened, also when it is
126 # not a ROOT file, e.g. a Git LFS pointer that was not fetched.
127 try:
128 response_file = ROOT.TFile.Open(path)
129 except OSError as error:
130 raise OSError(
131 f"Cannot open the UBT ADC response map file {path}; it is stored with Git LFS, so run `git lfs pull`"
132 " if it has not been fetched"
133 ) from error
134 maps = {}
135 for tile_size in tile_sizes:
136 name = f"adc_per_mev_{round(10.0 * tile_size)}mm"
137 histogram = response_file.Get(name)
138 if not isinstance(histogram, ROOT.TH2D):
139 raise ValueError(f"UBT ADC response map {path} has no TH2D '{name}'")
140 histogram.SetDirectory(ROOT.gROOT)
141 maps[tile_size] = histogram
142 response_file.Close()
143 return maps
144
145 @staticmethod
146 def _tile_count(grid_origin: float, grid_end: float, tile_size: float) -> int:
147 """Return the number of tiles of tile_size along a tile grid axis."""
148 tile_count = round((grid_end - grid_origin) / tile_size)
149 if tile_count <= 0:
150 raise ValueError(f"Invalid UBT tile grid [{grid_origin}, {grid_end}] with tile size {tile_size}")
151 return tile_count
152
153 @staticmethod
155 coordinate: float, grid_origin: float, grid_end: float, tile_size: float, tile_count: int
156 ) -> float:
157 """Return the globally aligned tile center containing coordinate."""
158 coordinate = min(max(coordinate, grid_origin), math.nextafter(grid_end, grid_origin))
159 # At the positive boundary, floating-point subtraction and division
160 # can round nextafter(grid_end, grid_origin) back to an exact quotient
161 # of tile_count. Cap the result so the last valid tile is selected.
162 tile_index = min(math.floor((coordinate - grid_origin) / tile_size), tile_count - 1)
163 return grid_origin + (tile_index + 0.5) * tile_size
164
165 def digitized_position(self, point, tile_size: float) -> ROOT.TVector3:
166 """Map an MC point to the center of its 2x2 or 4x4 cm2 tile."""
167 columns, rows = self._tile_counts[tile_size]
168 x = self._tile_center(point.GetX(), self._grid_x[0], self._grid_x[1], tile_size, columns)
169 y = self._tile_center(point.GetY(), self._grid_y[0], self._grid_y[1], tile_size, rows)
170 return ROOT.TVector3(x, y, self._z)
171
172 def tile_id(self, position: ROOT.TVector3, tile_size: float) -> int:
173 """Return a stable unique ID for a constituent tile.
174
175 The tile is identified by its lower-left cell on the tile-ID grid, the
176 grid of the smallest tile side (2 cm) over the tile grid bounds, with
177 ``columns`` x ``rows`` cells:
178
179 tile ID = (tile side / grid size - 1) * columns * rows + row * columns + column
180
181 So each tile side has its own range of ``columns * rows`` IDs, and a
182 2 cm and a 4 cm tile with the same lower-left cell get different IDs.
183 For the default geometry (340 x 504 cm2, 170 x 252 cells), the range
184 of 2 cm tiles is [0, 42840) and that of 4 cm tiles [42840, 85680). The
185 stride follows the UBT box, so decoding an ID needs the grid of its
186 geometry:
187
188 side_index, cell = divmod(tile_id, columns * rows)
189 row, column = divmod(cell, columns)
190 """
191 column = round((position.X() - tile_size / 2.0 - self._grid_x[0]) / self._grid_size)
192 row = round((position.Y() - tile_size / 2.0 - self._grid_y[0]) / self._grid_size)
193 if not (0 <= column < self._columns and 0 <= row < self._rows):
194 raise ValueError(
195 f"UBT tile at ({position.X()}, {position.Y()}) cm with size {tile_size} cm "
196 f"maps to cell ({column}, {row}), outside the {self._columns} x {self._rows} tile-ID grid; "
197 f"x bounds={self._grid_x} cm, y bounds={self._grid_y} cm, base cell size={self._grid_size} cm"
198 )
199 return self._id_offsets[tile_size] + row * self._columns + column
200
201 def adc_signal(self, point, tile_center: ROOT.TVector3, tile_size: float) -> float:
202 """Return the (unrounded) ADC signal of a point from its energy and position in the tile."""
203 # FairShip positions are in cm and the response-map coordinates are mm.
204 local_x_mm = 10.0 * (point.GetX() - tile_center.X())
205 local_y_mm = 10.0 * (point.GetY() - tile_center.Y())
206 response_map = self._adc_response_maps[tile_size]
207 # Clamp to the outermost bins so hits on a tile edge do not land in
208 # the under/overflow bins.
209 x_axis = response_map.GetXaxis()
210 y_axis = response_map.GetYaxis()
211 x_bin = min(max(x_axis.FindFixBin(local_x_mm), 1), x_axis.GetNbins())
212 y_bin = min(max(y_axis.FindFixBin(local_y_mm), 1), y_axis.GetNbins())
213 adc_per_mev = response_map.GetBinContent(x_bin, y_bin)
214 deposited_energy_mev = 1000.0 * point.GetEnergyLoss()
215 return deposited_energy_mev * adc_per_mev
216
217 def digitize(self) -> None:
218 """Digitize UBT MC points into one hit per fired constituent tile.
219
220 An MC point covers a (track, region) pair and a region holds 25 or 100
221 tiles, so a tile can collect points of several tracks, e.g. a muon and
222 a delta ray. Their ADC signals, each taken at its own position in the
223 tile, are summed before rounding and before the trigger threshold is
224 applied. The hit time is that of the first point in the tile.
225 """
226 tiles: dict[int, _FiredTile] = {} # by tile ID, in the order of their first point
227 for index, aMCPoint in enumerate(self.intree.UpstreamTaggerPoint):
228 tile_size = self._tile_sizes[aMCPoint.GetDetectorID()]
229 position = self.digitized_position(aMCPoint, tile_size)
230 tile_id = self.tile_id(position, tile_size)
231 tile = tiles.get(tile_id)
232 if tile is None:
233 tile = tiles[tile_id] = _FiredTile(aMCPoint, position)
234 elif aMCPoint.GetTime() < tile.first.GetTime():
235 tile.first = aMCPoint
236 tile.points.append(index)
237 tile.signals.append(self.adc_signal(aMCPoint, position, tile_size))
238
239 for tile_id, tile in tiles.items():
240 adc_counts = max(0, round(sum(tile.signals)))
241 aHit = ROOT.UpstreamTaggerHit(tile.first, self.intree.t0, tile.position, self._time_res)
242 aHit.SetTileID(tile_id)
243 aHit.SetADC(adc_counts)
244 aHit.SetTriggered(adc_counts >= self._trigger_threshold)
245 self.det.push_back(aHit)
246 if self.MCdet is not None:
247 self.MCdet.push_back(ROOT.std.vector("int")(tile.points))
248 if self.MCadc is not None:
249 self.MCadc.push_back(ROOT.std.vector("float")(tile.signals))
float _tile_center(float coordinate, float grid_origin, float grid_end, float tile_size, int tile_count)
None __init__(self, name, intree, outtree=None, mcBranchName=None)
float adc_signal(self, point, ROOT.TVector3 tile_center, float tile_size)
int tile_id(self, ROOT.TVector3 position, float tile_size)
ROOT.TVector3 digitized_position(self, point, float tile_size)
None validate_stored_geometry(cls, geo_manager, ubt_geo)
int _tile_count(float grid_origin, float grid_end, float tile_size)
dict[float, ROOT.TH2D] _load_adc_response_maps(str path, set[float] tile_sizes)