RBC vectors support

Optional RBC vector output

Build with ./configure --with-rbc=/path/to/rbc (a source tree, installed header directory, or installation prefix). The default --without-rbc build has no RBC dependency. An enabled build uses RBC stubs and loads rbc::vector only when vector output is requested; list-only use still works without RBC installed. Use the RBC 0.8.1 or newer headers and runtime, including the read-only stubs API.

# ::wave is created automatically if needed.
set sim [ngspicetclbridge::new /path/to/libngspice.so -output vector -namespace ::wave -ifexists error]
# Load a circuit, then start it with $sim command bg_run.
# After metadata has been processed by the event loop:
set signals [$sim vectors]
# Example result: time ::wave::time v(out) ::wave::v(out)
set samples [::wave::v(out) range 0 end]
$sim vectors -clear
# Commands survive clear and are refilled by subsequent samples/runs.
set copy [$sim asyncvector v(out) -name ::savedOutput]
set listCopy [$sim asyncvector v(out) -output list]

Live vector updates run in the Tcl thread, in batches. Run the event loop or call $sim flush to publish them. Complex signals use complex RBC vectors. A graph can bind directly to the returned names through -xdata and -ydata; bindings survive clear and new runs. Use a dedicated namespace to avoid collisions such as the global Tcl time command.

$sim flush publishes the initialization metadata and samples buffered at entry, then returns an empty result. It does not wait for the solver or process the Tcl event loop. Samples arriving during publication remain pending. Queued bridge events cannot append consumed samples twice. RBC notifications may invoke callbacks, but reentrant operations on the publishing handle are rejected except destruction. Tk redraws occur when the application returns to its normal event loop. The run helper flushes before returning.

-ifexists error is the initial default. replace adopts an existing same-type RBC vector in place, retaining graph bindings; it never overwrites an unrelated Tcl command. Previously attached vectors are reused regardless of the collision policy. Destroying the handle destroys only live vectors it created. Adopted vectors and on-demand asyncvector snapshots remain caller-owned. Use rbc::vector rename oldName newName to rename an attached live vector. The bridge follows the same C vector and preserves ownership, clear and rerun behavior; SIM vectors keeps the original ngspice signal key and returns the new fully qualified destination. An ordinary Tcl rename does not update the RBC registry and is not supported. Do not modify, resize, replace or delete live vectors while they are attached. Event-driven output errors are reported once through Tcl’s background error handler. Explicit SIM flush returns errors directly. Both retain failures for SIM vectors and SIM flush; a new plot retries initialization.

asyncvector accepts -output list|vector, -ifexists error|replace, -name destination, and -namespace name overrides. The per-call namespace is for vector output, resolves relative to the caller, and is created with missing parents. It does not change the handle defaults or live bindings. A fully qualified -name takes precedence. Snapshots never become live bindings and cannot overwrite an attached live vector. Snapshot data is copied under ngspice’s realloc lock; RBC operations happen after unlocking. asyncvector -info name is unchanged.

readVecsAsync returns all current-plot snapshots as a dictionary from raw signal names to lists or RBC vector names. It inherits the handle’s output, namespace, and collision defaults and accepts -output, -namespace, and -ifexists overrides. With no explicit namespace, it uses the helper’s caller namespace. Complex signals produce complex vectors; snapshots remain caller-owned. Use a separate destination when the simulator already maintains live vectors:

set snapshots [ngspicetclbridge::readVecsAsync -output vector -namespace ::snapshots $sim]
set snapshots [ngspicetclbridge::readVecsAsync -output vector -namespace ::snapshots -ifexists replace $sim]
set lists [ngspicetclbridge::readVecsAsync -output list $sim]
set metadata [ngspicetclbridge::readVecsAsync -info $sim]

-info cannot be combined with output options. Each vector is copied separately, so reading a running simulation is not an atomic snapshot across signals. If a later read fails, earlier snapshots remain created or updated.

Signal names with balanced parentheses, including v(1), are preserved literally. Unsafe names, namespace separators, and the reserved _raw_ prefix are encoded using the same _raw_ plus uppercase UTF-8 hex convention as tclsimrawreader. New vectors have no mapped array variable. SIM vectors returns the exact raw-name-to-command mapping.

The headless fixture covers repeated bg_run → bg_halt → bg_resume → bg_halt cycles in list and vector modes, including initialization resent for the same plot, queued samples, real/complex data, explicit clearing, failed resume attempts and transitions to a new plot. These tests use a mock shared library and do not require an installed ngspice solver.

The headless test-rbc checks also load the public Tcl helpers and require argparse on TCLLIBPATH. Optional checks use a deterministic shared-ngspice fixture, including a worker thread; they do not need a circuit solver:

make test-rbc TCLLIBPATH="/path/to/rbc/package"
make test-rbc-graph TCLLIBPATH="/path/to/rbc/package /path/to/Tk/package"

test/rbc-graph.test is a separate display-dependent check of graph bindings during streaming, clear and rerun. Neither optional suite runs through test/all.tcl. The graph check skips when Tk/RBC or a display is unavailable. These fixture checks complement the existing tests against a real ngspice shared library.

Graph integration with real ngspice

The separate test-rbc-graph-real target uses your actual ngspice shared library and the four-bit adder in examples/fourbit-adder.cir. It does not build or load the mock library. The circuit retains its 10 microsecond transient analysis and saves v(9), v(10), v(11) and v(12).

# Linux
make test-rbc-graph-real NGSPICE_LIBRARY=/usr/local/lib/libngspice.so TCLLIBPATH="/path/to/rbc"

# Windows / MSYS2: pass the complete DLL filename, using forward slashes.
make test-rbc-graph-real NGSPICE_LIBRARY="C:/Spice64/bin/ngspice.dll" TCLLIBPATH="C:/path/to/rbc"

Requires an RBC-enabled bridge, full RBC/Tk with a working display, and an ngspice library compatible with the bridge. Missing requirements cause an explicit error. This target is excluded from ordinary make test.

A window plots all four output voltages as the simulation runs. The test observes at least two increases in sample count while ngspice is active, checks completion at 10 microseconds, and compares every displayed vector and its time scale with independent list snapshots from ngspice. It then clears the live vectors and repeats the simulation without recreating the graph elements or vector commands. Closing the test window cancels the test; otherwise it closes automatically on completion.

The timeout is 180 seconds per run. For a slower build, use NGSPICE_TEST_TIMEOUT_MS=600000. This is deliberately a long, two-run integration test. If a machine completes the entire simulation before two live updates can be observed, the test reports that condition rather than claiming that streaming was verified. Initialization files are disabled with -noinit so local ngspice settings do not alter the example.

Vector destination namespace

An explicit handle -namespace applies to both live vectors and asyncvector snapshots. Relative namespace names resolve against the caller creating the handle; missing namespaces and parents are created then. The canonical name is retained even when reads happen in another namespace. Empty namespace names are rejected; :: selects the global namespace explicitly. Namespace creation also works in list-only builds and does not load RBC.

Without -namespace, existing behavior is preserved: live destinations use the handle creation namespace, while snapshots use the read caller’s namespace. A relative snapshot -name uses the selected default; a fully qualified -name overrides it and requires its destination namespace to exist.

set sim [ngspicetclbridge::new $lib -output vector -namespace ::wave]
# After simulation data is available, ::wave::time is the live vector.
set snapshot [$sim asyncvector time -name savedTime]
# -> ::wave::savedTime

Snapshot replacement of a live destination remains forbidden, even with -ifexists replace. Use a distinct snapshot name as above. Destroying the handle never deletes the namespace. Existing ownership rules remain: handle-created live vectors are destroyed, while adopted vectors and independent snapshots survive.

Read-only destinations

Snapshot output and adoption with -ifexists replace reject locked real or complex destinations with RBC VECTOR READONLY; the bridge never silently unlocks them. Newly created vectors are writable. Locking an attached live vector prevents subsequent updates, including direct writes within its existing capacity. All batch destinations are checked before writing the first vector. A streaming failure follows the existing persistent vector-output error path and reports one background error; unlocking alone does not replay discarded simulation data. Start a new simulation after unlocking to resume cleanly.

Reading SIM vectors is allowed while an attached vector is locked, unless a prior output failure is already recorded. SIM vectors -clear checks all retained destinations first. A lock present at entry leaves their contents, bridge storage metadata and pending producer rows intact. Unlock and retry clear, or continue the current simulation. Renaming and handle cleanup retain their existing ownership rules; cleanup can destroy owned locked vectors. Snapshots remain caller-owned.

Checks are repeated before individual updates because Tcl callbacks can change later destinations. Publication is not a transaction against arbitrary reentrant application callbacks.

Automatic snapshot vector names

Use -name #auto on a single asyncvector snapshot, or -names #auto on readVecsAsync to request a fresh RBC vector for every signal:

set one [$sim asyncvector v(out) -output vector -namespace ::results -name #auto]
set waves [::ngspicetclbridge::readVecsAsync -output vector -namespace ::results -names #auto $sim]
set output [dict get $waves v(out)]
puts [$output length]
::rbc::vector destroy $one {*}[dict values $waves]

readVecsAsync -names also accepts a dictionary mapping original plot vector names to destinations, for example -names {time #auto v(out) saved}. Omitted entries retain the normal signal-derived names. Naming requires effective vector output, either explicitly selected or inherited from the handle, and cannot be combined with -info. Unknown keys, empty destinations and malformed dictionaries are rejected before reading.

RBC expands a final #auto component itself, in the namespace selected by the per-call -namespace, then the explicit handle namespace, or otherwise the caller’s namespace. Relative namespace overrides and missing-parent creation continue to work as before. Absolute destination names override this location and require an existing parent namespace. auto without # remains an ordinary name. Automatic snapshots always create fresh vectors; -ifexists replace continues to apply to explicit destinations.

The dictionary keys remain the original ngspice signal names; values are the actual fully qualified RBC commands. Real/complex types and values are preserved. Snapshot vectors are caller-owned and survive simulator destruction; release them with ::rbc::vector destroy. Live $sim vectors bindings keep their existing names, identity and handle-owned lifetime. Bulk snapshots still read one vector at a time: if a later read fails, earlier snapshots remain in the destination namespace, as with explicit names.

Namespace precedence for snapshots

asyncvector and readVecsAsync select destinations in this order: per-call -namespace, explicit handle namespace, then the read caller’s namespace. Relative namespace options resolve against their own caller; missing parents are created. A per-call override requires vector output and never changes handle defaults or live streaming destinations. Empty namespaces are rejected.

Relative -name and -names destinations, omitted signal-derived names, and #auto use that selection. Fully qualified destinations override it; their parent namespace must already exist. RBC expands a final #auto component, including in a fully qualified name. auto without # is an ordinary name.

Package defaults

Set representation and collision defaults once after loading the package:

package require ngspicetclbridge
::ngspicetclbridge::configure -output vector -ifexists replace

New handles inherit output and collision defaults unless their creation call supplies -output or -ifexists explicitly. Existing handles keep their settings; per-read overrides still take precedence.

Use ::ngspicetclbridge::configure to query all settings, or ::ngspicetclbridge::configure -output to query one. The all-settings dictionary can be restored with ::ngspicetclbridge::configure {*}$saved. Initial representation defaults remain list; the initial -ifexists policy is error. Invalid requests and unavailable vector support leave settings unchanged. Configuration belongs to the current Tcl interpreter. The command is public but not namespace-exported, so wildcard imports cannot introduce a configure collision. Namespace selection and naming are unchanged. -ifexists replace still requires a compatible, writable destination. The collision setting affects vector output only and can be configured even in a build without RBC.


Copyright (c) George Yashin