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     Draw x-radial cross-sections of the BIC imaging layers (staves, carbon plates and side walls)
0006     from the loaded DD4hep/TGeo geometry. x runs across the sector, z radially outward from the
0007     inner face of the layer; layer 1 is the bottom panel of the combined figure.
0008     Staves are blue (even stave id, low rail) or orange (odd, high rail), the sensitive Si slice red,
0009     carbon plates and walls grey, the layer trapezoid black.
0010     Each layer holds two trays along the beam (tray0 at -z, tray1 at +z; tray1 is tray0 rotated by
0011     180 degrees about the radial axis, so for an even number of staves its layout is mirrored in x).
0012     --tray selects the tray drawn (default 0, the -z tray); --trays-side-by-side instead writes one
0013     figure comparing both trays of the first drawn layer. Geometry with the staves directly in the
0014     layer (no trays) is drawn as before.
0015 
0016     use case (writes <prefix>_layer<N>.png, <prefix>_all.png and <prefix>_zoom.png):
0017     python scripts/subdetector_tests/bic/draw_bic_imaging_sector.py -c epic_craterlake_bic_6layers.xml \
0018         -o figures/after --label After --layers 1-6
0019 
0020     use case (both trays of layer 1 side by side, writes bic_trays_layer1.png):
0021     python scripts/subdetector_tests/bic/draw_bic_imaging_sector.py -c epic_craterlake_bic_6layers.xml \
0022         -o pr-material/figures/bic --layers 1 --trays-side-by-side
0023 '''
0024 import argparse
0025 import array
0026 import math
0027 import os
0028 import re
0029 
0030 import ROOT
0031 import dd4hep
0032 import matplotlib
0033 matplotlib.use('Agg')
0034 import matplotlib.pyplot as plt
0035 from matplotlib.patches import Polygon
0036 
0037 ROOT.gROOT.SetBatch(True)
0038 
0039 # volume-name prefixes defined by src/BarrelCalorimeterImaging_geo.cpp
0040 SECTOR = 'sector'
0041 LAYER = 'layer'
0042 TRAY = 'tray'              # trays (tray0 at -z, tray1 at +z), layer daughters holding the staves
0043 STAVE = 'stave'            # staves (stave<id>) in a tray; older geometry: staves directly in the layer
0044 SLICE = 'slice1'           # sensitive Si slice inside the chip components
0045 PLATE = 'frame'            # inner/outer carbon plates (frame_inner<N>, frame_outer<N>)
0046 WALL = 'frame_side'        # carbon side walls, checked before PLATE
0047 
0048 LOW, HIGH, SI, GREY = '#2166ac', '#e08214', '#b2182b', '#777777'
0049 
0050 
0051 def box_pts(sh):
0052     return [(-sh.GetDX(), -sh.GetDZ()), (sh.GetDX(), -sh.GetDZ()),
0053             (sh.GetDX(), sh.GetDZ()), (-sh.GetDX(), sh.GetDZ())]
0054 
0055 
0056 def trd_pts(sh):
0057     return [(-sh.GetDx1(), -sh.GetDz()), (sh.GetDx1(), -sh.GetDz()),
0058             (sh.GetDx2(), sh.GetDz()), (-sh.GetDx2(), sh.GetDz())]
0059 
0060 
0061 def trap_pts(sh):
0062     # TGeoTrap is a TGeoArb8: 4 (x, y) vertices at -dz, then 4 at +dz; project on x-z
0063     v = sh.GetVertices()
0064     dz = sh.GetDz()
0065     lo = [v[2 * k] for k in range(4)]
0066     hi = [v[2 * k] for k in range(4, 8)]
0067     return [(min(lo), -dz), (max(lo), -dz), (max(hi), dz), (min(hi), dz)]
0068 
0069 
0070 def shape_pts(sh):
0071     return trap_pts(sh) if sh.IsA().GetName() == 'TGeoTrap' else trd_pts(sh)
0072 
0073 
0074 def xf(mats, pts, zoff):
0075     '''transform shape points through the node matrices (innermost first), cm -> mm, z from the layer bottom'''
0076     out = []
0077     for x, z in pts:
0078         p = array.array('d', [x, 0., z])
0079         for m in mats:
0080             q = array.array('d', [0., 0., 0.])
0081             m.LocalToMaster(p, q)
0082             p = q
0083         out.append((10 * p[0], 10 * (p[2] + zoff)))
0084     return out
0085 
0086 
0087 def find_sectors(vol, names, depth=0):
0088     '''sector volumes below the detector volume, by name'''
0089     found = {}
0090     for i in range(vol.GetNdaughters()):
0091         dv = vol.GetNode(i).GetVolume()
0092         if dv.GetName() in names:
0093             found[dv.GetName()] = dv
0094         elif depth < 4:
0095             found.update(find_sectors(dv, names, depth + 1))
0096     return found
0097 
0098 
0099 def find_slice(vol):
0100     '''nodes from vol down to the first sensitive slice (module > chip > component > slice), or None'''
0101     for i in range(vol.GetNdaughters()):
0102         n = vol.GetNode(i)
0103         if n.GetName().startswith(SLICE):
0104             return [n]
0105         sub = find_slice(n.GetVolume())
0106         if sub:
0107             return [n] + sub
0108     return None
0109 
0110 
0111 def x_ordered(pts):
0112     '''corners with the left edge first (a 180 degree rotation about the radial axis swaps them pairwise)'''
0113     return [pts[1], pts[0], pts[3], pts[2]] if pts[0][0] > pts[1][0] else pts
0114 
0115 
0116 def make_stave(idx, dn, outer, zoff):
0117     '''stave at placement dn below the nodes outer (innermost first): envelope and first sensitive slice'''
0118     box = xf([dn.GetMatrix()] + outer, box_pts(dn.GetVolume().GetShape()), zoff)
0119     path = find_slice(dn.GetVolume())
0120     si = xf([nd.GetMatrix() for nd in reversed(path)] + [dn.GetMatrix()] + outer,
0121             box_pts(path[-1].GetVolume().GetShape()), zoff)
0122     return dict(idx=idx, box=x_ordered(box), si=x_ordered(si))
0123 
0124 
0125 def extract(args):
0126     det = dd4hep.Detector.getInstance()
0127     det.fromXML(args.compact)
0128     sdet = det.detector(args.detector)
0129     if not sdet.isValid():
0130         raise SystemExit('detector %s not found in %s' % (args.detector, args.compact))
0131     secs = find_sectors(sdet.placement().volume().ptr(), set(args.sector))
0132     if not secs:
0133         raise SystemExit('none of the volumes %s found in %s' % (args.sector, args.detector))
0134     layers = {}
0135     for sv in secs.values():
0136         for i in range(sv.GetNdaughters()):
0137             ln = sv.GetNode(i)
0138             if not ln.GetName().startswith(LAYER):
0139                 continue
0140             n = int(ln.GetName()[len(LAYER):].split('_')[0])
0141             if n not in args.layers:
0142                 continue
0143             lv = ln.GetVolume()
0144             trd = lv.GetShape()
0145             zoff = trd.GetDz()  # layer-local z measured from the inner face
0146             d = dict(outline=xf([], trd_pts(trd), zoff), plates=[], walls=[], staves=[], trays={})
0147             seen = set()
0148             for j in range(lv.GetNdaughters()):
0149                 dn = lv.GetNode(j)
0150                 name = dn.GetName()
0151                 sh = dn.GetVolume().GetShape()
0152                 if name.startswith(WALL):
0153                     d['walls'].append(xf([dn.GetMatrix()], shape_pts(sh), zoff))
0154                 elif name.startswith(PLATE):
0155                     d['plates'].append(xf([dn.GetMatrix()], shape_pts(sh), zoff))
0156                 elif name.startswith(STAVE):
0157                     # a stave position consists of several staves along y with the same
0158                     # x-z footprint: draw each position once, index = order of first appearance
0159                     box = xf([dn.GetMatrix()], box_pts(sh), zoff)
0160                     key = tuple(sorted((round(x, 3), round(z, 3)) for x, z in box))  # any corner order
0161                     if key in seen:
0162                         continue
0163                     seen.add(key)
0164                     # placement order = stave index within the layer
0165                     d['staves'].append(make_stave(len(d['staves']), dn, [], zoff))
0166                 elif name.startswith(TRAY) and name[len(TRAY):].isdigit():
0167                     tv = dn.GetVolume()
0168                     sts = []
0169                     for k in range(tv.GetNdaughters()):
0170                         sn = tv.GetNode(k)
0171                         mt = re.fullmatch(STAVE + r'(\d+)', sn.GetName())
0172                         if mt:  # idx = readout stave id; the stave matrix is tray-local
0173                             sts.append(make_stave(int(mt.group(1)), sn, [dn.GetMatrix()], zoff))
0174                     d['trays'][int(name[len(TRAY):])] = sorted(sts, key=lambda s: s['box'][0][0])
0175             if d['trays']:
0176                 if args.tray not in d['trays']:
0177                     raise SystemExit('layer %d has trays %s, no tray %d' % (n, sorted(d['trays']), args.tray))
0178                 d['staves'] = d['trays'][args.tray]
0179             if d['staves']:
0180                 layers[n] = d
0181     return layers
0182 
0183 
0184 def wall_slope(d):
0185     '''half-angle of the slanted layer side wall: atan(dx/dz) of the trapezoid outline'''
0186     (xa, za), (xb, zb) = d['outline'][0], d['outline'][3]
0187     return math.atan2(abs(xb - xa), zb - za)
0188 
0189 
0190 def draw_layer(ax, d, n, label, stretch=True, tray_label='', ids=False):
0191     ax.add_patch(Polygon(d['outline'], closed=True, fill=False, ec='k', lw=1.2))
0192     for pl in d['plates']:
0193         ax.add_patch(Polygon(pl, closed=True, fc=GREY, ec=GREY, alpha=0.6))
0194     for pl in d['walls']:
0195         ax.add_patch(Polygon(pl, closed=True, fc='#4d4d4d', ec='#4d4d4d', alpha=0.8))
0196     for s in d['staves']:
0197         col = LOW if s['idx'] % 2 == 0 else HIGH
0198         ax.add_patch(Polygon(s['box'], closed=True, fc=col, ec=col, alpha=0.35, lw=0.8))
0199         ax.add_patch(Polygon(s['si'], closed=True, fc=SI, ec=SI, alpha=0.9))
0200         if ids:
0201             ax.text(sum(x for x, _ in s['box']) / 4, max(z for _, z in s['box']) + 0.5, str(s['idx']),
0202                     ha='center', va='bottom', fontsize=11, fontweight='bold', color=col)
0203     xs = [x for x, _ in d['outline']]
0204     zs = [z for _, z in d['outline']]
0205     ax.set_xlim(min(xs) - 3, max(xs) + 3)
0206     ax.set_ylim(min(zs) - 1, max(zs) + 1)
0207     st = d['staves']
0208     pitch = st[1]['box'][0][0] - st[0]['box'][0][0] if len(st) > 1 else 0
0209     w = st[0]['box'][1][0] - st[0]['box'][0][0]
0210     ax.set_title('%slayer %d%s: %d staves, pitch %.2f mm, stave overlap %.2f mm'
0211                  % (label + ', ' if label else '', n, tray_label, len(st), pitch, w - pitch), fontsize=10)
0212     ax.set_ylabel('radial z [mm] (up = outward)')
0213     ax.set_xlabel('x across the sector [mm]' + ('  (vertical axis stretched)' if stretch else ''))
0214 
0215 
0216 def zoom(d, n, label, out):
0217     '''three adjacent staves at the left wall, true scale, annotated'''
0218     st = d['staves']
0219     fig, ax = plt.subplots(figsize=(11, 6.5))
0220     draw_layer(ax, d, n, label, stretch=False)
0221     x0, zb = d['outline'][0]
0222     s0, s1, s2 = (s['box'] for s in st[:3])
0223     xc0 = 0.5 * (s0[0][0] + s0[1][0])
0224     xc1 = 0.5 * (s1[0][0] + s1[1][0])
0225     top = max(p[1] for b in (s0, s1, s2) for p in b) - zb  # height of the stave stack above the layer bottom
0226     ax.set_xlim(x0 - 2, s1[1][0] + 0.6 * (xc1 - xc0))  # up to just past the second stave
0227     ax.set_ylim(zb - 1, zb + top + 5)
0228     ax.set_aspect('equal')
0229     ax.set_title('%slayer %d, three adjacent staves at the sector wall (true scale)'
0230                  % (label + ': ' if label else '', n), fontsize=11)
0231     tilted = abs(s0[0][1] - s0[1][1]) > 1e-6
0232     ax.annotate('', xy=(xc1, zb + top + 2), xytext=(xc0, zb + top + 2), arrowprops=dict(arrowstyle='<->'))
0233     ax.text(0.5 * (xc0 + xc1), zb + top + 2.4, 'pitch %.2f mm' % (xc1 - xc0), ha='center', fontsize=9)
0234     if not tilted:
0235         ov0, ov1 = s1[0][0], s0[1][0]
0236         ax.annotate('', xy=(ov1, zb + top + 0.4), xytext=(ov0, zb + top + 0.4),
0237                     arrowprops=dict(arrowstyle='<->', color='r'))
0238         ax.text(0.5 * (ov0 + ov1), zb + top + 0.8, 'overlap %.2f mm' % (ov1 - ov0), ha='center', fontsize=9, color='r')
0239         # rails: heights of stave bottoms above the plate outer face
0240         plate_top = max(p[1] for p in d['plates'][0])
0241         for s in st[:2]:
0242             b = s['box']
0243             xr = b[0][0] + 1.5
0244             ax.annotate('', xy=(xr, b[0][1]), xytext=(xr, plate_top), arrowprops=dict(arrowstyle='<->'))
0245             ax.text(xr + 0.4, 0.5 * (b[0][1] + plate_top), 'rail %.2f mm' % (b[0][1] - plate_top),
0246                     fontsize=8, va='center')
0247         if d['walls']:  # inner face of the left wall: the max-x edge of the wall polygon
0248             w = min(d['walls'], key=lambda q: q[0][0])
0249             (xa, za), (xb, zc) = w[1], w[2]
0250 
0251             def wall_x(z):
0252                 return xa + (z - za) * (xb - xa) / (zc - za)
0253             what = 'wall inner face'
0254         else:
0255             (xa, za), (xb, zc) = d['outline'][0], d['outline'][3]
0256 
0257             def wall_x(z):
0258                 return xa + (z - za) * (xb - xa) / (zc - za)
0259             what = 'wall'
0260         c = (s0[0][0] - wall_x(s0[0][1])) * math.cos(wall_slope(d))  # perpendicular to the slanted face
0261         ax.annotate('min. distance to %s\n(perpendicular) %.2f mm' % (what, abs(c)), xy=s0[0],
0262                     xytext=(x0 + 1, zb + top - 0.5), fontsize=8, arrowprops=dict(arrowstyle='->'))
0263     ax.text(x0 + 1, zb + top + 3.8,
0264             'blue: even stave index%s; orange: odd stave index%s; red: sensitive Si; grey: carbon plates and side walls'
0265             % ('' if tilted else ' (low rail)', '' if tilted else ' (high rail)'), fontsize=8)
0266     fig.tight_layout()
0267     fig.savefig(out, dpi=150)
0268     plt.close(fig)
0269 
0270 
0271 def trays_side_by_side(d, n, out):
0272     '''both trays of one layer next to each other, same view, stave ids in the boxes'''
0273     names = {0: '-z tray (tray0)', 1: '+z tray (tray1)'}
0274     fig, axs = plt.subplots(1, 2, figsize=(14, 4.6), sharey=True)
0275     for ax, t in zip(axs, (0, 1)):
0276         draw_layer(ax, dict(d, staves=d['trays'][t]), n, '', tray_label=', ' + names[t], ids=True)
0277         ax.title.set_fontsize(9)
0278     axs[1].set_ylabel('')
0279     fig.suptitle('BIC imaging layer %d, stave envelopes (blue: even id, low rail; orange: odd id, high rail; '
0280                  'numbers: stave id) and sensitive Si (red)' % n, fontsize=10)
0281     fig.text(0.5, 0.01,
0282              'Cross-section in the layer frame, inner plate down, radial direction up (vertical axis stretched); both panels '
0283              'viewed along +z (from the -z end towards +z, into the page).\n'
0284              'The +z tray is the -z tray rotated by 180 degrees about the radial axis, so with an even number of staves '
0285              'its layout is mirrored in x and the rail tier at a given x is swapped.',
0286              ha='center', va='bottom', fontsize=8)
0287     fig.tight_layout(rect=(0, 0.08, 1, 0.95))
0288     fig.savefig(out, dpi=130)
0289     plt.close(fig)
0290 
0291 
0292 def parse_layers(text):
0293     '''"1,3-5" -> [1, 3, 4, 5]'''
0294     out = []
0295     for part in text.split(','):
0296         lo, _, hi = part.partition('-')
0297         out += range(int(lo), int(hi or lo) + 1)
0298     return sorted(set(out))
0299 
0300 
0301 if __name__ == '__main__':
0302     parser = argparse.ArgumentParser(
0303         prog='draw_bic_imaging_sector.py',
0304         description='Draw x-radial cross-sections of the BIC imaging layers from the loaded geometry')
0305     parser.add_argument('-c', '--compact', help='compact detector file',
0306                         default=f'{os.getenv("DETECTOR_PATH")}/{os.getenv("DETECTOR_CONFIG")}.xml')
0307     parser.add_argument('-o', '--output', default='bic_imaging', help='output file prefix')
0308     parser.add_argument('--detector', default='EcalBarrelImaging', help='name of the imaging calorimeter')
0309     parser.add_argument('--sector', nargs='+', default=['sector1', 'sector26'],
0310                         help='sector volumes to take layers from (layer 1 lives in sector1, layers 2-6 in sector26)')
0311     parser.add_argument('--layers', default='1', help='layers to draw, e.g. 1 or 1-6 or 1,3')
0312     parser.add_argument('--tray', type=int, choices=(0, 1), default=0,
0313                         help='tray to draw: 0 = -z tray (default), 1 = +z tray (the -z tray rotated by 180 deg about the radial axis)')
0314     parser.add_argument('--trays-side-by-side', action='store_true',
0315                         help='only write <output>_trays_layer<N>.png comparing both trays of the first drawn layer')
0316     parser.add_argument('--zoom-layer', type=int, help='layer for the zoom figure (default: first drawn layer)')
0317     parser.add_argument('--label', default='', help='label for the figure titles')
0318     args = parser.parse_args()
0319     args.layers = set(parse_layers(args.layers))
0320     if args.zoom_layer:
0321         args.layers.add(args.zoom_layer)
0322 
0323     layers = extract(args)
0324     if not layers:
0325         raise SystemExit('no layers %s with staves found' % sorted(args.layers))
0326     if args.trays_side_by_side:
0327         n = min(layers)
0328         if len(layers[n]['trays']) < 2:
0329             raise SystemExit('layer %d has no two trays' % n)
0330         trays_side_by_side(layers[n], n, '%s_trays_layer%d.png' % (args.output, n))
0331         print('wrote %s_trays_layer%d.png' % (args.output, n))
0332         raise SystemExit(0)
0333     for n in sorted(layers):
0334         fig, ax = plt.subplots(figsize=(14, 3.4))
0335         draw_layer(ax, layers[n], n, args.label)
0336         fig.tight_layout()
0337         fig.savefig('%s_layer%d.png' % (args.output, n), dpi=130)
0338         plt.close(fig)
0339         print('wrote %s_layer%d.png' % (args.output, n))
0340     if len(layers) > 1:
0341         fig, axs = plt.subplots(len(layers), 1, figsize=(14, 2.9 * len(layers)))
0342         for ax, n in zip(axs, sorted(layers, reverse=True)):  # layer 1 at the bottom
0343             draw_layer(ax, layers[n], n, args.label)
0344         fig.tight_layout()
0345         fig.savefig(args.output + '_all.png', dpi=110)
0346         plt.close(fig)
0347         print('wrote %s_all.png' % args.output)
0348     zl = args.zoom_layer or min(layers)
0349     if zl in layers and len(layers[zl]['staves']) >= 3:
0350         zoom(layers[zl], zl, args.label, args.output + '_zoom.png')
0351         print('wrote %s_zoom.png' % args.output)
0352     else:
0353         print('no zoom: layer %d not found or has fewer than 3 staves' % zl)