Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-17 09:29:51

0001 #!/usr/bin/env python3
0002 # SPDX-License-Identifier: LGPL-3.0-or-later
0003 # Copyright (C) 2026 Sylvester Joosten
0004 '''
0005     3D render (orthographic z-buffer) of a few BIC imaging layers from the loaded DD4hep/TGeo geometry.
0006     Walks the TGeo nodes of a sector volume, clips them to a window along the beam (y) and radially (z,
0007     sector frame), skips the outer carbon plates and the ScFi/Pb volumes (--skip, a safety net when a sector holding them is selected), and draws every leaf box/trd/trap
0008     as shaded faces: stave tops in the stave tier colour (blue even stave id, orange odd), red Si, yellow
0009     Kapton, orange Cu underneath, dark grey carbon plates and side walls.
0010 
0011     The staves sit in the two trays of each layer; the tier follows the stave id, so the rotated +z tray
0012     is coloured correctly (the default +-3 cm window straddles the junction of the two trays).
0013 
0014     use case (layers 2 and 3 of sector26, +-3 cm along the beam, radial direction up):
0015     python scripts/subdetector_tests/bic/render_bic_imaging_3d.py -c epic_craterlake_bic_6layers.xml \
0016         -o render3d_layers2-3.png --sector sector26 --y-range -3 3 --view 24 62 --z-range 86.7 92.65 \
0017         --title 'BIC imaging layers 2 (bottom) and 3 (top), radial direction up; outer carbon plates and ScFi/Pb hidden'
0018 '''
0019 import argparse
0020 import array
0021 import os
0022 import re
0023 
0024 import ROOT
0025 import dd4hep
0026 import matplotlib
0027 matplotlib.use('Agg')
0028 import matplotlib.pyplot as plt
0029 from matplotlib.patches import Patch
0030 import numpy as np
0031 
0032 ROOT.gROOT.SetBatch(True)
0033 
0034 # volume-name prefixes defined by src/BarrelCalorimeterImaging_geo.cpp
0035 LAYER = 'layer'
0036 TRAY = 'tray'    # trays (tray0 at -z, tray1 at +z), layer daughters holding the staves
0037 STAVE = 'stave'  # staves (stave<id>) in a tray; older geometry: staves directly in the layer
0038 OUTER_PLATE = 'frame_outer'
0039 
0040 SS = 3  # supersampling
0041 COLS = {'Silicon': '#c0392b', 'CarbonFiber': '#555555', 'Copper': '#e67e22', 'Kapton': '#f1c40f', 'Epoxy': '#27ae60'}
0042 TIER = ('#2166ac', '#e08214')  # even stave id: low rail, odd: high rail (as in draw_bic_imaging_sector.py)
0043 FACES = [[0, 1, 2, 3], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]
0044 
0045 
0046 def shape_pts(shape):
0047     a = array.array('d', [0.] * 24)
0048     shape.SetPoints(a)
0049     return np.array(a).reshape(8, 3)
0050 
0051 
0052 def to_master(mats, p):
0053     for mm in reversed(mats):
0054         b = array.array('d', [0.] * 3)
0055         mm.LocalToMaster(array.array('d', p), b)
0056         p = b
0057     return np.array(p)
0058 
0059 
0060 def collect(vol, args, skip):
0061     '''leaf box/trd/trap volumes in the window, as (8 corner points, colour) pairs'''
0062     ylo, yhi = args.y_range
0063     zlo, zhi = args.z_range
0064     polys, fc, count = [], [], {}
0065     tier = [0]
0066     positions = {}
0067 
0068     def walk(v, mats, depth, in_stave=False):
0069         for i in range(v.GetNdaughters()):
0070             n = v.GetNode(i)
0071             name = n.GetName()
0072             dv = n.GetVolume()
0073             mat = dv.GetMaterial().GetName()
0074             # rail tier = parity of the stave id (stave<id> in a tray); older geometry with the stave
0075             # pieces directly in the layer: order of first appearance of the layer-local (x, z);
0076             # done before filtering so --skip does not shift rail parity
0077             if depth == 0 and name.startswith(LAYER):
0078                 positions.clear()
0079             if name.startswith(STAVE):
0080                 sid = re.fullmatch(STAVE + r'(\d+)', name)
0081                 if sid:
0082                     tier[0] = int(sid.group(1)) % 2  # even: low rail
0083                 else:
0084                     t = n.GetMatrix().GetTranslation()
0085                     tier[0] = positions.setdefault((round(t[0], 4), round(t[2], 4)), len(positions)) % 2
0086             if skip.search(name) or skip.search(mat) or name.startswith(OUTER_PLATE):
0087                 continue
0088             m = mats + [n.GetMatrix()]
0089             o = to_master(m, [0., 0., 0.])
0090             if not (zlo - 3 < o[2] < zhi + 3 or depth < 1):
0091                 continue
0092             if in_stave and (o[1] > yhi + 12 or o[1] < ylo - 12):
0093                 continue
0094             sh = dv.GetShape()
0095             if mat in COLS and dv.GetNdaughters() == 0 and (
0096                     sh.IsA().InheritsFrom('TGeoBBox') or sh.IsA().GetName() in ('TGeoTrd2', 'TGeoTrap')):
0097                 # leaf volumes only: the chip container is Si too
0098                 P = np.array([to_master(m, list(q)) for q in shape_pts(sh)])
0099                 if zlo < P[:, 2].mean() < zhi:
0100                     P[:, 1] = np.clip(P[:, 1], ylo, yhi)
0101                     if P[:, 1].max() - P[:, 1].min() > 1e-6:
0102                         c = TIER[tier[0]] if mat == 'Epoxy' else COLS[mat]  # stave top: tier colour
0103                         count[mat] = count.get(mat, 0) + 1
0104                         for f in FACES:
0105                             polys.append(P[f])
0106                             fc.append(matplotlib.colors.to_rgb(c))
0107             walk(dv, m, depth + 1, in_stave or name.startswith(STAVE))
0108     walk(vol, [], 0)
0109     print('boxes:', count, 'faces', len(polys))
0110     return polys, fc
0111 
0112 
0113 def render(polys, fc, elev, azim):
0114     # orthographic camera, radial z up on screen
0115     el, az = np.radians(elev), np.radians(azim)
0116     D = np.array([np.cos(el) * np.cos(az), np.cos(el) * np.sin(az), np.sin(el)])  # towards the viewer
0117     Rt = np.array([-np.sin(az), np.cos(az), 0.])
0118     Up = np.cross(D, Rt)
0119     allp = np.vstack(polys)
0120     sx, sy = allp @ Rt, allp @ Up
0121     W, H = 1800 * SS, 1100 * SS
0122     sc = min(0.94 * W / np.ptp(sx), 0.94 * H / np.ptp(sy))
0123     ox, oy = W / 2 - sc * (sx.max() + sx.min()) / 2, H / 2 + sc * (sy.max() + sy.min()) / 2
0124     zbuf = np.full((H, W), -np.inf)
0125     img = np.ones((H, W, 3))
0126     oid = np.full((H, W), -1, dtype=np.int32)
0127     light = np.array([0.35, -0.45, 0.82])
0128     light /= np.linalg.norm(light)
0129 
0130     def raster(tri, depth, colour, ident):
0131         xs, ys = tri[:, 0], tri[:, 1]
0132         x0, x1 = int(max(xs.min(), 0)), int(min(xs.max() + 1, W - 1))
0133         y0, y1 = int(max(ys.min(), 0)), int(min(ys.max() + 1, H - 1))
0134         if x1 <= x0 or y1 <= y0:
0135             return
0136         X, Y = np.meshgrid(np.arange(x0, x1) + 0.5, np.arange(y0, y1) + 0.5)
0137         d = (ys[1] - ys[2]) * (xs[0] - xs[2]) + (xs[2] - xs[1]) * (ys[0] - ys[2])
0138         if abs(d) < 1e-12:
0139             return
0140         a = ((ys[1] - ys[2]) * (X - xs[2]) + (xs[2] - xs[1]) * (Y - ys[2])) / d
0141         b = ((ys[2] - ys[0]) * (X - xs[2]) + (xs[0] - xs[2]) * (Y - ys[2])) / d
0142         c = 1 - a - b
0143         m = (a >= -1e-9) & (b >= -1e-9) & (c >= -1e-9)
0144         z = a * depth[0] + b * depth[1] + c * depth[2]
0145         sub = zbuf[y0:y1, x0:x1]
0146         upd = m & (z > sub)
0147         sub[upd] = z[upd]
0148         img[y0:y1, x0:x1][upd] = colour
0149         oid[y0:y1, x0:x1][upd] = ident
0150 
0151     for k, (P, col) in enumerate(zip(polys, fc)):
0152         n = np.cross(P[1] - P[0], P[2] - P[1])
0153         n /= (np.linalg.norm(n) + 1e-30)
0154         if np.dot(n, D) < 0:
0155             n = -n  # all solids: shade the visible side
0156         shade = 0.45 + 0.55 * max(np.dot(n, light), 0.) * 0.9 + 0.08 * max(np.dot(n, D), 0.)
0157         colour = np.clip(np.array(col) * shade, 0, 1)
0158         scr = np.stack([ox + sc * (P @ Rt), oy - sc * (P @ Up)], axis=1)
0159         dep = P @ D
0160         for tri in ((0, 1, 2), (0, 2, 3)):
0161             raster(scr[list(tri)], dep[list(tri)], colour, k)
0162     # outline where the face id changes
0163     edge = np.zeros((H, W), bool)
0164     edge[:, 1:] |= oid[:, 1:] != oid[:, :-1]
0165     edge[1:, :] |= oid[1:, :] != oid[:-1, :]
0166     img[edge] = img[edge] * 0.55
0167     return img.reshape(H // SS, SS, W // SS, SS, 3).mean(axis=(1, 3))
0168 
0169 
0170 if __name__ == '__main__':
0171     parser = argparse.ArgumentParser(
0172         prog='render_bic_imaging_3d.py',
0173         description='3D z-buffer render of BIC imaging layers from the loaded geometry')
0174     parser.add_argument('-c', '--compact', help='compact detector file',
0175                         default=f'{os.getenv("DETECTOR_PATH")}/{os.getenv("DETECTOR_CONFIG")}.xml')
0176     parser.add_argument('-o', '--output', default='bic_imaging_3d.png', help='output figure')
0177     parser.add_argument('--sector', default='sector26', help='sector volume to draw (layers 2-6: sector26)')
0178     parser.add_argument('--y-range', nargs=2, type=float, default=[-3., 3.], metavar=('LO', 'HI'),
0179                         help='clip window along the beam [cm]')
0180     parser.add_argument('--z-range', nargs=2, type=float, required=True, metavar=('LO', 'HI'),
0181                         help='radial window in the sector frame [cm], selects the layers')
0182     parser.add_argument('--view', nargs=2, type=float, default=[24., 62.], metavar=('ELEV', 'AZIM'),
0183                         help='camera elevation and azimuth [deg]')
0184     parser.add_argument('--skip', default='scifi|^fiber',
0185                         help='regex (case-insensitive) on volume and material names to skip with their daughters')
0186     parser.add_argument('--title', default='BIC imaging layers, radial direction up; outer carbon plates and ScFi/Pb hidden')
0187     args = parser.parse_args()
0188 
0189     det = dd4hep.Detector.getInstance()
0190     det.fromXML(args.compact)
0191     vols = [v for v in ROOT.gGeoManager.GetListOfVolumes() if v.GetName() == args.sector]
0192     if not vols:
0193         raise SystemExit('volume %s not found in %s' % (args.sector, args.compact))
0194     polys, fc = collect(vols[0], args, re.compile(args.skip, re.I))
0195     if not polys:
0196         raise SystemExit('nothing to draw in the given windows')
0197     im = render(polys, fc, *args.view)
0198 
0199     fig = plt.figure(figsize=(16, 10))
0200     ax = fig.add_axes([0, 0.05, 1, 0.9])
0201     ax.imshow(im)
0202     ax.axis('off')
0203     leg = [Patch(fc=c, label=l) for l, c in (
0204         ('stave top, low rail (even id)', TIER[0]), ('stave top, high rail (odd id)', TIER[1]),
0205         ('Si sensor, Cu, Kapton underneath (facing the inner plate)', COLS['Silicon']),
0206         ('carbon: inner plate and side walls', COLS['CarbonFiber']))]
0207     ax.legend(handles=leg, loc='upper left', fontsize=11, frameon=False)
0208     fig.suptitle(args.title, fontsize=12)
0209     fig.savefig(args.output, dpi=110)
0210     print('wrote', args.output)