FairShip
Loading...
Searching...
No Matches
SciFiMapping.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
4
5"""Mapping between detector modules and SciFi channels."""
6
7import argparse
8
9import matplotlib.patches as patches
10import matplotlib.pyplot as plt
11import numpy as np
12import ROOT
13import shipDet_conf
14from ShipGeoConfig import load_from_root_file
15
16
18 """Mapping between detector modules and SciFi channels."""
19
20 def __init__(self, modules) -> None:
21 """Initialize the SciFiMapping instance with geometry modules.
22
23 Parameters
24 ----------
25 modules : dict
26 Dictionary of detector geometry modules, must include key 'MTC'.
27
28 """
29 self.modules = modules
30 self.scifi = modules["MTC"]
31
32 def create_fibre_to_simp_map(self) -> None:
33 """Build mappings from optical fibres to SiPM channels for U and V planes.
34
35 Retrieves the U and V SiPM maps from the SciFi module and constructs
36 dictionaries mapping each fibre index to its associated SiPM channels,
37 including weight and x-position information.
38
39 For full details, see SND/MTC/MTCDetector.cxx in the SND framework.
40
41 Side Effects
42 ------------
43 Sets attributes 'fibre_to_simp_map_U' and 'fibre_to_simp_map_V'.
44 """
45 FU, FV = self.scifi.GetSiPMmapU(), self.scifi.GetSiPMmapV()
47 for x1, x2 in zip(FU, FV):
48 self.fibre_to_simp_map_U[x1.first] = {}
49 for z in x1.second:
50 self.fibre_to_simp_map_U[x1.first][z.first] = {
51 "weight": z.second[0],
52 "xpos": z.second[1],
53 }
54 self.fibre_to_simp_map_V[x2.first] = {}
55 for z in x2.second:
56 self.fibre_to_simp_map_V[x2.first][z.first] = {
57 "weight": z.second[0],
58 "xpos": z.second[1],
59 }
60
61 def create_sipm_to_fibre_map(self) -> None:
62 """Build mappings from SiPM channels to optical fibres for U and V planes.
63
64 Retrieves the U and V fibre maps from the SciFi module and constructs
65 dictionaries mapping each SiPM channel index to its associated fibres,
66 including weight and x-position information.
67
68 For full details, see SND/MTC/MTCDetector.cxx in the SND framework.
69
70 Side Effects
71 ------------
72 Sets attributes 'sipm_to_fibre_map_U' and 'sipm_to_fibre_map_V'.
73 """
74 XU, XV = self.scifi.GetFibresMapU(), self.scifi.GetFibresMapV()
76 for x1, x2 in zip(XU, XV):
77 self.sipm_to_fibre_map_U[x1.first] = {}
78 for z in x1.second:
79 self.sipm_to_fibre_map_U[x1.first][z.first] = {
80 "weight": z.second[0],
81 "xpos": z.second[1],
82 }
83 self.sipm_to_fibre_map_V[x2.first] = {}
84 for z in x2.second:
85 self.sipm_to_fibre_map_V[x2.first][z.first] = {
86 "weight": z.second[0],
87 "xpos": z.second[1],
88 }
89
90 def create_sipm_to_position_map(self) -> None:
91 """Create a mapping from SiPM channels to their positions in the SciFi detector.
92
93 This method retrieves the SiPM positions for both U and V planes and constructs
94 dictionaries mapping each SiPM channel index to its corresponding position.
95
96 Side Effects
97 ------------
98 Sets attributes 'sipm_pos_U' and 'sipm_pos_V'.
99 """
100 sipm_pos_U_raw = self.scifi.GetSiPMPos_U()
101 sipm_pos_V_raw = self.scifi.GetSiPMPos_V()
102 self.sipm_pos_U, self.sipm_pos_V = {}, {}
103
104 for pair in sipm_pos_U_raw:
105 self.sipm_pos_U[pair.first] = pair.second
106 for pair in sipm_pos_V_raw:
107 self.sipm_pos_V[pair.first] = pair.second
108
109 def make_mapping(self) -> None:
110 """Execute the full mapping sequence for the SciFi detector.
111
112 Calls internal methods to calculate SiPM overlap, perform the mapping
113 in the SciFi module, and build both fibre-to-SiPM and SiPM-to-fibre maps.
114
115 Currently is used in python/shipDigiReco.py.
116 """
117 self.scifi.SiPMOverlap()
118 self.scifi.SiPMmapping()
122
124 """Retrieve the SiPM-to-fibre mapping dictionaries.
125
126 Returns
127 -------
128 tuple of dict
129 (sipm_to_fibre_map_U, sipm_to_fibre_map_V)
130
131 """
133
135 """Retrieve the fibre-to-SiPM mapping dictionaries.
136
137 Returns
138 -------
139 tuple of dict
140 (fibre_to_simp_map_U, fibre_to_simp_map_V)
141
142 """
144
145 def draw_channel(self, sGeo, channel: int) -> None:
146 """Draw a single channel mapping showing fibre positions and the SiPM sensor.
147
148 Parameters
149 ----------
150 sGeo: ROOT.TGeoManager
151 The geometry manager for the detector setup.
152 channel : int
153 Global channel identifier encoding plane type, SiPM unit, and channel index.
154
155 Side Effects
156 ------------
157 Saves a PDF file named 'scifi_mapping_channel_1_{channel}.pdf' with the plot.
158
159 """
160 AF = ROOT.TVector3()
161 BF = ROOT.TVector3()
162 plane_type = int(channel / 1e5) % 10
163 locChannel = channel % 1000000
164 fibreVol = sGeo.FindVolumeFast("FiberVol")
165 R = fibreVol.GetShape().GetDX()
166 DX = 0.025
167 DZ = 0.135
168 xmin = 999.0
169 xmax = -999.0
170 ymin = 999.0
171 ymax = -999.0
172 fibre_positions = []
173 fibresSiPM = self.fibre_to_simp_map_U if plane_type == 0 else self.fibre_to_simp_map_V
174 if not fibresSiPM[locChannel]:
175 return
176 globfiberID = 0
177 for fibre in fibresSiPM[locChannel]:
178 globfiberID = (
179 fibre + 100000000 + 1000000 + 0 * 100000
180 if plane_type == 0
181 else fibre + 100000000 + 1000000 + 1 * 100000
182 )
183 self.scifi.GetPosition(globfiberID, AF, BF)
184 loc = self.scifi.GetLocalPos(globfiberID, BF)
185 print(f"Position for fibre {globfiberID} A: {BF.X()}, {BF.Y()}, {BF.Z()}")
186 fibre_positions.append((loc[0], loc[2]))
187 if xmin > loc[0]:
188 xmin = loc[0]
189 if ymin > loc[2]:
190 ymin = loc[2]
191 if xmax < loc[0]:
192 xmax = loc[0]
193 if ymax < loc[2]:
194 ymax = loc[2]
195 D = ymax - ymin + 3 * R
196 x0 = (xmax + xmin) / 2.0
197 _fig, ax = plt.subplots(figsize=(8, 8))
198 ax.set_xlim(x0 - D / 2, x0 + D / 2)
199 ax.set_ylim(ymin - 1.5 * R, ymax + 1.5 * R)
200 for i, (x, y) in enumerate(fibre_positions):
201 ellipse = patches.Ellipse((x, y), width=2 * R, height=2 * R, color="orange", alpha=0.6)
202 ax.add_patch(ellipse)
203 self.scifi.GetSiPMPosition(locChannel, AF, BF)
204 loc = self.scifi.GetLocalPos(globfiberID, BF)
205 print(f"SiPM position for channel {channel}: {loc[0]}, {loc[1]}, {loc[2]}")
206 rect = patches.Rectangle(
207 (loc[0] - DX, loc[2] - DZ),
208 2 * DX,
209 2 * DZ,
210 linewidth=1,
211 edgecolor="blue",
212 facecolor="blue",
213 alpha=0.3,
214 hatch="//",
215 )
216 ax.add_patch(rect)
217 ax.set_xlabel("X [cm]")
218 ax.set_ylabel("Z [cm]")
219 ax.set_title(f"SiPM Mapping for Channel {channel}")
220 ax.grid(True)
221 ax.set_aspect("equal")
222 plt.savefig(f"scifi_mapping_channel_1_{channel}.pdf")
223
225 self,
226 sGeo,
227 number_of_channels=20,
228 output_file="scifi_mapping_many_channels.pdf",
229 labeling=True,
230 figsize=(16, 16),
231 dpi=300,
232 cmap_name="tab20",
233 alpha_fibre=0.4,
234 ) -> None:
235 """Draw overlay plot of multiple channel mappings on a single figure.
236
237 Parameters
238 ----------
239 number_of_channels : int, optional
240 Total number of channels to display (split evenly between U and V planes).
241 Default is 20.
242 sGeo : ROOT.TGeoManager
243 The geometry manager for the detector setup.
244 output_file : str, optional
245 Filename for the saved PDF plot. Default: 'scifi_mapping_all_channels.pdf'.
246 labeling : bool, optional
247 If True, annotate each SiPM rectangle with channel information.
248 Default is True.
249 figsize : tuple of float, optional
250 Figure size in inches. Default is (16, 16).
251 dpi : int, optional
252 Resolution of the figure in dots per inch. Default is 300.
253 cmap_name : str, optional
254 Matplotlib colormap name for differentiating channels. Default is 'tab20'.
255 alpha_fibre : float, optional
256 Transparency for fibre ellipses. Default is 0.4.
257
258 Side Effects
259 ------------
260 Saves an overlay PDF plot with the specified filename.
261
262 """
263 # Prepare fig & ax
264 fig, ax = plt.subplots(figsize=figsize, dpi=dpi)
265
266 # Geometry constants
267 fibreVol = sGeo.FindVolumeFast("FiberVol")
268 R = fibreVol.GetShape().GetDX()
269 DX, DZ = 0.025, 0.135 / 2
270
271 # Select your channels. Hardcoded range for demonstration
272 # channelsU = sorted(self.fibre_to_simp_map_U.keys())[:10]
273 # channelsV = sorted(self.fibre_to_simp_map_V.keys())[::-1][86:96]
274
275 # Find SiPM channel in the center of the U and V planes
276 center_channel_U = [chan for chan, x_pos in self.sipm_pos_U.items() if abs(x_pos) <= DX - 0.001][0]
277 center_channel_V = [chan for chan, x_pos in self.sipm_pos_V.items() if abs(x_pos) <= DX - 0.001][0]
278
279 def get_surrounding_keys(d: dict, target_key, N: int):
280 """Return neighbors of `target_key` in value-sorted order.
281
282 Given a dict `d`, find `target_key` in the ordering of keys sorted by
283 their values, and return up to N//2 keys that come before it and N//2 keys
284 that come after it (excluding the target_key itself).
285
286 Parameters
287 ----------
288 d : dict
289 Mapping from keys to comparable values.
290 target_key : hashable
291 The key around which to collect neighbors.
292 N : int
293 Total number of neighbors to return (N//2 before, N//2 after).
294
295 Returns
296 -------
297 list
298 List of up to N keys: first the keys before, then the keys after.
299
300 """
301 # 1) sort keys by their associated values
302 sorted_keys = sorted(d.keys(), key=lambda k: d[k])
303 # 2) locate the target
304 try:
305 idx = sorted_keys.index(target_key)
306 except ValueError:
307 raise KeyError(f"Target key {target_key!r} not found in dictionary") from None
308
309 half = N // 2
310 # 3) slice out the neighbors
311 start = max(0, idx - half)
312 end_before = idx
313 start_after = idx + 1
314 end_after = idx + 1 + half
315
316 before = sorted_keys[start:end_before]
317 after = sorted_keys[start_after:end_after]
318
319 return before + [target_key] + after
320
321 channelsU = get_surrounding_keys(self.sipm_pos_U, center_channel_U, number_of_channels)
322 channelsV = get_surrounding_keys(self.sipm_pos_V, center_channel_V, number_of_channels)
323
324 channels = channelsU + channelsV
325 n_chan = len(channels)
326
327 AF = ROOT.TVector3()
328 BF = ROOT.TVector3()
329
330 # Loop through all channels
331 for chan in channels:
332 isU = chan in channelsU
333 # decode local channel
334 locChan = chan % 1_000_000
335
336 # collect fibre positions
337 xs, ys = [], []
338 for fibreID in (self.fibre_to_simp_map_U if chan in channelsU else self.fibre_to_simp_map_V)[locChan]:
339 globfiberID = (
340 fibreID + 100000000 + 1000000 + 0 * 100000
341 if chan in channelsU
342 else fibreID + 100000000 + 1000000 + 1 * 100000
343 )
344 self.scifi.GetPosition(globfiberID, AF, BF)
345 loc = self.scifi.GetLocalPos(globfiberID, BF)
346 xs.append(loc[0])
347 ys.append(loc[2])
348
349 # draw fibres (still orange)
350 for x, y in zip(xs, ys):
351 ell = patches.Ellipse(
352 (x, y),
353 2 * R,
354 2 * R,
355 fill=False,
356 edgecolor="black",
357 linewidth=1,
358 alpha=alpha_fibre,
359 )
360 ax.add_patch(ell)
361
362 # draw SiPM rect in its unique shade
363 self.scifi.GetSiPMPosition(chan, BF, AF)
364 # GetLocalPos needs the global detector id (station/plane encoded);
365 # build it from the channel so it does not depend on the (now stale)
366 # fibre loop variable, which is also unbound if the fibre list is empty.
367 globSiPMID = locChan + 100000000 + 1000000 + (0 if isU else 1) * 100000
368 loc_siPM = self.scifi.GetLocalPos(globSiPMID, BF)
369 rx, ry = loc_siPM[0], loc_siPM[2]
370 rect = patches.Rectangle(
371 (rx - DX, ry - DZ),
372 2 * DX,
373 2 * DZ,
374 linewidth=1,
375 edgecolor="black",
376 facecolor="blue" if isU else "red", # override with solid colors for clarity,
377 alpha=alpha_fibre * 0.8,
378 hatch="//" if isU else "\\\\",
379 )
380 ax.add_patch(rect)
381
382 if labeling:
383 # compute a fontsize that fits the rect width
384 # 1) data→display coords:
385 p0 = ax.transData.transform((rx - DX, ry))
386 p1 = ax.transData.transform((rx + DX, ry))
387 disp_width = abs(p1[0] - p0[0])
388 # 2) convert px→points (1pt = 1/72in; fig.dpi px/inch):
389 pts = disp_width * 72.0 / fig.dpi
390 fontsize = max(2, min(12, pts * 0.8))
391
392 # label above the rect
393 text = f"SiPM: {(chan // 1000) % 10} \n ch: {chan % 1000}"
394 ax.text(
395 rx - DX / 2,
396 ry + DZ + R * 0.1,
397 text,
398 ha="left",
399 va="bottom",
400 fontsize=fontsize,
401 color="black",
402 clip_on=True,
403 )
404
405 # finalize plot
406 ax.relim()
407 ax.autoscale_view()
408 ax.set_aspect("equal")
409 ax.tick_params(axis="both", which="major", labelsize=18)
410 ax.tick_params(axis="both", which="minor", labelsize=18)
411 ax.set_xlabel("X [cm]", fontsize=20)
412 ax.set_ylabel("Z [cm]", fontsize=20)
413 ax.set_title("SiPM-Channel Mappings Overlaid", fontsize=24)
414 ax.grid(True)
415
416 plt.tight_layout()
417 plt.savefig(output_file)
418 plt.close(fig)
419 print(f"Saved overlay plot of {n_chan} channels to {output_file}")
420
422 self,
423 number_of_channels: int = 20,
424 real_event: bool = False,
425 x_coords: list[float] | None = None,
426 output_file: str = "scifi_channel_ribbons_XY.pdf",
427 figsize: tuple[int, int] = (16, 16),
428 dpi: int = 300,
429 ) -> None:
430 """Plot SciFi channel ribbons and SiPM boxes in X–Y view.
431
432 Simplified X–Y view: one ribbon per channel (no per-fiber loops).
433 Ribbons span Y from -25 to +25 (length=50 cm), thickness equal
434 to channel height = 2*DZ, tilted +5° for U-plane channels, -5° for
435 V-plane. SiPM boxes sit on top at y=25→25+2*DZ.
436
437 Parameters
438 ----------
439 number_of_channels : int
440 Total ribbons (split around center) per plane.
441 real_event : bool
442 If True, highlight ribbons corresponding to given x_coords.
443 x_coords : list of float
444 If real_event is True, list of two x-coordinates [x_U, x_V] to highlight.
445 output_file : str
446 Path to save the PDF.
447 figsize : tuple of float
448 Figure size in inches.
449 dpi : int
450 Figure resolution in dots per inch.
451 Side Effects
452 ------------
453 Saves a PDF file with the specified filename containing the plot.
454
455 """
456 # 2) Geometry constants
457 DZ = 0.135 / 2 # SiPM half-height [cm]
458 DX = 0.025 # SiPM half-width [cm]
459 L = 50.0 # ribbon length (full Y-span) [cm]
460 angle_U = -5.0 # tilt for U
461 angle_V = +5.0 # tilt for V
462
463 # These are only used in the real_event branch; bound to 0 here so static
464 # analysis sees them defined on the not-real_event branch too.
465 channels_x_U = 0
466 channels_x_V = 0
467 channel_x_U = 0
468 channel_x_V = 0
469 if not real_event:
470 alpha_sipm, alpha_fibre = 0.75, 0.5
471 else:
472 alpha_sipm, alpha_fibre = 0.1, 0.1
473 if x_coords is None or len(x_coords) < 2:
474 raise ValueError("x_coords must provide at least two coordinates when real_event is True")
475 # find the channels corresponding to x_coords
476 matches_U = [c for c, x in self.sipm_pos_U.items() if abs(x - x_coords[0]) < DX]
477 matches_V = [c for c, x in self.sipm_pos_V.items() if abs(x - x_coords[1]) < DX]
478 if not matches_U or not matches_V:
479 raise ValueError(f"x_coords {x_coords} do not match any SciFi channel within {DX} cm")
480 channels_x_U = channel_x_U = matches_U[0]
481 channels_x_V = channel_x_V = matches_V[0]
482 # 1) Figure setup
483 fig, ax = plt.subplots(figsize=figsize, dpi=dpi)
484
485 # get center channels + neighbors
486 centerU = next(c for c, x in self.sipm_pos_U.items() if abs(x) < DX)
487 centerV = next(c for c, x in self.sipm_pos_V.items() if abs(x) < DX)
488
489 def get_surrounding(d, target, N):
490 keys = sorted(d.keys(), key=lambda k: d[k])
491 i = keys.index(target)
492 half = N // 2
493 start = max(0, i - half)
494 end = min(len(keys), i + half + 1)
495 return keys[start:end]
496
497 if not real_event:
498 chansU = get_surrounding(self.sipm_pos_U, centerU, number_of_channels)
499 chansV = get_surrounding(self.sipm_pos_V, centerV, number_of_channels)
500 else:
501 chansU = get_surrounding(self.sipm_pos_U, channels_x_U, number_of_channels)
502 chansV = get_surrounding(self.sipm_pos_V, channels_x_V, number_of_channels)
503 all_chans = chansU + chansV
504
505 # cmap_U = plt.get_cmap('tab20')
506 # cmap_V = plt.get_cmap('tab20b')
507 # colorsU = [cmap_U(i/(len(chansU)-1)) for i in range(len(chansU))]
508 # colorsV = [cmap_V(i/(len(chansV)-1)) for i in range(len(chansV))]
509 # alpha (tilt of the last drawn ribbon, used below to shift xlim)
510 # initialised here so static analysis sees it defined even if the loop
511 # doesn't iterate; both U and V have the same |alpha|.
512 alpha = np.deg2rad(angle_U)
513 # 3) Draw ribbons and SiPM boxes per channel
514 for chan in all_chans:
515 isU = chan in chansU
516 x0 = self.sipm_pos_U[chan] if isU else self.sipm_pos_V[chan]
517 angle = angle_U if isU else angle_V
518
519 alpha = np.deg2rad(angle) # e.g. angle_deg = +5 or -5
520 dx = DX
521 dy = L / 2
522 shift = dy * np.tan(alpha) # horizontal shear of bottom edge
523 # define the four corners in XY
524 coords = [
525 (x0 - dx, +dy), # top-left
526 (x0 + dx, +dy), # top-right
527 (x0 + dx - shift, -dy), # bottom-right
528 (x0 - dx - shift, -dy), # bottom-left
529 ]
530
531 # col = colorsU[k_U] if isU else colorsV[k_V]
532 col = "blue" if isU else "red" # override with solid colors for clarity
533 if not real_event:
534 ribbon = patches.Polygon(
535 coords,
536 closed=True,
537 facecolor=col, # fill in your color
538 edgecolor="black",
539 alpha=alpha_fibre, # semi-transparent
540 )
541 ax.add_patch(ribbon)
542
543 y_top = L / 2 if isU else L / 2 + DZ
544
545 box = patches.Rectangle(
546 (x0 - DX, y_top),
547 2 * DX,
548 DZ,
549 facecolor=col, # same fill color
550 edgecolor="black",
551 alpha=alpha_sipm, # a bit more opaque
552 hatch="//" if isU else "\\\\",
553 )
554 ax.add_patch(box)
555 else:
556 if channel_x_U == chan or channel_x_V == chan:
557 # draw the ribbon
558 ribbon = patches.Polygon(
559 coords,
560 closed=True,
561 facecolor=col, # fill in your color
562 edgecolor="black",
563 alpha=0.50, # semi-transparent
564 )
565 ax.add_patch(ribbon)
566
567 y_top = L / 2 if isU else L / 2 + DZ
568
569 box = patches.Rectangle(
570 (x0 - DX, y_top),
571 2 * DX,
572 DZ,
573 facecolor=col, # same fill color
574 edgecolor="black",
575 alpha=0.75, # a bit more opaque
576 hatch="//" if isU else "\\\\",
577 )
578 ax.add_patch(box)
579 else:
580 ribbon = patches.Polygon(
581 coords,
582 closed=True,
583 facecolor=col, # fill in your color
584 edgecolor="black",
585 alpha=alpha_fibre, # semi-transparent
586 )
587 ax.add_patch(ribbon)
588
589 y_top = L / 2 if isU else L / 2 + DZ
590
591 box = patches.Rectangle(
592 (x0 - DX, y_top),
593 2 * DX,
594 DZ,
595 facecolor=col, # same fill color
596 edgecolor="black",
597 alpha=alpha_sipm, # a bit more opaque
598 hatch="//" if isU else "\\\\",
599 )
600 ax.add_patch(box)
601
602 # 4) Finalize plot
603 ax.set_aspect("equal")
604 if not real_event:
605 shift = 3 * np.tan(alpha)
606 min_x = min([self.sipm_pos_U[chan] for chan in chansU]) - shift
607 max_x = max(self.sipm_pos_V[chan] for chan in chansV) + shift
608 ax.set_xlim(min_x, max_x)
609 ax.set_ylim(22, 26)
610 else:
611 min_x, max_x = -25, 25
612 ax.set_ylim(-25, 26)
613 ax.set_xlim(min_x, max_x)
614 # ax.set_ylim(22, 26)
615 ax.set_xlabel("X [cm]")
616 ax.set_ylabel("Y [cm]")
617 ax.set_title("SciFi channel ribbons & SiPM boxes (X–Y view)")
618 ax.grid(True)
619 # create legend handles
620 legend_handles = [
621 patches.Patch(
622 facecolor="blue",
623 edgecolor="black",
624 hatch="//",
625 label="U plane",
626 alpha=0.75,
627 ),
628 patches.Patch(
629 facecolor="red",
630 edgecolor="black",
631 hatch="\\\\",
632 label="V plane",
633 alpha=0.75,
634 ),
635 ]
636
637 ax.legend(handles=legend_handles, title="Plane", loc="upper right")
638 plt.tight_layout()
639 plt.savefig(output_file)
640 plt.close(fig)
641 print(f"Saved channel ribbons + SiPM boxes to {output_file}")
642
644 self,
645 sGeo,
646 number_of_channels=20,
647 output_file="scifi_combined_views.pdf",
648 figsize=(18, 8),
649 dpi=300,
650 alpha_fibre=0.4,
651 ) -> None:
652 """Draw combined Z–X and X–Y views of SciFi channel mappings side by side.
653
654 Parameters
655 ----------
656 sGeo : ROOT.TGeoManager
657 The geometry manager for the detector setup.
658 number_of_channels : int, optional
659 Total number of channels to display (split evenly between U and V planes).
660 Default is 20.
661 output_file : str, optional
662 Filename for the saved PDF plot. Default: 'scifi_combined_views.pdf'.
663 figsize : tuple of float, optional
664 Figure size in inches. Default is (18, 8).
665 dpi : int, optional
666 Resolution of the figure in dots per inch. Default is 300.
667 alpha_fibre : float, optional
668 Transparency for fibre ellipses. Default is 0.4.
669 Side Effects
670 ------------
671 Saves a PDF file with the specified filename containing the combined views.
672
673 """
674 # Prepare fig & axes
675
676 fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize, dpi=dpi)
677
678 fibreVol = sGeo.FindVolumeFast("FiberVol")
679 R = fibreVol.GetShape().GetDX()
680 DX, DZ = 0.025, 0.135 / 2
681
682 center_U = [chan for chan, x in self.sipm_pos_U.items() if abs(x) <= DX - 0.001][0]
683 center_V = [chan for chan, x in self.sipm_pos_V.items() if abs(x) <= DX - 0.001][0]
684
685 def get_keys(d, target, N):
686 ks = sorted(d, key=lambda k: d[k])
687 i = ks.index(target)
688 half = N // 2
689 start = max(0, i - half)
690 end = min(len(ks), i + half + 1)
691 return ks[start:end]
692
693 chansU = get_keys(self.sipm_pos_U, center_U, number_of_channels)
694 chansV = get_keys(self.sipm_pos_V, center_V, number_of_channels)
695 channels = chansU + chansV
696 n_chan = len(channels)
697 cmap = plt.get_cmap("tab20")
698 colors = [cmap(i / (n_chan - 1)) for i in range(n_chan)]
699
700 AF = ROOT.TVector3()
701 BF = ROOT.TVector3()
702 for idx, chan in enumerate(channels):
703 col = colors[idx]
704 locChan = chan % 1000000
705 fmap = self.fibre_to_simp_map_U if chan in chansU else self.fibre_to_simp_map_V
706 xs, zs = [], []
707 for fid in fmap[locChan]:
708 gid = fid + int(1e8 + 1e6 + (0 if chan in chansU else 1) * 1e5)
709 self.scifi.GetPosition(gid, AF, BF)
710 loc = self.scifi.GetLocalPos(gid, BF)
711 xs.append(loc[0])
712 zs.append(loc[2])
713 for x, z in zip(xs, zs):
714 ell = patches.Ellipse((x, z), 2 * R, 2 * R, color="orange", alpha=alpha_fibre)
715 ax1.add_patch(ell)
716 self.scifi.GetSiPMPosition(chan, BF, AF)
717 # Build the global detector id from the channel so it does not depend
718 # on the (now stale) fibre loop variable, which is also unbound if the
719 # fibre list is empty.
720 gidSiPM = locChan + int(1e8 + 1e6 + (0 if chan in chansU else 1) * 1e5)
721 loc = self.scifi.GetLocalPos(gidSiPM, BF)
722 rx, rz = loc[0], loc[2]
723 rect = patches.Rectangle(
724 (rx - DX, rz - DZ),
725 2 * DX,
726 2 * DZ,
727 linewidth=1,
728 edgecolor="black",
729 facecolor=col,
730 alpha=alpha_fibre * 0.8,
731 )
732 ax1.add_patch(rect)
733
734 ax1.set_xlabel("X [cm]")
735 ax1.set_ylabel("Z [cm]")
736 ax1.set_aspect("equal")
737 ax1.grid(True)
738 ax1.set_title("Z–X: SciFi mappings")
739
740 DZ = 0.135 / 2
741 DX = 0.025
742 L = 50.0
743 angleU = 5.0
744 angleV = -5.0
745 centerU = [c for c, x in self.sipm_pos_U.items() if abs(x) < DX][0]
746 centerV = [c for c, x in self.sipm_pos_V.items() if abs(x) < DX][0]
747 chansU = get_keys(self.sipm_pos_U, centerU, number_of_channels)
748 chansV = get_keys(self.sipm_pos_V, centerV, number_of_channels)
749 all_ch = chansU + chansV
750 colorsU = [plt.get_cmap("Blues")(i / max(len(chansU) - 1, 1)) for i in range(len(chansU))]
751 colorsV = [plt.get_cmap("Reds")(i / max(len(chansV) - 1, 1)) for i in range(len(chansV))]
752
753 for chan in all_ch:
754 isU = chan in chansU
755 x0 = self.sipm_pos_U[chan] if isU else self.sipm_pos_V[chan]
756 angle = angleU if isU else angleV
757 alpha_rad = np.deg2rad(angle)
758 dy = L / 2
759 dx = DX
760 shift = dy * np.tan(alpha_rad)
761 coords = [
762 (x0 - dx, dy),
763 (x0 + dx, dy),
764 (x0 + dx - shift, -dy),
765 (x0 - dx - shift, -dy),
766 ]
767 col = colorsU[chansU.index(chan)] if isU else colorsV[chansV.index(chan)]
768 poly = patches.Polygon(coords, closed=True, facecolor=col, edgecolor="black", alpha=0.5)
769 ax2.add_patch(poly)
770 y_top = dy
771 box = patches.Rectangle(
772 (x0 - DX, y_top),
773 2 * DX,
774 2 * DZ,
775 facecolor=col,
776 edgecolor="black",
777 alpha=0.75,
778 )
779 ax2.add_patch(box)
780
781 ax2.set_xlabel("X [cm]")
782 ax2.set_ylabel("Y [cm]")
783 ax2.set_aspect("equal")
784 ax2.grid(True)
785 ax2.set_title("X–Y: Channel ribbons")
786
787 legend_handles = [
788 patches.Patch(
789 facecolor="blue",
790 edgecolor="black",
791 hatch="//",
792 label="U plane",
793 alpha=0.75,
794 ),
795 patches.Patch(
796 facecolor="red",
797 edgecolor="black",
798 hatch="\\",
799 label="V plane",
800 alpha=0.75,
801 ),
802 ]
803 ax2.legend(handles=legend_handles, title="Plane", loc="upper right")
804
805 plt.tight_layout()
806 plt.savefig(output_file)
807 plt.close(fig)
808
809 def mapping_validation(self) -> None:
810 """Validate and print the SiPM-to-fibre and fibre-to-SiPM mappings.
811
812 Prints out the mappings for the U plane, showing fibre indices,
813 SiPM channels, weights, and x-positions for both mapping directions.
814
815 """
816 sipm_to_fiber_map_U, _ = self.get_sipm_to_fibre_map()
817 fiber_to_sipm_map_U, _ = self.get_fibre_to_simp_map()
818
819 print("Validating U plane mapping:")
820 for sipm_chan, fibers in sipm_to_fiber_map_U.items():
821 for fiber_id, chan_info in fibers.items():
822 weight = chan_info["weight"]
823 xpos = chan_info["xpos"]
824 print(
825 f"""---- SiPM Channel: {sipm_chan}, Fiber index: {fiber_id},
826 Weight: {weight}, X Position: {xpos}"""
827 )
828 for fiber_id, sipm_fibers in fiber_to_sipm_map_U.items():
829 for sipm_chan, fiber_info in sipm_fibers.items():
830 weight = fiber_info["weight"]
831 xpos = fiber_info["xpos"]
832 print(
833 f"""++++ Fiber index: {fiber_id}, SiPM Channel: {sipm_chan},
834 Weight: {weight}, X Position: {xpos}"""
835 )
836
837
838if __name__ == "__main__":
839 parser = argparse.ArgumentParser(description="SciFiMapping visualization tool")
840 parser.add_argument(
841 "-g",
842 dest="geoFile",
843 type=str,
844 default="geofile_full.conical.PG_13-TGeant4.root",
845 help="Path to the geometry ROOT file",
846 )
847 parser.add_argument(
848 "--mode",
849 dest="mode",
850 type=str,
851 default="draw_many_channels",
852 help="Operation mode",
853 choices=[
854 "draw_channel",
855 "draw_many_channels",
856 "draw_channel_XY",
857 "draw_combined_scifi_views",
858 "validation",
859 ],
860 )
861 args = parser.parse_args()
862 geoFile = args.geoFile
863 fgeo = ROOT.TFile.Open(geoFile)
864 ship_geo = load_from_root_file(fgeo, "ShipGeo")
865
866 # -----Create geometry----------------------------------------------
867
868 run = ROOT.FairRunSim()
869 run.SetName("TGeant4") # Transport engine
870 import tempfile
871
872 sink = ROOT.FairRootFileSink(tempfile.mktemp(suffix=".root"))
873 run.SetSink(sink)
874 ROOT.SetOwnership(sink, False) # C++ FairRun takes ownership
875 run.SetUserConfig("g4Config_basic.C") # geant4 transport not used
876 rtdb = run.GetRuntimeDb()
877 modules = shipDet_conf.configure(run, ship_geo)
878 run.Init()
879 print("configured geofile")
880 sGeo = fgeo.FAIRGeom
881 top = sGeo.GetTopVolume()
882 # -----Create SciFiMapping instance--------------------------------
883 mapping = SciFiMapping(modules)
884 mapping.make_mapping()
885
886 if args.mode == "draw_channel":
887 test_channel = 1000000 # Example channel
888 mapping.draw_channel(sGeo, test_channel)
889 elif args.mode == "draw_many_channels":
890 mapping.draw_many_channels(sGeo, number_of_channels=20)
891 elif args.mode == "draw_channel_XY":
892 mapping.draw_channel_XY(number_of_channels=20, real_event=False)
893 elif args.mode == "draw_combined_scifi_views":
894 mapping.draw_combined_scifi_views(sGeo, number_of_channels=20)
895 elif args.mode == "validation":
896 mapping.mapping_validation()
897 else:
898 print(f"Unknown mode: {args.mode}")
None create_sipm_to_fibre_map(self)
None draw_many_channels(self, sGeo, number_of_channels=20, output_file="scifi_mapping_many_channels.pdf", labeling=True, figsize=(16, 16), dpi=300, cmap_name="tab20", alpha_fibre=0.4)
None draw_channel_XY(self, int number_of_channels=20, bool real_event=False, list[float]|None x_coords=None, str output_file="scifi_channel_ribbons_XY.pdf", tuple[int, int] figsize=(16, 16), int dpi=300)
None create_sipm_to_position_map(self)
None draw_combined_scifi_views(self, sGeo, number_of_channels=20, output_file="scifi_combined_views.pdf", figsize=(18, 8), dpi=300, alpha_fibre=0.4)
None draw_channel(self, sGeo, int channel)
None __init__(self, modules)
None create_fibre_to_simp_map(self)
configure(run, ship_geo, str|None geofile=None)