nexus API Reference
A complete, self-contained specification of the nexus scripting API. It is written to be precise enough for an external developer — or an AI code agent — to author a correct script from scratch without seeing the application. For a gentler introduction, start with Writing Scripts.
Table of contents
- 1. Execution model
- 2. Signal types
- 3. Declarations
- 4. Reading signals
- 5. Writing results
- 6. Annotations
- 7. 4D-STEM scans
- 8. Authoring rules (for static parsing)
- 9. Worked examples
- 9.1
0Dts→0Dts(moving average) - 9.2
2Dts→2Dts(per-frame image transform) - 9.3
1Dts→1Dts(scale spectra, preserve channels) - 9.4
2Dts→0Dts(reduce a stack to a trace) - 9.5 Static
1Doutput (histogram) - 9.6 Custom axes on an output (
2Dtsingle image, with a calibrated time axis on a derived trace) - 9.7
4D→1D(radial profile of the mean pattern)
- 9.1
- 10. Constraints & gotchas
- 11. Quick reference card
1. Execution model
A script is a plain Python program that runs out of process in a managed virtual environment. Understanding how it is executed removes most surprises:
- One module, top to bottom. The whole script is
compile()d andexec()d once per run. There is no entry-point function to define; code at module level runs in order. __name__is"__nexus_script__", not"__main__". Aif __name__ == "__main__":guard will therefore never execute. Do not use one.import nexusis required to reach the API. NumPy and SciPy are available by default (import numpy as np,import scipy); other packages must be installed into the environment first (see Python Environment).print()is your debug channel. Everything written tostdoutandstderris captured and shown in the Output panel below the editor. This is the primary debugging channel.- Exceptions abort the run. An uncaught exception stops execution; its full traceback is shown in the Output panel. Any outputs produced by
set_signalbefore the exception are still stored (partial results), so guard against half-written output sets if that matters to you. - The worker is warm and reused across runs, but module state does not persist between runs in a way you should rely on: always re-declare and re-read everything at the top of the script. The process is killed and respawned on timeout, cancel, or crash.
- The timeout is an idle deadline, not a whole-run budget. While a script runs the worker sends a heartbeat roughly once a second from a background thread, and the deadline resets on each one. A run whose heartbeat stays silent for the whole window (default 120 seconds, configurable by the operator via
NEXUS_SCRIPT_TIMEOUT_SECS) is treated as stuck and ended — with one exception on Windows and Linux: there the host also measures the CPU time the worker’s processes used over that window, and lets the run continue if it used at least a tenth of one CPU core across it. That is what keeps a single long C call that holds the GIL alive —sum(range(10**12)), one enormous NumPy or SciPy operation — which starves the heartbeat thread but keeps a core busy. On other platforms only the heartbeat counts, so a silent window always ends the run. A native call that stays below that tenth of a core is ended too: one blocked on something that never arrives, but also one that is throttled, or mostly waiting on disk, the network or a lock. Python code that keeps the heartbeat flowing is never ended by the timeout however long it takes — use the Stop control to cancel a run yourself. Treat the CPU check as a safety net rather than something to rely on: over large data, loop in chunks andprintprogress as you go, so the heartbeat keeps flowing and the Output panel shows the run moving. - Full privileges. Scripts run with the same file-system and network access as the application. There is no sandbox. Only run scripts you trust.
Canonical script skeleton
import numpy as np
import nexus
# 1. Declare what the script needs (these render as UI controls).
params = nexus.add_parameters({ ... })
inputs = nexus.add_inputs({ ... })
outputs = nexus.add_outputs({ ... })
# 2. Read bound input signals.
sig = nexus.get_signal(inputs["src"])
data = sig.get_data()
# 3. Compute.
result = data * params["gain"]
# 4. Write one or more result signals.
nexus.set_signal(outputs["result"], result,
units=sig.metadata.get("units", ""),
metadata=sig.metadata,
axes=sig.axes)
The three add_* calls are also parsed statically (as text) by the application to build the UI, so keep them as literal dictionary calls near the top — see §8 Authoring rules.
2. Signal types
A “signal” is a numeric array with a type string that fixes its dimensionality and whether it varies over time. The type governs the shape returned by get_data() and the shape/metadata you must supply to set_signal(). §2.1 and §2.2 below explain what each type is and how its array is constructed; for the application-wide concept (how imported data is classified and which viewer it opens in) see Signal Types.
Only the seven types below are supported — every one has a panel that can display it. Do not read or produce any other type; a signal Nexus cannot display is not useful as a script result.
| Type | Meaning | get_data() shape |
Displayed by |
|---|---|---|---|
0Dts |
Scalar value vs time (a trace) | (T,) |
Time Series; Scatter (two 0Dts) |
1Dts |
Spectrum vs time | (T, channels) |
Spectrogram; Spectrum if single snapshot (T == 1) |
2Dts |
Image stack vs time | (T, height, width) |
Image |
2Dt |
Single time-stamped image | (1, height, width) as an input |
Image |
2D |
Static image | (1, height, width) as an input |
Image |
1D |
Static 1-D array (spectrum / histogram) | (N,) |
Spectrum |
1Dt |
Single time-stamped spectrum (niche; read as 1Dts) |
(1, channels) |
Spectrum |
4D, 4Dt, 4Dts |
A 4D-STEM scan: a diffraction pattern at every scan position (input only; see §7) | not loaded whole — read patterns on demand | 4D STEM |
Notes for agents:
- The
tssuffix = time series (many frames/points over time); thetsuffix is time-stamped; the no-suffix forms are static (no timeline placement). All three variants of the 2-D image family (2Dts,2Dt,2D) render in the Image panel. - Reading a 2-D input is normalised to
2Dts. The 2-D image family shares one internal storage form, so any bound 2-D input — whether the app labels it2D,2Dt, or2Dts— is presented to your script assignal_type == "2Dts", andget_data()always returns a 3-D(T, H, W)stack (a single image is simplyT == 1). Treat 2-D inputs uniformly as2Dtsand iterate frames withget_frame_count()/get_frame(i); the2Dt/2Ddistinction only matters when you write an output (see §2.2). 1Dis deliberately not a time series — use it for histograms/static spectra; it renders in the Spectrum panel.1Dtis a single time-stamped spectrum — it renders in the Spectrum panel but is a niche middle-ground: prefer1Dfor a static spectrum or1Dtsfor a series. On read, a1Dtinput is delivered to your script as1Dts(its storage form).- The scalar
0Dt/0Dtypes have no display panel and are therefore out of scope. Emit a scalar result as0Dts. - A 4D-STEM scan (
4D, a timed4Dt, a series4Dts) can be bound as an input but never produced: its patterns are read on demand (§7), and what a script makes of them is an image, a spectrum or a trace of one of the types above. Writing one fails the run:set_signalraises for a4D,4Dtor4Dtstype, or for a NumPy array of four or more dimensions that is not a2Dtsstack with itswidthandheightgiven, and that output is not stored. The check reads the array’sshape, so it does not see a nested Python list; pass NumPy arrays. Write patterns you computed as a2Dtsstack of shape(frames, height, width)instead. - When you write an output, the type is resolved by the rules in §5.2.
2.1 The shared data model
Every signal is built from three ingredients. Understanding them makes the per-type rules below obvious:
- A numeric array. Internally the data is always a flat 1-D list of 64-bit floats; the type plus the
width/height/channelsyou declare tell Nexus how to fold it back into frames, spectra, or points. Arrays are interpreted in row-major (C) order — exactly how NumPy flattens, so passing a correctly-shaped NumPy array “just works”. For an image, that means values run left-to-right along each row, top row first (index = y * width + x). For a stack, frames/spectra are laid end to end (index = t * frame_size + …). - Timestamps (
times): one value in seconds per point/frame. There are three tiers:- Time-series (
0Dts/1Dts/2Dts) — a timestamp per point/frame and a navigable Time axis; they sit on the shared timeline. - Single-event (
2Dt/1Dt) — exactly one timestamp for timeline placement, but no navigable Time axis (you scrub a series, not a lone event). - Static (
2D/1D) — no time dimension at all.
When you omit
times,set_signalinherits it from a matching input (else spreads it over the first input’s time span, or0,1,2,…with no input) for the time-series and single-event tiers; static outputs get none (see §5.3). Pass explicittimes(orfps) whenever the result has a different number of frames from its input, or needs real (or non-uniform) values. - Time-series (
- Axes: a descriptor per dimension —
{name, units, scale, offset, size, navigate}.scale/offsetcalibrate index → physical units (e.g. pixel size in nm, or channel → energy in eV:value = offset + index*scale).navigate: truemarks the dimension you scrub through (time);navigate: falsemarks a data dimension within a frame (spatial X/Y, or spectral channel). You normally propagate an input’s.axesunchanged; supply your own only when you create a new dimension.
2.2 Each type in detail
0Dts — scalar vs time (a “trace”).
One number per time point: temperature, pressure, mean intensity over time. Array is 1-D (T,) with a matching times of length T. Has a single navigable Time axis. This is the default output type and the target for any reduction of a richer signal (e.g. mean-per-frame of a 2Dts stack).
nexus.set_signal(out["trace"], values, units="°C") # times: see §5.3
1Dts — spectrum vs time.
One full spectrum per time point (e.g. an EELS or EDS series). Array is 2-D (T, channels); flattened row-major so each spectrum’s channels are contiguous. Requires channels on output. Axes: navigable Time + a non-navigable Channel axis (calibrate it via axes= for an energy/wavelength scale). Renders as a Spectrogram; a single-snapshot series (T == 1) can also open in the Spectrum panel.
nexus.set_signal(out["eels"], spectra, signal_type="1Dts", channels=sig.channels)
2Dts — image stack vs time (video).
One 2-D image per time point. Array is 3-D (T, height, width); flattened row-major (t*H*W + y*W + x). Requires width and height. Axes: navigable Time + non-navigable Y and X spatial axes (calibrate with pixel size). This is the workhorse type for in-situ image series.
nexus.set_signal(out["stack"], frames, signal_type="2Dts",
width=sig.width, height=sig.height, axes=sig.axes)
2Dt — a single time-stamped image.
One image that still belongs at a moment on the timeline (e.g. a single STEM scan, or any single image from a DM or TIFF file). Nexus stores it as one [height, width] image with one timestamp and no navigable time axis. Pass a 2-D (H, W) array with signal_type="2Dt"; a (1, H, W) array is accepted too. Renders in the Image panel.
As an input, every image reads as a stack. A 2D, 2Dt or 2Dts input reports signal_type == "2Dts", and get_data() returns (T, height, width), with T == 1 and get_frame_count() == 1 for a single image. Use get_frame(0) for the (H, W) frame. A script input declared "2Dts" therefore accepts a single image.
nexus.set_signal(out["img"], frame, signal_type="2Dt",
width=w, height=h) # frame is (H, W)
2D — a static image.
An image with no timeline placement (a mask, a computed map, an FFT of one frame). Array is 2-D (height, width); spatial Y/X axes only — no times, no navigable axis. set_signal does not fabricate timestamps for 2D. Requires width and height.
nexus.set_signal(out["mask"], mask2d, signal_type="2D", width=w, height=h)
1D — a static 1-D array.
A single spectrum, histogram, or profile with no time dimension. Array is 1-D (N,); the value count is the channel count. It is not a time series — set_signal does not fabricate times, it carries only a channel axis, and timeline-bound tools skip it. Renders in the Spectrum panel.
counts, _ = np.histogram(data, bins=64)
nexus.set_signal(out["hist"], counts.astype(np.float64), signal_type="1D", units="count")
1Dt — a single time-stamped spectrum (niche).
One spectrum that carries a single timestamp — a middle-ground between a static 1D and a 1Dts series. You write a single spectrum (channels,) and declare channels; it renders in the Spectrum panel. It carries one timestamp (inherited from a matching input, or synthesised, when you omit times) but has no navigable Time axis. On read it is delivered as 1Dts with a single row (get_data() → (1, channels), i.e. T == 1). Prefer 1D (static spectrum) or 1Dts (series) unless you specifically need a lone time-stamped spectrum.
nexus.set_signal(out["spec"], spectrum, signal_type="1Dt", channels=len(spectrum))
Choosing an output type: does the result have one value per timeline moment? → 0Dts. A spectrum per moment? → 1Dts. An image per moment? → 2Dts. A single time-stamped image? → 2Dt. A calculated image with no time? → 2D. A histogram/profile/single spectrum? → 1D (or 1Dt for the rare lone time-stamped spectrum).
3. Declarations
Three functions declare the script’s interface. Each takes a dict of definitions keyed by an internal name and returns a dict of resolved values keyed by the same names. Declare them at the top of the script.
3.1 nexus.add_parameters(defs) → dict
Returns {name: value} for each declared parameter, using the value the user set in the UI (or the declared default). Only names present in the resolved context are returned; unknown names are omitted.
Each definition dict accepts:
| Key | Applies to | Meaning |
|---|---|---|
type |
all (required) | Control/value type — see the table below |
title |
all | Label shown in the UI (defaults to the name) |
default |
all | Initial value; also the value if the control is untouched |
min |
numeric | Minimum (spinner/slider bound) |
max |
numeric | Maximum |
step |
numeric | Increment |
unit |
numeric | Unit label shown beside the field (display only) |
options |
enum |
List of allowed string choices |
Parameter types and the Python value you receive:
type |
UI control | Python value |
|---|---|---|
number |
Number field (min/max/step/unit) |
int or float |
string |
Text field | str |
boolean |
Toggle | bool |
enum |
Dropdown of options |
str (one of options) |
color |
Colour picker | str, hex e.g. "#4ECDC4" |
intensity |
Pipette — sample a pixel value | float |
timestamp |
Clock — pick a time from the timeline, a graph, or a 2-D viewer | float (seconds) |
coordinate |
Crosshair — pick a 2-D point | str "x,y" (pixel coords) |
roi |
Dropdown of any annotation | str (annotation id) |
roi_rectangle |
Dropdown of rectangles | str (annotation id) |
roi_circle |
Dropdown of circles | str (annotation id) |
roi_line |
Dropdown of lines/arrows | str (annotation id) |
roi_point |
Dropdown of points | str (annotation id) |
Which of these to reach for is a question about what the value means, not what shape it has in Python — see Choosing the right type.
coordinate returns a string "x,y". Parse it: x, y = (int(float(v)) for v in params["centre"].split(",")). ROI parameters return the annotation id string; resolve geometry with get_annotation. Booleans are Python True/False — note the capitalisation in default.
A picked timestamp (from the timeline, a graph, or a 2-D viewer), or a typed wall-clock date, is absolute Unix-epoch seconds — a different clock from sig.timestamps, which are on the signal’s own relative scale. Comparing a picked value directly against sig.timestamps matches nothing. Convert it first — see §5.3 Timestamp resolution for the picked_time_to_relative helper.
params = nexus.add_parameters({
"window": {"type": "number", "title": "Window", "default": 5, "min": 1, "max": 99, "step": 1},
"method": {"type": "enum", "title": "Method", "default": "mean", "options": ["mean", "median"]},
"invert": {"type": "boolean", "title": "Invert", "default": False},
"centre": {"type": "coordinate", "title": "Beam centre", "default": "0,0"},
})
window = int(params["window"])
3.2 nexus.add_inputs(defs) → dict
Returns {name: signal_id} — the id of the signal the user bound (an empty string "" if unbound). Pass the id to get_signal.
| Key | Meaning |
|---|---|
title |
Label in the UI |
signal_type |
Restricts which signals can be bound (e.g. "2Dts"); optional |
default |
Pre-bound signal id, usually "" |
optional |
True lets the script run with this input unbound; default False |
inputs = nexus.add_inputs({
"src": {"title": "Source", "signal_type": "0Dts", "default": ""},
})
A script will not run until every required input is bound. Type filtering is by dimensional base, so 2Dt/2D/2Dts are mutually compatible for binding purposes.
An input declared "optional": True may be left unbound; its value is then "". Check for that before reading it, because get_signal("") raises KeyError:
inputs = nexus.add_inputs({
"src": {"title": "Source", "signal_type": "2Dts", "default": ""},
"background": {"title": "Background", "signal_type": "2Dts", "default": "", "optional": True},
})
bg = nexus.get_signal(inputs["background"]).get_data() if inputs["background"] else None
3.3 nexus.add_outputs(defs) → dict
Returns {name: chosen_output_name} — the (user-editable) display name for each output. Pass that value as the first argument to set_signal.
| Key | Meaning |
|---|---|
title |
Label in the UI |
signal_type |
Declares the output’s type; applied by set_signal unless you override it |
default |
Default output name |
outputs = nexus.add_outputs({
"result": {"title": "Result", "signal_type": "0Dts", "default": "smoothed"},
})
The declared signal_type here is authoritative for the output unless the set_signal call passes its own signal_type= (see §5.2).
4. Reading signals
nexus.get_signal(signal_id) → NexusSignal
Returns a read-only proxy over the bound input signal. Raises KeyError if signal_id is unknown (e.g. an unbound optional input passed as "" — see §3.2).
Attributes:
| Attribute | Type | Description |
|---|---|---|
.signal_type |
str |
The type string. Any 2-D input reports "2Dts" (see the normalisation note in §2) |
.timestamps |
list |
Time value per frame/point (seconds, relative to the experiment start) — the way to read a signal’s timing |
.metadata |
dict |
Metadata; always includes signal_type, units, name, and — when the source carried it — experiment_start_unix_time (acquisition start in absolute Unix seconds; legacy fallback key experiment_start_unix), used to convert a picked timestamp parameter to relative time (see §5.3). Carries no raw time arrays (timestamps, frame_times, timeMinSec, timeMaxSec) — use .timestamps |
.time_offset |
float |
The user’s sync offset in seconds: the timeline draws the signal at experiment_start_unix_time + timestamps + time_offset. 0.0 when never synced. Read-only — Kelvin’s SET_TIME_OFFSET or the sync tool changes it |
.spatial_offset |
dict |
The user’s spatial alignment of an image, {"x", "y"} in the signal’s own axis units, added to the spatial axes’ offset. Zeros when never set. Read-only — Kelvin’s SET_SPATIAL_OFFSET or the Alignment fields change it |
.axes |
list |
Axis descriptors — dicts of name, units, scale, offset, size, navigate |
.width |
int |
Frame width (2-D types) |
.height |
int |
Frame height (2-D types) |
.channels |
int |
Channel count (1-D spectrum types) |
.pixel_size |
dict |
{"x", "y", "units", "offset_x", "offset_y"} from spatial axes (2Dts only). The offsets are the image’s origin in those units — where it sits on the sample, not just how big a pixel is |
Methods:
| Method | Returns | Valid for |
|---|---|---|
.get_data() |
Whole array (shape per §2) | all |
.get_frame(i) |
One frame (height, width) |
2-D types |
.get_frame_count() |
Number of frames | 2-D types |
.get_spectrum(i) |
One spectrum (channels,) |
1-D types |
.get_spectrum_count() |
Number of spectra | 1-D types |
.crop(x, y, w, h) |
A CroppedSignal — see below |
2-D types |
get_frame / get_spectrum raise IndexError on an out-of-range index. Array results are NumPy float64 arrays when NumPy is available (it is, by default), otherwise plain nested lists.
sig = nexus.get_signal(inputs["img"]) # a 2Dts stack
stack = sig.get_data() # (T, H, W) float64
frame0 = sig.get_frame(0) # (H, W)
print(sig.width, sig.height, sig.get_frame_count())
px = sig.pixel_size # {"x": 0.1, "y": 0.1, "units": "nm"}
Reading data is read-only — mutating the returned array does not change the source signal. Produce changes as new outputs via set_signal.
sig.crop(x, y, width, height) → CroppedSignal
Cuts a rectangle out of every frame and derives the output’s axes from the parent’s, so the result knows where on the sample it came from:
offset_child = offset_parent + start_index * scale_parent
scale_child = scale_parent
That offset is what places a crop correctly when it is overlaid on the original — without it the
crop is drawn at the parent’s top-left corner. x/y are the top-left corner in pixels of the
signal’s own grid; the rectangle is clamped to the frame, so a crop running off the edge is
trimmed rather than an error. A rectangle entirely outside the frame (or of zero size) raises
ValueError. The navigate (time) axis and the timestamps pass through untouched — a crop selects
pixels, not frames.
The returned CroppedSignal carries .data, .axes, .timestamps, .width, .height and
.units. Hand it straight to set_signal with source=:
sig = nexus.get_signal(inputs["img"])
region = sig.crop(100, 50, 256, 256)
nexus.set_signal(outputs["crop"], region.data, signal_type="2Dts", source=region)
5. Writing results
nexus.set_signal(name, data, **kwargs) → None
Produces one output signal. Call it once per output; multiple calls in a run produce multiple result signals. name should be the value from add_outputs (its resolved display name), though any string works.
data may be a NumPy array, a Python list/tuple, or any nesting thereof. It is flattened to a 1-D list of floats internally; the shape you declare (via signal_type + width/height/channels, or inferred from the array’s .shape) is what determines how it is reassembled. Data must be numeric — non-numeric values raise TypeError.
Keyword arguments:
| Keyword | Type | Purpose |
|---|---|---|
signal_type |
str |
Force the output type. Highest precedence. |
times |
list of float | Explicit timestamps, one per frame/point. |
fps |
float |
Evenly spaced timestamps at this frame rate, from the first timestamp of the source= signal, else of the first input the script declared that has timestamps (0 with neither). Time-series and single-event types only; not with times. |
units |
str |
Units string. |
width |
int |
Frame width (2-D output). |
height |
int |
Frame height (2-D output). |
channels |
int |
Channel count (1-D output). |
color |
str |
Suggested display colour (hex). |
metadata |
dict |
Extra metadata to attach (NumPy scalars/arrays are coerced to native). Time and display keys are reserved — see below. |
axes |
list of dict | Axis descriptors: name, units, scale, offset, size, navigate. |
source |
signal | A CroppedSignal or NexusSignal this output was derived from. Fills in axes, units and the dimensions that are not given explicitly, and times when the output has as many frames as the source (otherwise see §5.3). |
times= is the only channel for an output’s timestamps. The keys timestamps, frame_times, timeMinSec and timeMaxSec are owned by Nexus: they are ignored if you pass them in metadata= and always recomputed from the output’s own times (see §5.3). This is what makes metadata=sig.metadata safe — you propagate the source’s calibration without also inheriting the source’s timing, which would place your result at the wrong moment on the timeline.
Display keys are reserved too. display_min, display_max, display_trim_low_pct, display_trim_high_pct, the nested display block, and the per-frame containers per_frame_metadata, per_file_metadata and per_frame_metadata_indices (which carry the same display blocks one level down, addressed by the source’s frame count) are likewise ignored in metadata=, and for the same reason: they describe how the source was drawn. Your result’s values almost always live in a different numeric domain from the source’s raw detector counts — a 0-1 mask, a difference image, a normalised field — so the source’s contrast window would map every pixel to the bottom of the ramp and the image would render solid black. Dropping them lets the viewer auto-contrast from your result’s own pixels, which is what it already does for any signal that carries no display range. Together with the time keys above, this is what makes metadata=sig.metadata safe: you propagate the source’s calibration, not its presentation.
nexus.set_signal(outputs["result"], smoothed,
units=sig.metadata.get("units", ""),
metadata=sig.metadata, # propagate source metadata
axes=sig.axes) # propagate calibrated axes
5.1 Shape requirements per output type
To reassemble the flat values correctly you must ensure the shape is known — either declare it or let it be inferred from a NumPy array’s .shape:
2Dts/2Dt/2D— needswidthandheight. From a NumPy array these are inferred: a 3-D(T, H, W)gives frames +H,W; a 2-D(H, W)gives a single frame. Frame count =len(values) / (width*height).1Dts— needschannels. Inferred from a 2-D(T, channels)array. Spectra count =len(values) / channels.1Dt— a single spectrum; needschannels(the value count for one spectrum).1D— static; channel count is just the value count. Stored as a non-time-series array.0Dts— 1-D; no extra shape needed.
These describe how a flat value list is reassembled once the type is known. Which type an undeclared output gets is decided separately, and a 2-D array does not become an image on its own — see §5.2.
5.2 Signal-type resolution (precedence)
When you call set_signal, the output type is decided in this order:
- Explicit
signal_type=kwarg — always wins. - Declared type from
add_outputs— used if you did not passsignal_type=. - Auto-detected from the array
.shape— only when neither of the above applies. Inference picks an image type only for a result that is actually shaped like an image:- 1-D array →
0Dts. - 2-D
(rows, cols)whererowsequals a bound input’s frame count → one row of values per frame:0Dtswhencols == 1, otherwise1Dtswithchannels = cols. This is whatnp.mean(frames, axis=(1,2))[:, None]and a per-frame(T, 2)drift vector produce. - 2-D array otherwise →
1Dtsif a bound input is1Dts(and none is2Dts); otherwise2Dtsif any bound input is2Dts. - 3-D
(T, H, W)→2Dts(withheight,widthfromshape[1],shape[2]), except a degenerate(T, 1, 1)— whatkeepdims=Truegives for one scalar per frame — which is0Dts.
- 1-D array →
- Fallback
0Dts.
Two rules break the ties. An array whose shape matches a bound input’s frame size (height×width) is an image even when its row count also happens to equal the frame count — so the mean image of a stack exactly as long as its frames are tall stays 2Dts. And your own dimensions outrank the array’s shape: passing both width= and height= says how to reassemble a frame, which nothing but an image type does, so it selects 2Dts whatever the bound inputs are. Passing only one is not enough to name a type, but is still enough to stand the two per-frame rules down.
For anything non-trivial, be explicit: declare signal_type in add_outputs and/or pass signal_type=, width=, height=, channels=. Do not rely on inference for image/spectrum outputs.
add_outputs declarations are keyed by the bound output name — the name the user chose in the panel, not the key in your add_outputs dict. Calling set_signal("my_result", …) with a string literal that differs from it skips your own declaration and falls through to inference above. Always pass the value add_outputs returned: out = nexus.add_outputs({...}) then nexus.set_signal(out["result"], …). set_signal prints a warning to the Output panel when the name it is given is not one of the declared outputs.
5.3 Timestamp resolution
Timestamp handling applies to the time-series types (0Dts/1Dts/2Dts) and the single-event types (2Dt/1Dt) — see the three tiers in §2.1. When you do not pass times= for one of them:
- The number of points/frames is computed from the flat values and the shape.
- A
source=signal with timestamps is used first: its times are taken when the counts match, and otherwise it is the time span in step 3. Without one, Nexus looks through the bound input signals for one whose timestamp count matches, and inherits its timestamps — so the result lines up on the timeline with its source. - If no input matches, timestamps are synthesised on the time span of the
source=signal, or else of the first input the script declared inadd_inputsthat has timestamps, with a warning in the Output panel:- fewer frames than that input: each frame takes the mean time of its share of the input’s frames, so averaging every n frames gives each output frame the mean time of the n it averages;
- more frames: spread evenly from the input’s first to its last timestamp;
- one frame: the input’s first timestamp;
- an input with no duration (a single frame, or every frame at one time): one second apart from its start.
With no timed input at all, they are
0, 1, 2, …(one second apart).
fps= replaces steps 2 and 3: the result’s frames are 1/fps seconds apart, starting at the first timestamp of the source= signal, else of the first input the script declared that has timestamps (0 with neither). A result that changes the number of frames should still pass its own times= when it knows them — the fallback is a safety net, not a substitute:
t = np.asarray(sig.timestamps)
k = len(t) // n # averaging every n frames
nexus.set_signal(out["avg"], frames[:k * n].reshape(k, n, *frames.shape[1:]).mean(axis=1),
times=t[:k * n].reshape(k, n).mean(axis=1))
nexus.set_signal(out["every_kth"], frames[::step], times=t[::step]) # every step-th frame
A single-event output (2Dt/1Dt) gets exactly one timestamp (step 2 or 3 above) but no navigable Time axis. Static outputs (2D/1D) are given no timestamps at all — set_signal leaves their times unset. For irregular (non-uniform) spacing on a time-series result, pass times= explicitly — it is preserved verbatim and drives per-frame positioning.
Timestamps are seconds relative to the experiment start, which the result inherits from its input — never absolute Unix time. Passing times= from a different clock (or smuggling an input’s raw time arrays through metadata=, which is why those keys are reserved) would place the result an entire epoch away from its source on the timeline.
Picked timestamps are on a different clock
sig.timestamps are on the signal’s relative time scale, but a timestamp parameter the user picked — off the timeline, a graph, or a 2-D viewer — or typed as a wall-clock date, is absolute Unix-epoch seconds (~1.6e9). (A timestamp typed as an elapsed duration like MM:SS is already relative.) So comparing a picked value directly against sig.timestamps silently matches nothing. Put it on the same scale by subtracting the signal’s acquisition start (experiment_start_unix_time in .metadata) — the same offset the backend removes when it normalises a signal’s times — and, when the user has synced the signal, its time_offset, since the timeline draws it that much later:
EPOCH_2000 = 946684800.0 # values >= this are absolute Unix seconds (2000-01-01)
def picked_time_to_relative(t_picked, sig):
"""Align a picked `timestamp` parameter with sig.timestamps (relative seconds).
Absolute (picked / typed-date) values are converted; typed-elapsed values are
already relative. Returns None when it cannot be resolved."""
if t_picked is None or t_picked <= 0:
return None
if t_picked < EPOCH_2000:
return float(t_picked) # already relative (typed elapsed, e.g. MM:SS)
start = (sig.metadata.get("experiment_start_unix_time")
or sig.metadata.get("experiment_start_unix"))
# A synced signal is drawn time_offset later than its own clock (NXE-815), so a time
# picked off the timeline is shifted by it too.
return float(t_picked) - float(start) - sig.time_offset if start is not None else None
5.4 The produced signal
Each output becomes a new signal in a script-run folder in the workspace. Its id is derived as {script_id}_{run_id}_{name} (name lower-cased, spaces → underscores); its source metadata is set to "script". Re-running a script in place overwrites the same run’s outputs — see Re-running Scripts.
6. Annotations
nexus.get_annotation(annotation_id) → dict
Resolves a drawn annotation (typically obtained from an ROI parameter) to a geometry dict. Raises KeyError if the id is unknown.
Always present:
| Key | Meaning |
|---|---|
id |
Annotation id |
type |
Raw type: rectangle, circle, ellipse, line, arrow, point |
roi_type |
Normalised: roi_rectangle, roi_circle, roi_line, roi_point |
name |
User label (may be empty) |
source_signal_id |
The signal the annotation was drawn on |
color |
Colour string |
x1, y1, x2, y2 |
Raw corner coordinates (pixels), always available |
Shape-specific geometry (added on top):
| Shape | Extra keys |
|---|---|
| Rectangle | center_x, center_y, width, height, rotation |
| Circle/Ellipse | center_x, center_y, radius_x, radius_y, rotation |
| Line/Arrow | start_x, start_y, end_x, end_y |
| Point | x, y |
Coordinates are in pixels; rotation is in degrees.
params = nexus.add_parameters({"region": {"type": "roi_rectangle", "title": "Region", "default": ""}})
inputs = nexus.add_inputs({"img": {"title": "Image", "signal_type": "2Dts", "default": ""}})
roi = nexus.get_annotation(params["region"])
x0 = int(roi["center_x"] - roi["width"] / 2)
y0 = int(roi["center_y"] - roi["height"] / 2)
frame = nexus.get_signal(inputs["img"]).get_frame(0)
patch = frame[y0:y0 + int(roi["height"]), x0:x0 + int(roi["width"])]
nexus.set_signal("region_mean", [float(patch.mean())])
7. 4D-STEM scans
A 4D-STEM acquisition (Merlin, EMPAD, K2, ARINA, DM4, raw) is a scan of rows × cols positions with a diffraction pattern of height × width pixels at each — gigabytes that no script should load whole. Bind one as an input (signal_type: "4D" accepts 4D, 4Dt and 4Dts) and read what you need: one pattern, a block, or the mean over an area. Each read is answered by Nexus from the acquisition on disk while the script runs, so even a 17 GB scan is cheap to query.
Reading a scan
| Attribute / method | Meaning |
|---|---|
.signal_type |
"4D", "4Dt" (timed) or "4Dts" (a series of scans) |
.scan_shape |
(rows, cols) scan positions |
.pattern_shape |
(height, width) pattern pixels |
.scans |
Scans in a series; 1 for a single scan |
.shape |
(scans, rows, cols, height, width) |
.metadata |
Includes scan_rows, scan_cols, pattern_width, pattern_height, dwell_s, the acquisition’s own keys, and fourd_detectors (below) |
.axes |
Scan Y, Scan X (navigate) and Q Y, Q X — calibrated when the user set a pixel size in the panel |
.get_pattern(row, col, scan=0) |
One pattern as (height, width) |
.get_patterns(first, count) |
count consecutive patterns (row-major over the scan; a series stacks its scans) as (count, height, width) |
.get_block(row0, col0, rows, cols, scan=0) |
A rectangle of patterns as (rows, cols, height, width) |
.get_mean_pattern(x0, y0, x1, y1, scan=0) |
The mean pattern over scan columns x0..x1 and rows y0..y1 (inclusive) as (height, width), summed by Nexus |
.detectors |
The scan’s virtual detectors as the panel shows them (a list of dicts; see below) |
get_data(), get_frame() and crop() raise on a 4D input: there is no whole array to return.
Running the 4D tools
The panel’s reductions are available to a script with the panel’s own parameters:
images = nexus.run_tool("fourd_overview", sig) # sum, CoM x/y/magnitude, mean and max pattern
images = nexus.run_tool("fourd_virtual_detector", sig,
center_x=-1, center_y=-1, # -1: the pattern centre
inner_radius=0, outer_radius=40,
mode="intensity", segments=1, azimuth_deg=0, icom_highpass=0)
images = nexus.run_tool("fourd_virtual_diffraction", sig, x0=0, y0=0, x1=-1, y1=-1, mode="mean")
Each call returns a list of NexusSignals (2Dts images, one frame per scan of a series), each with metadata["fourd_kind"] naming it (sum, com_x, virtual_detector, dpc_x, icom, mean_pattern, …) and the scan’s or the pattern’s axes. They are ordinary inputs from there: img.get_frame(0), img.metadata, and nexus.set_signal(name, img.get_data(), signal_type="2Dts", source=img) to keep one as a result — source=img carries its axes, units and per-scan timestamps across, so the kept stack is still placed in time (or nexus.set_signal(name, img.get_frame(0), signal_type="2D", axes=img.axes) for one static image). A CoM or segmented detector also gives an icom image, the integrated centre of mass.
Detectors
sig.detectors is the list the panel’s Detectors section shows, each a dict with id, name, cx, cy (pattern pixels), inner, outer (radii in pattern pixels), mode ("intensity" or "com"), segments, azimuth (degrees) and icomHighpass. nexus.set_detectors(sig, detectors) replaces that list when the run ends; a detector without an id gets one. The panel picks the change up and the user applies the detectors as usual.
dets = sig.detectors
dets.append({"name": "ADF", "cx": 127.5, "cy": 127.5, "inner": 40, "outer": 100, "mode": "intensity"})
nexus.set_detectors(sig, dets)
A 4D input is bound like any other, but nothing is loaded for it up front: the first get_pattern reads from the acquisition. Prefer get_mean_pattern and run_tool over loops of get_pattern — they run in Rust over the whole scan at once.
8. Authoring rules (for static parsing)
The three add_* calls are parsed from the script text (not executed) to build the parameter/input/output UI. Follow these rules so parsing succeeds:
- Call each as a literal dict:
nexus.add_parameters({ ... }). Do not build the dict dynamically or spread a variable into it. - Use string keys for definition names, and keep each name a plain identifier — letters, digits, and underscores only (matching
\w+). Names containing hyphens, spaces, or dots (e.g."window-size","start point") are silently skipped by the parser, so their control never appears even though the script still runs. Use"window_size", not"window-size". - Keep values as literals the parser understands: strings in quotes, numbers,
True/False, andoptionsas a list of quoted strings. - Each parameter definition must have a
typefrom §3.1; definitions without a validtypeare ignored by the UI. - The declared
defaultvalues are read and written back into your script text when the user edits a control — so the script file is the single source of truth for current parameter values. Keepdefaultpresent.
At runtime the same add_* calls execute normally and return resolved values, so your computation reads from their return dicts as shown throughout.
9. Worked examples
9.1 0Dts → 0Dts (moving average)
import numpy as np
import nexus
params = nexus.add_parameters({"window": {"type": "number", "title": "Window", "default": 5, "min": 1, "max": 99, "step": 1}})
inputs = nexus.add_inputs({"signal": {"title": "Input", "signal_type": "0Dts", "default": ""}})
outputs = nexus.add_outputs({"smoothed": {"title": "Smoothed", "signal_type": "0Dts", "default": "smoothed"}})
sig = nexus.get_signal(inputs["signal"])
data = sig.get_data()
kernel = np.ones(int(params["window"])) / int(params["window"])
smoothed = np.convolve(data, kernel, mode="same")
nexus.set_signal(outputs["smoothed"], smoothed,
units=sig.metadata.get("units", ""),
metadata=sig.metadata, axes=sig.axes)
print(f"Smoothed {len(data)} points")
9.2 2Dts → 2Dts (per-frame image transform)
import numpy as np
import nexus
inputs = nexus.add_inputs({"image": {"title": "Stack", "signal_type": "2Dts", "default": ""}})
outputs = nexus.add_outputs({"inverted": {"title": "Inverted", "signal_type": "2Dts", "default": "inverted"}})
sig = nexus.get_signal(inputs["image"])
stack = sig.get_data() # (T, H, W)
out = stack.max() - stack # invert intensities
nexus.set_signal(outputs["inverted"], out,
signal_type="2Dts", width=sig.width, height=sig.height,
metadata=sig.metadata, axes=sig.axes)
9.3 1Dts → 1Dts (scale spectra, preserve channels)
import numpy as np
import nexus
inputs = nexus.add_inputs({"eels": {"title": "EELS", "signal_type": "1Dts", "default": ""}})
outputs = nexus.add_outputs({"scaled": {"title": "Scaled", "signal_type": "1Dts", "default": "scaled"}})
sig = nexus.get_signal(inputs["eels"])
nexus.set_signal(outputs["scaled"], sig.get_data() * 2.0,
signal_type="1Dts", channels=sig.channels)
9.4 2Dts → 0Dts (reduce a stack to a trace)
import numpy as np
import nexus
inputs = nexus.add_inputs({"image": {"title": "Stack", "signal_type": "2Dts", "default": ""}})
outputs = nexus.add_outputs({"mean": {"title": "Mean vs time", "signal_type": "0Dts", "default": "frame_mean"}})
sig = nexus.get_signal(inputs["image"])
means = [float(sig.get_frame(i).mean()) for i in range(sig.get_frame_count())]
# times inherited automatically from the 2Dts input (same frame count).
nexus.set_signal(outputs["mean"], means, units="intensity")
9.5 Static 1D output (histogram)
import numpy as np
import nexus
inputs = nexus.add_inputs({"signal": {"title": "Input", "signal_type": "0Dts", "default": ""}})
outputs = nexus.add_outputs({"hist": {"title": "Histogram", "signal_type": "1D", "default": "histogram"}})
data = nexus.get_signal(inputs["signal"]).get_data()
counts, _ = np.histogram(data, bins=64)
# 1D is static — no timeline placement, no times needed.
nexus.set_signal(outputs["hist"], counts.astype(np.float64), signal_type="1D", units="count")
9.6 Custom axes on an output (2Dt single image, with a calibrated time axis on a derived trace)
# A derived 0Dts trace with an explicit, calibrated time axis:
time_axis = {"name": "Time", "units": "s", "scale": 1e-5, "offset": 0.0, "size": len(values), "navigate": True}
nexus.set_signal(outputs["waveform"], values, units="nm", times=list(times), axes=[time_axis])
# A single 2Dt image: pass the (H, W) frame and say it is a 2Dt. Without signal_type a
# (1, H, W) array is inferred as a one-frame 2Dts stack.
nexus.set_signal(outputs["corrected"], corrected, signal_type="2Dt",
units=sig.metadata.get("units", ""), axes=sig.axes, metadata=sig.metadata)
9.7 4D → 1D (radial profile of the mean pattern)
import nexus
import numpy as np
inputs = nexus.add_inputs({"scan": {"title": "4D-STEM scan", "signal_type": "4D", "default": ""}})
outputs = nexus.add_outputs({"profile": {"title": "Radial profile", "signal_type": "1D", "default": "Radial profile"}})
sig = nexus.get_signal(inputs["scan"])
rows, cols = sig.scan_shape
mean = sig.get_mean_pattern(0, 0, cols - 1, rows - 1) # (height, width), summed by Nexus
h, w = mean.shape
yy, xx = np.indices((h, w))
r = np.hypot(xx - (w - 1) / 2, yy - (h - 1) / 2).astype(int) # pixel radius from the pattern centre
profile = np.bincount(r.ravel(), weights=mean.ravel()) / np.maximum(np.bincount(r.ravel()), 1)
q = next((a for a in sig.axes if a["name"] == "Q X"), None) # calibrated when the panel has a pixel size
scale, units = (q["scale"], q["units"]) if q else (1.0, "px")
nexus.set_signal(outputs["profile"], profile, signal_type="1D", units=sig.units,
axes=[{"name": "q", "units": units, "scale": scale, "offset": 0.0, "size": len(profile)}])
print(f"{rows}×{cols} scan: profile over {len(profile)} radii")
10. Constraints & gotchas
- Numeric arrays only.
set_signaldata is flattened to floats; strings/objects raiseTypeError. Encode categorical results numerically. - Declare shape for 1-D/2-D outputs. Do not rely on inference for
1Dts/1Dt/2Dts/2Dt— passchannelsorwidth+height(or a correctly-shaped NumPy array). - Name the type of a single-image output. With
signal_type="2Dt"(or"2D") both an(H, W)and a(1, H, W)array store one[H, W]image. Left to inference, a(1, H, W)array becomes a one-frame2Dtsstack, and an(H, W)array is an image only when its size is given or matches an input’s frame. if __name__ == "__main__":never runs — the module name is__nexus_script__.- Respect the timeout (120 s default, an idle deadline — see above). A run is ended when its heartbeat is silent for the whole window and — on Windows and Linux only — it also used less than a tenth of one CPU core over that window. Python loops keep the heartbeat flowing and one huge vectorised call keeps a core busy, so both run to completion on those platforms. What does get ended is a native call that blocks, or is throttled or waiting so it stays under that tenth of a core, and on other platforms any call that holds the GIL for the whole window. For long work, prefer chunks with a
printof progress per chunk over one enormous call: the heartbeat keeps flowing and the user sees it moving. - Required inputs must be bound before a run. An
optionalinput may arrive as""; check it before callingget_signal, which raisesKeyErroron"". - Metadata is propagated, not merged automatically — pass
metadata=(andaxes=) yourself to carry calibration onto the result. Merge with source using{**sig.metadata, "extra": ...}. - A derived output with no
axes=is uncalibrated. It falls back topixelsat scale 1.0, which makes it the wrong physical size next to its source — visibly so when it is used as an overlay. Passsource=sig(orsource=the crop) and the calibration comes across. - No persistent state between runs; re-declare and re-read at the top every time.
- Packages beyond NumPy and SciPy must be installed into the managed environment first; a
ModuleNotFoundErrortriggers an install prompt (see Python Environment).
11. Quick reference card
import nexus
# Declarations (literal dicts, near the top)
params = nexus.add_parameters({name: {type, title, default, min?, max?, step?, unit?, options?}}) -> {name: value}
inputs = nexus.add_inputs({name: {title, signal_type?, default, optional?}}) -> {name: signal_id}
outputs = nexus.add_outputs({name: {title, signal_type?, default}}) -> {name: out_name}
# Read
sig = nexus.get_signal(signal_id) # raises KeyError if unknown
sig.get_data() # 0Dts:(T,) 1Dts:(T,C) 2Dts:(T,H,W)
sig.get_frame(i) / sig.get_frame_count() # 2-D types
sig.get_spectrum(i) / sig.get_spectrum_count() # 1-D types
sig.timestamps, sig.metadata, sig.axes, sig.width, sig.height, sig.channels, sig.pixel_size
sig.crop(x, y, w, h) # -> CroppedSignal, axes placed at the crop
# Write (call once per output)
nexus.set_signal(name, data,
signal_type=?, times=?, units=?, width=?, height=?, channels=?,
color=?, metadata=?, axes=?, source=?, fps=?)
# Annotations
roi = nexus.get_annotation(annotation_id) # id/type/roi_type/name/color/x1..y2 + shape geometry
# 4D-STEM (input only; read on demand)
sig.scan_shape, sig.pattern_shape, sig.scans, sig.shape, sig.detectors
sig.get_pattern(row, col, scan=0) # (H, W)
sig.get_patterns(first, count) # (count, H, W)
sig.get_block(row0, col0, rows, cols, scan=0) # (rows, cols, H, W)
sig.get_mean_pattern(x0, y0, x1, y1, scan=0) # (H, W), inclusive scan area
nexus.run_tool(tool_id, sig, **params) # fourd_overview | fourd_virtual_detector | fourd_virtual_diffraction -> [NexusSignal]
nexus.set_detectors(sig, detectors) # replace the panel's detector list
# Parameter value types: number->int|float, string/enum/color->str, boolean->bool,
# intensity->float, timestamp->float(s), coordinate->"x,y" str, roi*->annotation id str