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 the silicon layout of two BIC imaging staves from the loaded DD4hep/TGeo geometry, seen from
0006     above: one stave of the -z tray (tray 0) and the stave of the +z tray (tray 1) that sits at the same
0007     x, so that together they form one line of silicon along the beam (12 AstroPix modules each, 9 chips
0008     per module). y runs along the beam (true scale), x across the stave (not to scale in the full-stave
0009     panel). All dimensions are measured from the node shapes and matrices; the gaps are printed to stdout.
0010 
0011     Figure 1 (<prefix>.png): the two staves plus four equal-scale zooms (outer stave end, chip-to-chip
0012     gap, module-to-module gap, junction of the two trays at the calorimeter centre).
0013     Figure 2 (<prefix>_module.png): module 0 of each stave with its 9 chips at true scale.
0014     Module, chip, stave and tray labels are the readout ids (physVolIDs) of the placements; positions go
0015     through the full node matrices (the +z tray is the -z tray rotated by 180 degrees about the layer
0016     normal, so stave k of the +z tray is at the x-mirrored position of stave k of the -z tray). Module
0017     and chip ids count from the outer end of the tray. Colour = module id parity (blue even, orange
0018     odd); the same colours are used in all panels.
0019 
0020     use case (writes <prefix>.png and <prefix>_module.png):
0021     python scripts/subdetector_tests/bic/draw_bic_stave_modules.py -c epic_craterlake_bic_6layers.xml \
0022         -o pr-material/figures/bic_stave_modules --sector sector26 --layer 2 --stave 0
0023 '''
0024 import argparse
0025 import array
0026 import os
0027 
0028 import ROOT
0029 import dd4hep
0030 import matplotlib
0031 matplotlib.use('Agg')
0032 import matplotlib.pyplot as plt
0033 from matplotlib.patches import ConnectionPatch, Rectangle
0034 
0035 ROOT.gROOT.SetBatch(True)
0036 
0037 # volume-name prefixes defined by src/BarrelCalorimeterImaging_geo.cpp
0038 LAYER = 'layer'
0039 TRAY = 'tray'              # trays tray0 (-z) and tray1 (+z, the same volume rotated by 180 deg); readout id 'tray'
0040 STAVE = 'stave'            # staves stave<k> inside a tray, air; readout id 'stave' (k within the tray)
0041 MODULE = 'AstroPix_Module'  # module envelope (air), readout id 'module', counted from the outer stave end
0042 CHIP = 'AstroPix_Chip'     # chip assembly, readout id 'chip', counted from the outer end; daughter is the Si box
0043 
0044 COLORS = ('#9ecae1', '#fdd0a2')  # even, odd module index
0045 EDGE, MARK = '#333333', '#b2182b'
0046 
0047 
0048 def find_volume(vol, name, depth=0):
0049     for i in range(vol.GetNdaughters()):
0050         dv = vol.GetNode(i).GetVolume()
0051         if dv.GetName() == name:
0052             return dv
0053         if depth < 4:
0054             r = find_volume(dv, name, depth + 1)
0055             if r:
0056                 return r
0057     return None
0058 
0059 
0060 def volid(node, field):
0061     '''readout id (physVolID) of a placement, e.g. module or chip'''
0062     return {k.decode() if isinstance(k, bytes) else k: v for k, v in dd4hep.PlacedVolume(node).volIDs()}[field]
0063 
0064 
0065 def footprint(chain, shape):
0066     '''layer-local (x, y centre, y half-length, x half-width) in mm of a box shape placed through the node
0067     chain (outermost node first), using the full node matrices (the +z tray is rotated by 180 degrees)'''
0068     ys, xs = [], []
0069     for sx in (-1, 1):
0070         for sy in (-1, 1):
0071             p = array.array('d', [sx * shape.GetDX(), sy * shape.GetDY(), 0.])
0072             for n in reversed(chain):
0073                 q = array.array('d', [0., 0., 0.])
0074                 n.GetMatrix().LocalToMaster(p, q)
0075                 p = q
0076             xs.append(10 * p[0])
0077             ys.append(10 * p[1])
0078     return dict(x=(max(xs) + min(xs)) / 2, y=(max(ys) + min(ys)) / 2, hy=(max(ys) - min(ys)) / 2, hx=(max(xs) - min(xs)) / 2)
0079 
0080 
0081 def extract(args):
0082     det = dd4hep.Detector.getInstance()
0083     det.fromXML(args.compact)
0084     sdet = det.detector(args.detector)
0085     if not sdet.isValid():
0086         raise SystemExit('detector %s not found in %s' % (args.detector, args.compact))
0087     sec = find_volume(sdet.placement().volume().ptr(), args.sector)
0088     if not sec:
0089         raise SystemExit('volume %s not found in %s' % (args.sector, args.detector))
0090     layer = [sec.GetNode(i) for i in range(sec.GetNdaughters())
0091              if sec.GetNode(i).GetName().startswith('%s%d_' % (LAYER, args.layer))]
0092     if not layer:
0093         raise SystemExit('layer %d not found in %s' % (args.layer, args.sector))
0094     lv = layer[0].GetVolume()
0095     trays = sorted((lv.GetNode(i) for i in range(lv.GetNdaughters()) if lv.GetNode(i).GetName().startswith(TRAY)),
0096                    key=lambda t: t.GetMatrix().GetTranslation()[1])  # -z tray first
0097     if len(trays) != 2:
0098         raise SystemExit('layer %d: expected two trays, found %d' % (args.layer, len(trays)))
0099     cand = [[(tn, sn) for sn in (tn.GetVolume().GetNode(i) for i in range(tn.GetVolume().GetNdaughters()))
0100              if sn.GetName().startswith(STAVE)] for tn in trays]
0101     first = [c for c in cand[0] if volid(c[1], 'stave') == args.stave]
0102     if not first:
0103         raise SystemExit('stave %d not found in %s of layer %d' % (args.stave, trays[0].GetName(), args.layer))
0104     # the stave of the +z tray at the same layer-frame x as the chosen one (its z tier may differ)
0105     fp = lambda c: footprint([c[0], c[1]], c[1].GetVolume().GetShape())
0106     f0 = fp(first[0])
0107     second = [c for c in cand[1] if abs(fp(c)['x'] - f0['x']) < 1e-3]
0108     if len(second) != 1:
0109         raise SystemExit('no unique stave of %s at x = %.3f mm' % (trays[1].GetName(), f0['x']))
0110     out = []
0111     for tn, h in (first[0], second[0]):
0112         hv = h.GetVolume()
0113         d = dict(id=volid(h, 'stave'), tray=volid(tn, 'tray'), mods=[], **footprint([tn, h], hv.GetShape()))
0114         for i in range(hv.GetNdaughters()):
0115             m = hv.GetNode(i)
0116             if not m.GetName().startswith(MODULE):
0117                 continue
0118             mv = m.GetVolume()
0119             mod = dict(id=volid(m, 'module'), chips=[], **footprint([tn, h, m], mv.GetShape()))
0120             for j in range(mv.GetNdaughters()):
0121                 cn = mv.GetNode(j)
0122                 c = cn.GetVolume().GetNode(0)  # Si box inside the chip assembly
0123                 chip = dict(id=volid(cn, 'chip'), **footprint([tn, h, m, cn, c], c.GetVolume().GetShape()))
0124                 mod['chips'].append(chip)
0125             mod['chips'].sort(key=lambda c: c['y'])
0126             d['mods'].append(mod)
0127         d['mods'].sort(key=lambda m: m['y'])  # ascending y; the ids follow from the geometry
0128         out.append(d)
0129     return out
0130 
0131 
0132 def box(ax, y, hy, hx, **kw):
0133     ax.add_patch(Rectangle((y - hy, -hx), 2 * hy, 2 * hx, **kw))
0134 
0135 
0136 def label(h):
0137     return '%s (tray %d), stave %d' % ('-z tray' if h['y'] < 0 else '+z tray', h['tray'], h['id'])
0138 
0139 
0140 def draw(ax, staves, labels=False, lw=0.6):
0141     for h in staves:
0142         box(ax, h['y'], h['hy'], h['hx'], fill=False, ec=EDGE, ls='--', lw=1.4, zorder=4)
0143         for m in h['mods']:
0144             for c in m['chips']:
0145                 box(ax, c['y'], c['hy'], c['hx'], fc=COLORS[m['id'] % 2], ec=EDGE, lw=lw, zorder=2)
0146             box(ax, m['y'], m['hy'], m['hx'], fill=False, ec=EDGE, lw=lw * 2, zorder=3)
0147             if labels:
0148                 ax.text(m['y'], 0, str(m['id']), ha='center', va='center', fontsize=8, zorder=5)
0149 
0150 
0151 def dim(ax, y1, y2, x, text, tx=None, ha='center', off=0.5):
0152     '''dimension marker for the gap y1..y2: two arrows pointing at its edges from outside, plus the text'''
0153     for a, b in ((y1 - off, y1), (y2 + off, y2)):
0154         ax.annotate('', xy=(b, x), xytext=(a, x), arrowprops=dict(arrowstyle='->', color=MARK, lw=1.3, shrinkA=0, shrinkB=0))
0155     ax.text((y1 + y2) / 2 if tx is None else tx, x + 0.35, text, color=MARK, ha=ha, va='bottom', fontsize=10, zorder=6,
0156             bbox=dict(fc='white', ec='none', alpha=0.85, pad=1))
0157 
0158 
0159 def table(staves):
0160     h0, h1 = staves
0161     chip, mod = h0['mods'][0]['chips'][0], h0['mods'][0]
0162     cg = [b['y'] - b['hy'] - (a['y'] + a['hy']) for h in staves for m in h['mods'] for a, b in zip(m['chips'], m['chips'][1:])]
0163     mg = [b['y'] - b['hy'] - (a['y'] + a['hy']) for h in staves for a, b in zip(h['mods'], h['mods'][1:])]
0164     jg = h1['mods'][0]['y'] - h1['mods'][0]['hy'] - (h0['mods'][-1]['y'] + h0['mods'][-1]['hy'])
0165     eg = [(h['mods'][0]['y'] - h['mods'][0]['hy']) - (h['y'] - h['hy']) for h in staves[:1]] + \
0166          [(h['y'] + h['hy']) - (h['mods'][-1]['y'] + h['mods'][-1]['hy']) for h in staves[1:]]
0167     hg = (h1['y'] - h1['hy']) - (h0['y'] + h0['hy'])
0168     rows = [('chip Si size y x x [mm]', '%.3f x %.3f' % (2 * chip['hy'], 2 * chip['hx'])),
0169             ('chips per module', str(len(mod['chips']))),
0170             ('module envelope y x x [mm]', '%.3f x %.3f' % (2 * mod['hy'], 2 * mod['hx'])),
0171             ('stave envelope y x x [mm]', '%.3f x %.3f' % (2 * h0['hy'], 2 * h0['hx'])),
0172             ('modules per stave (-z tray + +z tray)', '%d + %d' % (len(h0['mods']), len(h1['mods']))),
0173             ('chips in the two staves', str(sum(len(m['chips']) for h in staves for m in h['mods']))),
0174             ('chip-to-chip gap [mm] (min/max)', '%.3f / %.3f' % (min(cg), max(cg))),
0175             ('module-to-module gap [mm] (min/max)', '%.3f / %.3f' % (min(mg), max(mg))),
0176             ('junction module gap at y=0 [mm]', '%.3f' % jg),
0177             ('gap at the outer stave ends [mm]', '%.3f / %.3f' % tuple(eg)),
0178             ('-z tray / +z tray stave box gap at y=0 [mm]', '%.3f' % hg),
0179             ('length of the two staves (outer edges) [mm]', '%.3f' % (h1['y'] + h1['hy'] - (h0['y'] - h0['hy'])))]
0180     for k, v in rows:
0181         print('%-46s %s' % (k, v))
0182     print('%-46s %s' % ('paired staves at the same x (%.3f mm)' % h0['x'],
0183                         '%s  +  %s' % (label(h0), label(h1))))
0184     print('%-46s %s' % ('module ids from -z to +z', ' '.join(str(m['id']) for h in staves for m in h['mods'])))
0185     print('%-46s %s' % ('chip ids in the first module of each stave',
0186                         ' | '.join('%s: ' % label(h) + ' '.join(str(c['id']) for c in h['mods'][0]['chips'])
0187                                    for h in staves)))
0188 
0189 
0190 def fig_stave(staves, args):
0191     h0, h1 = staves
0192     L = h1['y'] + h1['hy']
0193     fig = plt.figure(figsize=(16, 8.6))
0194     top = fig.add_axes([0.06, 0.64, 0.92, 0.25])
0195     draw(top, staves, labels=True)
0196     top.set_xlim(-L * 1.01, L * 1.01)
0197     top.set_ylim(-14, 14)
0198     top.set_yticks([])
0199     top.set_xlabel('y along the beam, from the calorimeter centre [mm] (x across the stave is stretched)')
0200     for h in staves:
0201         ids = [m['id'] for m in (h['mods'] if h['y'] < 0 else h['mods'][::-1])]  # outer end first
0202         top.text(h['y'], 12, '%s: modules %d-%d from the outer end' % (label(h), ids[0], ids[-1]),
0203                  ha='center', va='center', fontsize=10)
0204     # zoom targets: (title, y centre, annotations)
0205     m0 = h0['mods']
0206     gaps = [(h0['y'] - h0['hy'], 'outer stave end'),
0207             (0.5 * (m0[3]['chips'][4]['y'] - m0[3]['chips'][4]['hy'] + m0[3]['chips'][3]['y'] + m0[3]['chips'][3]['hy']),
0208              'chip-to-chip gap'),
0209             (0.5 * (m0[7]['y'] + m0[7]['hy'] + m0[8]['y'] - m0[8]['hy']), 'module-to-module gap'),
0210             (0.0, 'junction of the two trays (calorimeter centre)')]
0211     for k, (yc, title) in enumerate(gaps):
0212         ax = fig.add_axes([0.06 + 0.2375 * k, 0.07, 0.195, 0.40])
0213         draw(ax, staves, lw=0.8)
0214         w = 2.1
0215         ax.set_xlim(yc - w, yc + w)
0216         ax.set_ylim(10.4 - 2 * w, 10.4)
0217         ax.set_aspect('equal')
0218         ax.set_xlabel('y [mm]')
0219         ax.set_ylabel('x [mm]')
0220         ax.set_title('(%s) %s' % ('abcd'[k], title), fontsize=11)
0221         top.plot([yc, yc], [-10.2, 10.2], color=MARK, lw=1.5, zorder=6)
0222         top.text(yc, -12.3, '(%s)' % 'abcd'[k], color=MARK, ha='center', va='center', fontsize=11)
0223         fig.add_artist(ConnectionPatch((yc, -10.2), (0.5, 1), 'data', 'axes fraction', axesA=top, axesB=ax,
0224                                        color=MARK, lw=0.8, ls=':'))
0225         if k == 0:
0226             e = h0['y'] - h0['hy']
0227             dim(ax, e, m0[0]['y'] - m0[0]['hy'], 8.0, '%.3f mm' % (m0[0]['y'] - m0[0]['hy'] - e), tx=e + 1.2)
0228             ax.text(e - 0.1, 7.0, 'stave\nenvelope edge', ha='right', fontsize=9)
0229         elif k == 2:
0230             a, b = m0[7], m0[8]
0231             dim(ax, a['y'] + a['hy'], b['y'] - b['hy'], 8.0, '%.3f mm' % (b['y'] - b['hy'] - a['y'] - a['hy']))
0232         elif k == 1:
0233             a, b = m0[3]['chips'][3], m0[3]['chips'][4]
0234             dim(ax, a['y'] + a['hy'], b['y'] - b['hy'], 8.0, '%.3f mm' % (b['y'] - b['hy'] - a['y'] - a['hy']))
0235         else:
0236             a, b = m0[-1], h1['mods'][0]
0237             dim(ax, a['y'] + a['hy'], 0, 8.0, '%.3f mm' % (-a['y'] - a['hy']), tx=-0.3, ha='right', off=0.3)
0238             dim(ax, 0, b['y'] - b['hy'], 8.0, '%.3f mm' % (b['y'] - b['hy']), tx=0.3, ha='left', off=0.3)
0239             ax.text(0, 7.0, 'module gap %.3f mm\nstave envelopes touch' % (b['y'] - b['hy'] - a['y'] - a['hy']),
0240                     ha='center', fontsize=9, zorder=6, bbox=dict(fc='white', ec='none', alpha=0.9))
0241     fig.suptitle('BIC %s layer %d, %s and %s at the same x (x = %.1f mm): %d chips (%s)\n'
0242                  'boxes: AstroPix chip Si (component0) footprints, solid outlines: module envelopes (air), '
0243                  'dashed: stave envelopes (air)' %
0244                  (args.sector, args.layer, label(h0), label(h1), h0['x'], sum(len(m['chips']) for h in staves for m in h['mods']),
0245                   'colour = module id parity'), fontsize=10.5, y=0.97)
0246     fig.savefig(args.output + '.png', dpi=150)
0247 
0248 
0249 def fig_module(staves, args):
0250     fig, axes = plt.subplots(2, 1, figsize=(14, 5.6))
0251     for ax, h in zip(axes, staves):
0252         m = next(m for m in h['mods'] if m['id'] == 0)
0253         out = -1 if h['y'] < 0 else 1  # direction of the outer stave end along y, from the geometry
0254         for c in m['chips']:
0255             box(ax, c['y'], c['hy'], c['hx'], fc=COLORS[0], ec=EDGE, lw=0.8)
0256             ax.text(c['y'], 0, 'chip %d' % c['id'], ha='center', va='center', fontsize=9)
0257         box(ax, m['y'], m['hy'], m['hx'], fill=False, ec=EDGE, lw=1.6)
0258         c0 = m['chips'][0]
0259         ax.annotate('', xy=(c0['y'] - c0['hy'], c0['hx'] + 3), xytext=(c0['y'] + c0['hy'], c0['hx'] + 3),
0260                     arrowprops=dict(arrowstyle='<->', color=MARK, lw=1.3, shrinkA=0, shrinkB=0))
0261         ax.text(c0['y'], c0['hx'] + 4.5, 'chip %.3f mm' % (2 * c0['hy']), color=MARK, ha='center', fontsize=10)
0262         yb = -c0['hx'] - 3
0263         for sgn, txt in ((out, 'outer stave end'), (-out, 'towards junction (y = 0)')):
0264             ax.annotate(txt, xy=(m['y'] + sgn * (m['hy'] + 3.5), yb), xytext=(m['y'] + sgn * 12, yb), color=MARK,
0265                         ha='right' if sgn < 0 else 'left', va='center', fontsize=10,
0266                         arrowprops=dict(arrowstyle='->', color=MARK, lw=1.3, shrinkA=0, shrinkB=0))
0267         ax.set_xlim(m['y'] - m['hy'] - 4, m['y'] + m['hy'] + 4)
0268         ax.set_ylim(-c0['hx'] - 6, c0['hx'] + 8)
0269         ax.set_aspect('equal')
0270         ax.set_ylabel('x [mm]')
0271         ax.set_title('module %d of the %s, true scale: %.3f mm long, %d chips, '
0272                      '%.3f mm chip-to-chip gap (boxes: chip Si footprints, outline: module envelope)' %
0273                      (m['id'], label(h), 2 * m['hy'], len(m['chips']),
0274                       m['chips'][1]['y'] - m['chips'][1]['hy'] - m['chips'][0]['y'] - m['chips'][0]['hy']), fontsize=10)
0275     axes[-1].set_xlabel('y from the calorimeter centre [mm]')
0276     fig.tight_layout()
0277     fig.savefig(args.output + '_module.png', dpi=150)
0278 
0279 
0280 if __name__ == '__main__':
0281     parser = argparse.ArgumentParser()
0282     parser.add_argument('-c', '--compact', help='compact detector file',
0283                         default=f'{os.getenv("DETECTOR_PATH")}/{os.getenv("DETECTOR_CONFIG")}.xml')
0284     parser.add_argument('-o', '--output', default='bic_stave_modules', help='output file prefix')
0285     parser.add_argument('--detector', default='EcalBarrelImaging', help='name of the imaging calorimeter')
0286     parser.add_argument('--sector', default='sector26', help='sector volume (sector1 for layer 1, sector26 for 2-6)')
0287     parser.add_argument('--layer', type=int, default=2, help='layer number')
0288     parser.add_argument('--stave', type=int, default=0, help='stave id in the -z tray (paired with the +z tray stave at the same x)')
0289     args = parser.parse_args()
0290     staves = extract(args)
0291     table(staves)
0292     fig_stave(staves, args)
0293     fig_module(staves, args)