Display geometry¶
The mccode_antlr.display submodule parses a component's MCDISPLAY section
into a symbolic Python geometry model backed by Expr. The
geometry can be evaluated at any parameter values and rendered in 3-D — without
compiling the instrument.
Quick start¶
from mccode_antlr.loader import load_mcstas_instr
from mccode_antlr.display import InstrumentDisplay
from mccode_antlr.display.render.matplotlib import plot_geometry
import matplotlib.pyplot as plt
instr = load_mcstas_instr('my_instrument.instr')
disp = InstrumentDisplay(instr)
polys = disp.to_polylines({'E_i': 5.0}) # dict[name → list[np.ndarray]]
fig, ax = plot_geometry(polys)
plt.show()
Single-component use:
from mccode_antlr.display import ComponentDisplay
cd = ComponentDisplay(comp)
pls = cd.to_polylines({'xwidth': 0.05, 'yheight': 0.1})
Architecture¶
Comp.display (tuple[RawC])
│
▼ parse_display_source() ← DisplayVisitor wraps C99 CParser
│
list[Primitive] ← every argument is an Expr
│
├── ComponentDisplay.to_polylines(params) → list[np.ndarray]
│
InstrumentDisplay.to_polylines(params, global_frame=True)
(applies Orient: Rotation × pts + translation, all Expr-backed)
│
dict[comp_name → list[np.ndarray (N,3)]]
│
├──▶ render/matplotlib.py (zero new hard deps)
└──▶ render/threejs.py (soft-import pythreejs / K3D)
The parsing is done by DisplayVisitor, a subclass of the existing C99
CVisitor ANTLR visitor. It handles:
- Simple calls —
circle("xy", 0, 0, 0, r); - Math in arguments —
multiline(5, -xw/2, -yh/2, 0, ...); - Local variable declarations —
double t = height/2; line(0,0,-t, 0,0,t); - Conditionals —
if (show_guide) { rectangle(...); }→ConditionalBlock - Loops —
for (int i = ...) { ... }→LoopBlockplaceholder
API reference¶
parse_display_source¶
mccode_antlr.display.visitor.parse_display_source(source, local_vars=None)
¶
Parse the raw C source of a MCDISPLAY body into geometry primitives.
Parameters¶
source:
The raw C text found between %{ and %} in a component
MCDISPLAY section.
local_vars:
Optional pre-defined variable bindings (e.g. from the component's
SETTING PARAMETERS made available to the display function).
Returns¶
list[Primitive | ConditionalBlock | LoopBlock] The extracted geometry primitives in source order.
Source code in src/mccode_antlr/display/visitor.py
ComponentDisplay¶
mccode_antlr.display.component_display.ComponentDisplay
¶
Parse and evaluate the MCDISPLAY section of a component.
Parameters¶
comp:
The component whose display RawC blocks to parse.
Source code in src/mccode_antlr/display/component_display.py
primitives
property
¶
Lazily parse the display source and cache the result.
is_empty()
¶
to_polylines(params=None)
¶
Return all geometry as a flat list of (N, 3) numpy arrays.
Parameters¶
params: Component parameter values (and any instrument parameters referenced in the display expressions). Values that are unknown in params remain symbolic and may cause evaluation errors; they are silently skipped.
Source code in src/mccode_antlr/display/component_display.py
InstrumentDisplay¶
mccode_antlr.display.instrument_display.InstrumentDisplay
¶
Parse and evaluate the geometry for an entire instrument.
Parameters¶
instr:
The :class:~mccode_antlr.instr.instr.Instr to display.
Source code in src/mccode_antlr/display/instrument_display.py
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | |
component_names
property
¶
Names of components that have display geometry.
component_display(name)
¶
to_polylines(params=None, *, global_frame=True)
¶
Evaluate all component geometries and return polylines.
Parameters¶
params:
Instrument parameter values. Component SETTING parameters that
match instance parameter assignments are also injected automatically.
global_frame:
If True (default) transform all polylines to the global
instrument frame using each component's :class:~mccode_antlr.instr.orientation.Orient.
If False return component-local coordinates.
Returns¶
dict[str, list[np.ndarray]]
Mapping from component instance name to a list of (N, 3)
polyline arrays.
Source code in src/mccode_antlr/display/instrument_display.py
Geometry primitives¶
All non-string arguments are Expr objects and are resolved lazily at
.to_polylines(params) time.
| Primitive | C call | Polylines |
|---|---|---|
Line |
line(x1,y1,z1, x2,y2,z2) |
1 segment |
DashedLine |
dashed_line(x1,y1,z1, x2,y2,z2, n) |
n segments |
Multiline |
multiline(count, x1,y1,z1,...) |
1 open polyline |
Circle |
circle(plane, cx,cy,cz, r) |
1 closed polyline (24 pts) |
Rectangle |
rectangle(plane, cx,cy,cz, w,h) |
1 closed rect (5 pts) |
Box |
box(cx,cy,cz, w,h,d) |
12 edges |
Sphere |
sphere(cx,cy,cz, r) |
3 great circles |
Cylinder |
cylinder(cx,cy,cz, r,h, nx,ny,nz) |
2 end caps + 4 lines |
Cone |
cone(cx,cy,cz, r,h, nx,ny,nz) |
tapered circles + 4 lines |
Magnify |
magnify(scale) |
metadata only |
ConditionalBlock |
if (cond) { ... } |
filtered at evaluate-time |
LoopBlock |
for/while (...) |
unrolled at evaluate-time |
mccode_antlr.display.primitives
¶
Geometry primitives for the McCode MCDISPLAY section.
Each primitive stores its arguments as :class:~mccode_antlr.common.expression.Expr
objects and can:
- :meth:
evaluate— substitute a parameter dict and return a resolved copy with all :class:~mccode_antlr.common.expression.Exprvalues replaced byfloat. - :meth:
to_polylines— return a list of(N, 3)numpy arrays (open or closed polylines) suitable for 3-D rendering. - :meth:
to_mesh— return(vertices, faces)arrays for solid-surface rendering, orNonefor wire-only primitives.
Primitive
dataclass
¶
Abstract base for all MCDISPLAY geometry primitives.
Source code in src/mccode_antlr/display/primitives.py
evaluate(params)
¶
to_polylines(params=None)
¶
Return a list of (N, 3) polyline arrays in component-local coordinates.
to_mesh(params=None)
¶
Return (vertices, faces) for solid-surface rendering, or None.
vertices : (V, 3) float32 array of 3-D positions.
faces : (F, 3) int32 array of triangle vertex indices.
Wire-only primitives return None.
Source code in src/mccode_antlr/display/primitives.py
is_active(params)
¶
Return True if this primitive's condition is satisfied (or absent).
Magnify
dataclass
¶
Bases: Primitive
magnify(what) — sets the magnification scale (metadata only).
Source code in src/mccode_antlr/display/primitives.py
Line
dataclass
¶
Bases: Primitive
line(x1,y1,z1, x2,y2,z2) — a single line segment.
Source code in src/mccode_antlr/display/primitives.py
DashedLine
dataclass
¶
Bases: Primitive
dashed_line(x1,y1,z1, x2,y2,z2, n) — dashed line with n gaps.
Source code in src/mccode_antlr/display/primitives.py
Multiline
dataclass
¶
Bases: Primitive
multiline(count, x1,y1,z1,...) — open polyline with count vertices.
Source code in src/mccode_antlr/display/primitives.py
Circle
dataclass
¶
Bases: Primitive
circle(plane, cx,cy,cz, r) — circle in a coordinate plane.
Source code in src/mccode_antlr/display/primitives.py
Rectangle
dataclass
¶
Bases: Primitive
rectangle(plane, cx,cy,cz, w,h) — filled (closed) rectangle.
Source code in src/mccode_antlr/display/primitives.py
Box
dataclass
¶
Bases: Primitive
box(cx,cy,cz, xw,yh,zd[, thickness[, nx,ny,nz]]) — rectangular box.
The new McCode overhaul adds an optional thickness (hollow-wall depth) and an orientation normal (nx, ny, nz). When thickness is zero or absent the box is rendered as 12 wire edges, otherwise a second inner box is also drawn. The normal is currently used only by the 3-D renderer; the wire representation always uses the legacy axis-aligned form.
Source code in src/mccode_antlr/display/primitives.py
Sphere
dataclass
¶
Bases: Primitive
sphere(cx,cy,cz, r) — sphere rendered as three great circles.
Source code in src/mccode_antlr/display/primitives.py
Cylinder
dataclass
¶
Bases: Primitive
cylinder(cx,cy,cz, r,h[, thickness[, nx,ny,nz]]) — cylinder.
The new McCode overhaul adds an optional thickness for hollow cylinders. The axis orientation (nx, ny, nz) was already supported.
Source code in src/mccode_antlr/display/primitives.py
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 | |
Cone
dataclass
¶
Bases: Primitive
cone(cx,cy,cz, r,h[, nx,ny,nz]) — cone.
Source code in src/mccode_antlr/display/primitives.py
CircleNormal
dataclass
¶
Bases: Primitive
Circle(x,y,z,r,nx,ny,nz) / new_circle(…) — circle with arbitrary normal.
Unlike :class:Circle, the plane is specified by a normal vector rather than
a plane string. Corresponds to mcdis_Circle / mcdis_new_circle in C.
Source code in src/mccode_antlr/display/primitives.py
Disc
dataclass
¶
Bases: Primitive
disc(x,y,z,r,nx,ny,nz) — filled disc with an arbitrary normal.
Corresponds to mcdis_disc in C. Wire representation is the perimeter
circle; mesh representation is a fan-triangulated flat disc.
Source code in src/mccode_antlr/display/primitives.py
Annulus
dataclass
¶
Bases: Primitive
annulus(x,y,z,r_outer,r_inner,nx,ny,nz) — annular disc with arbitrary normal.
Corresponds to mcdis_annulus in C. Wire representation is two concentric
circles; mesh representation is a ring of quads.
Source code in src/mccode_antlr/display/primitives.py
Polygon
dataclass
¶
Bases: Primitive
polygon(count, x1,y1,z1,…) — closed flat polygon.
Corresponds to mcdis_polygon in C. Wire representation closes the path;
mesh representation is fan-triangulated from the centroid.
Source code in src/mccode_antlr/display/primitives.py
Polyhedron
dataclass
¶
Bases: Primitive
polyhedron(json_str) — 3-D polyhedron defined by a JSON string.
The JSON format produced by mcdis_polygon (and usable directly) is::
{ "vertices": [[x,y,z], ...],
"faces": [{"face": [i, j, k]}, ...] }
Corresponds to mcdis_polyhedron in C.
Source code in src/mccode_antlr/display/primitives.py
ConditionalBlock
dataclass
¶
A group of primitives guarded by a C if condition expression.
Source code in src/mccode_antlr/display/primitives.py
LoopBlock
dataclass
¶
A for/while loop containing display primitives (not yet unrolled).
Source code in src/mccode_antlr/display/primitives.py
Renderers¶
matplotlib (zero new dependencies)¶
mccode_antlr.display.render.matplotlib.plot_geometry(geometry, ax=None, colors=None, *, show_labels=True, label_offset=0.02, linewidth=1.0, alpha=1.0)
¶
Draw instrument geometry using matplotlib's 3-D axes.
Parameters¶
geometry:
Output from :meth:~mccode_antlr.display.InstrumentDisplay.to_polylines
— a dict mapping component names to lists of (N, 3) numpy arrays.
ax:
An existing Axes3D instance to draw onto. If None a new
figure and axes are created.
colors:
Optional mapping from component name to a matplotlib colour spec.
Components not present in this dict receive auto-assigned colours.
show_labels:
If True (default) annotate each component with its name at the
centroid of its geometry.
label_offset:
Fractional offset applied to the label position (relative to the
overall scene bounding box diagonal).
linewidth:
Line width for all polylines.
alpha:
Opacity for all lines.
Returns¶
(fig, ax): The matplotlib Figure and Axes3D objects.
Source code in src/mccode_antlr/display/render/matplotlib.py
WebGL via pythreejs / K3D (optional)¶
mccode_antlr.display.render.threejs.show_geometry(geometry, instrument_display=None, *, backend='auto', use_mesh=True, params=None, width=800, height=600, background='#111111', opacity=0.6)
¶
Display instrument geometry in a Jupyter notebook using WebGL.
Parameters¶
geometry:
Output from :meth:~mccode_antlr.display.InstrumentDisplay.to_polylines.
instrument_display:
The :class:~mccode_antlr.display.InstrumentDisplay instance. When
provided and use_mesh is True, solid surface meshes are drawn.
backend:
'pythreejs', 'k3d', or 'auto' (tries pythreejs first).
use_mesh:
If True (default) and instrument_display is supplied, solid
surface meshes are drawn alongside the wire representation.
params:
Parameter dict forwarded to to_mesh; defaults to {}.
width, height:
Widget dimensions in pixels.
background:
Background colour (CSS colour string, used by pythreejs backend).
opacity:
Opacity for mesh surfaces.
Returns¶
widget
An ipywidget renderable in a Jupyter cell. Call display(widget)
or simply return it as the last expression in a cell.