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
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 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | |
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), onto which the box's local y axis is
rotated by the smallest rotation. A thickness > 0 adds a closed inner cavity
xw-2t × yh-2t × zd-2t with the same centre and orientation, drawn only when
all three are positive, as mcdis_box in McCode's mccode-r.c.
Source code in src/mccode_antlr/display/primitives.py
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 | |
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: a
closed inner cavity of radius r-t and height h-2t, drawn only when both
are positive, as mcdis_cylinder in McCode's mccode-r.c.
The axis orientation (nx, ny, nz) was already supported.
Source code in src/mccode_antlr/display/primitives.py
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 | |
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,thickness,nx,ny,nz) — annular disc with arbitrary normal.
Corresponds to mcdis_annulus in C. thickness is the ring width, as
McStas and McXtrace Annulus.comp pass it, so the inner radius is
max(0, r_outer - thickness). 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.