FairShip
Loading...
Searching...
No Matches
UpstreamTaggerDetector.UpstreamTaggerDetector Class Reference
Inheritance diagram for UpstreamTaggerDetector.UpstreamTaggerDetector:
[legend]
Collaboration diagram for UpstreamTaggerDetector.UpstreamTaggerDetector:
[legend]

Public Member Functions

None __init__ (self, name, intree, outtree=None, mcBranchName=None)
None validate_stored_geometry (cls, geo_manager, ubt_geo)
None delete (self)
ROOT.TVector3 digitized_position (self, point, float tile_size)
int tile_id (self, ROOT.TVector3 position, float tile_size)
float adc_signal (self, point, ROOT.TVector3 tile_center, float tile_size)
None digitize (self)
Public Member Functions inherited from BaseDetector.BaseDetector
None __init__ (self, name, intree, branchName=None, mcBranchType=None, mcBranchName=None, int splitLevel=99, outtree=None)
None fill (self)
None process (self)

Public Attributes

 MCadc = None
Public Attributes inherited from BaseDetector.BaseDetector
 name = name
 intree = intree
 outtree = outtree if outtree is not None else intree
 det = ROOT.std.vector(f"{name}Hit")()
 MCdet = None
 mcBranch = None
 branch = self.outtree.Branch(f"Digi_{branchName}Hits", self.det, 32000, splitLevel)

Static Public Attributes

str ASSEMBLY_VOLUME = "Upstream_Tagger"
 REGION_VOLUME_PATTERN = re.compile(r"UpstreamTaggerRegion\d*_(\d+)cm(?:_|$)")

Static Protected Member Functions

dict[float, ROOT.TH2D] _load_adc_response_maps (str path, set[float] tile_sizes)
int _tile_count (float grid_origin, float grid_end, float tile_size)
float _tile_center (float coordinate, float grid_origin, float grid_end, float tile_size, int tile_count)

Protected Attributes

dict _tile_sizes = {int(region): float(size) for region, size in ubt_geo.RegionTileSize.items()}
tuple _grid_x = (ubt_geo.TileGridOriginX, ubt_geo.TileGridEndX)
tuple _grid_y = (ubt_geo.TileGridOriginY, ubt_geo.TileGridEndY)
 _z = ubt_geo.z
 _time_res = ubt_geo.TimeResolution
 _trigger_threshold = ubt_geo.ADCTriggerThreshold
 _grid_size = min(self._tile_sizes.values())
 _columns = round((self._grid_x[1] - self._grid_x[0]) / self._grid_size)
 _rows = round((self._grid_y[1] - self._grid_y[0]) / self._grid_size)
dict _id_offsets = {}
dict _tile_counts
dict[float, ROOT.TH2D] _adc_response_maps

Detailed Description

Definition at line 28 of file UpstreamTaggerDetector.py.

Constructor & Destructor Documentation

◆ __init__()

None UpstreamTaggerDetector.UpstreamTaggerDetector.__init__ ( self,
name,
intree,
outtree = None,
mcBranchName = None )

Definition at line 36 of file UpstreamTaggerDetector.py.

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
82 self._adc_response_maps = self._load_adc_response_maps(
83 ubt_geo.ADCResponseMapFile, set(self._tile_sizes.values())
84 )
85

Member Function Documentation

◆ _load_adc_response_maps()

dict[float, ROOT.TH2D] UpstreamTaggerDetector.UpstreamTaggerDetector._load_adc_response_maps ( str path,
set[float] tile_sizes )
staticprotected
Load the ADC/MeV vs local position (mm) TH2D for each tile size (cm).

Definition at line 123 of file UpstreamTaggerDetector.py.

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

◆ _tile_center()

float UpstreamTaggerDetector.UpstreamTaggerDetector._tile_center ( float coordinate,
float grid_origin,
float grid_end,
float tile_size,
int tile_count )
staticprotected
Return the globally aligned tile center containing coordinate.

Definition at line 154 of file UpstreamTaggerDetector.py.

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

◆ _tile_count()

int UpstreamTaggerDetector.UpstreamTaggerDetector._tile_count ( float grid_origin,
float grid_end,
float tile_size )
staticprotected
Return the number of tiles of tile_size along a tile grid axis.

Definition at line 146 of file UpstreamTaggerDetector.py.

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

◆ adc_signal()

float UpstreamTaggerDetector.UpstreamTaggerDetector.adc_signal ( self,
point,
ROOT.TVector3 tile_center,
float tile_size )
Return the (unrounded) ADC signal of a point from its energy and position in the tile.

Definition at line 201 of file UpstreamTaggerDetector.py.

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

◆ delete()

None UpstreamTaggerDetector.UpstreamTaggerDetector.delete ( self)
Clear the hit, MC link and per-point ADC containers.

Reimplemented from BaseDetector.BaseDetector.

Definition at line 116 of file UpstreamTaggerDetector.py.

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

◆ digitize()

None UpstreamTaggerDetector.UpstreamTaggerDetector.digitize ( self)
Digitize UBT MC points into one hit per fired constituent tile.

An MC point covers a (track, region) pair and a region holds 25 or 100
tiles, so a tile can collect points of several tracks, e.g. a muon and
a delta ray. Their ADC signals, each taken at its own position in the
tile, are summed before rounding and before the trigger threshold is
applied. The hit time is that of the first point in the tile.

Reimplemented from BaseDetector.BaseDetector.

Definition at line 217 of file UpstreamTaggerDetector.py.

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))

◆ digitized_position()

ROOT.TVector3 UpstreamTaggerDetector.UpstreamTaggerDetector.digitized_position ( self,
point,
float tile_size )
Map an MC point to the center of its 2x2 or 4x4 cm2 tile.

Definition at line 165 of file UpstreamTaggerDetector.py.

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

◆ tile_id()

int UpstreamTaggerDetector.UpstreamTaggerDetector.tile_id ( self,
ROOT.TVector3 position,
float tile_size )
Return a stable unique ID for a constituent tile.

The tile is identified by its lower-left cell on the tile-ID grid, the
grid of the smallest tile side (2 cm) over the tile grid bounds, with
``columns`` x ``rows`` cells:

    tile ID = (tile side / grid size - 1) * columns * rows + row * columns + column

So each tile side has its own range of ``columns * rows`` IDs, and a
2 cm and a 4 cm tile with the same lower-left cell get different IDs.
For the default geometry (340 x 504 cm2, 170 x 252 cells), the range
of 2 cm tiles is [0, 42840) and that of 4 cm tiles [42840, 85680). The
stride follows the UBT box, so decoding an ID needs the grid of its
geometry:

    side_index, cell = divmod(tile_id, columns * rows)
    row, column = divmod(cell, columns)

Definition at line 172 of file UpstreamTaggerDetector.py.

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

◆ validate_stored_geometry()

None UpstreamTaggerDetector.UpstreamTaggerDetector.validate_stored_geometry ( cls,
geo_manager,
ubt_geo )
Raise UBTGeometryMismatch if the UBT points of this geometry cannot be digitized.

The decision is taken from the simulated geometry, not from the
configuration, which configure replaces for old geometry files. A
geometry without any UBT region predates the scintillator UBT: its UBT
was a vacuum box, whose detector IDs are not region IDs. Otherwise
every region of the UBT map must be placed, with the same tile size.

Definition at line 87 of file UpstreamTaggerDetector.py.

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:
106 raise UBTGeometryMismatch(
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:
112 raise UBTGeometryMismatch(
113 f"{len(differing)} UBT regions of the geometry differ from the UBT map, e.g. {differing[:5]}"
114 )
115

Member Data Documentation

◆ _adc_response_maps

dict[float, ROOT.TH2D] UpstreamTaggerDetector.UpstreamTaggerDetector._adc_response_maps
protected
Initial value:
= self._load_adc_response_maps(
ubt_geo.ADCResponseMapFile, set(self._tile_sizes.values())
)

Definition at line 82 of file UpstreamTaggerDetector.py.

◆ _columns

UpstreamTaggerDetector.UpstreamTaggerDetector._columns = round((self._grid_x[1] - self._grid_x[0]) / self._grid_size)
protected

Definition at line 65 of file UpstreamTaggerDetector.py.

◆ _grid_size

UpstreamTaggerDetector.UpstreamTaggerDetector._grid_size = min(self._tile_sizes.values())
protected

Definition at line 62 of file UpstreamTaggerDetector.py.

◆ _grid_x

tuple UpstreamTaggerDetector.UpstreamTaggerDetector._grid_x = (ubt_geo.TileGridOriginX, ubt_geo.TileGridEndX)
protected

Definition at line 54 of file UpstreamTaggerDetector.py.

◆ _grid_y

tuple UpstreamTaggerDetector.UpstreamTaggerDetector._grid_y = (ubt_geo.TileGridOriginY, ubt_geo.TileGridEndY)
protected

Definition at line 55 of file UpstreamTaggerDetector.py.

◆ _id_offsets

dict UpstreamTaggerDetector.UpstreamTaggerDetector._id_offsets = {}
protected

Definition at line 67 of file UpstreamTaggerDetector.py.

◆ _rows

UpstreamTaggerDetector.UpstreamTaggerDetector._rows = round((self._grid_y[1] - self._grid_y[0]) / self._grid_size)
protected

Definition at line 66 of file UpstreamTaggerDetector.py.

◆ _tile_counts

dict UpstreamTaggerDetector.UpstreamTaggerDetector._tile_counts
protected
Initial value:
= {
tile_size: (self._tile_count(*self._grid_x, tile_size), self._tile_count(*self._grid_y, tile_size))
for tile_size in set(self._tile_sizes.values())
}

Definition at line 77 of file UpstreamTaggerDetector.py.

◆ _tile_sizes

dict UpstreamTaggerDetector.UpstreamTaggerDetector._tile_sizes = {int(region): float(size) for region, size in ubt_geo.RegionTileSize.items()}
protected

Definition at line 53 of file UpstreamTaggerDetector.py.

◆ _time_res

UpstreamTaggerDetector.UpstreamTaggerDetector._time_res = ubt_geo.TimeResolution
protected

Definition at line 57 of file UpstreamTaggerDetector.py.

◆ _trigger_threshold

UpstreamTaggerDetector.UpstreamTaggerDetector._trigger_threshold = ubt_geo.ADCTriggerThreshold
protected

Definition at line 58 of file UpstreamTaggerDetector.py.

◆ _z

UpstreamTaggerDetector.UpstreamTaggerDetector._z = ubt_geo.z
protected

Definition at line 56 of file UpstreamTaggerDetector.py.

◆ ASSEMBLY_VOLUME

str UpstreamTaggerDetector.UpstreamTaggerDetector.ASSEMBLY_VOLUME = "Upstream_Tagger"
static

Definition at line 33 of file UpstreamTaggerDetector.py.

◆ MCadc

UpstreamTaggerDetector.UpstreamTaggerDetector.MCadc = None

Definition at line 43 of file UpstreamTaggerDetector.py.

◆ REGION_VOLUME_PATTERN

UpstreamTaggerDetector.UpstreamTaggerDetector.REGION_VOLUME_PATTERN = re.compile(r"UpstreamTaggerRegion\d*_(\d+)cm(?:_|$)")
static

Definition at line 34 of file UpstreamTaggerDetector.py.


The documentation for this class was generated from the following file: