This page covers project scripts and simulation scripts. Review unfamiliar scripts before choosingTrust and run.
Simulation Script block API
A Simulation Script block runs before its sheet is prepared for simulation. It makes finite real values available to component expressions; it does not provide the document API for running analyses, reading results, plotting, or downloading files.
| Name | Type | Behavior |
|---|---|---|
params | dict[str, float] | Effective numeric Circuit Part Parameters for this instance. Assigning params["name"] publishes the updated value. |
| Parameter names | float | Each valid public Parameter name is also available directly. Reassign it to override that value for this run. |
request_timeout(seconds) | float | Requests more preparation time and returns the granted number of seconds. Use a positive number. OhmSpice may grant less time than requested. |
print(...) | Python built-in | Writes text to the simulation Console. |
numpy | module | Available for numerical work. Python standard-library modules and other project scripts can also be imported. |
Public top-level assignments and finite real values written to params become expression names for the current run. Names that begin with an underscore, booleans, complex values, infinities, and NaN are not published.
import math
resistance = 2_200
params["resistance"] = resistance
cutoff_hz = 1_000
capacitance = 1 / (2 * math.pi * resistance * cutoff_hz)
print("C = %.3g F" % capacitance)Use published names in eligible component values with a leading =, such as =resistance or =1 / (2 * pi * resistance * capacitance). The script and its imports run once for each sheet occurrence, including Circuit Part instances, before the simulator starts.
Plotting with a Python document
Plot titles are optional. Use axis.text() and axis.table() for notes and tables anchored to a plot corner, or axis.annotate() for text attached to a data coordinate. Pass formatted strings for table cells when you want units such as 4.8 V. Figure output and figure.savefig() include the same overlays.
Histograms and cumulative distributions
Use axis.hist(samples, bins=40) to count values in bins, or pass explicit bin edges for unequal widths. It returns NumPy arrays (counts, edges). Use density=True for a histogram whose area is one; the heights are probability density, not probabilities. Samples must be finite real numbers.
axis.ecdf(samples) shows the fraction of samples at or below each value. Repeated values form one jump. Add a nominal value with axis.axvline(value, label="Nominal"). Reference lines follow zoom and appear in PNG exports.
fig, axes = subplots(2, sharex=True)
axes[0].hist([3.9, 4.0, 4.0, 4.1], bins=8)
axes[0].set(xlabel="Output voltage (V)", ylabel="Trials per bin")
axes[1].ecdf([3.9, 4.0, 4.0, 4.1])
axes[1].set(xlabel="Output voltage (V)", ylabel="Cumulative fraction")
for ax in axes:
ax.axvline(4, label="Nominal 4 V")
fig.show()Open the Divider resistor tolerances example and run Divider tolerances.py for 4,096 seeded SPICE trials, a histogram, and an empirical CDF. The script runs batches of 256 and reports progress and summary statistics in the Console. Uniform, independent ±5% resistor tolerances are a modeling assumption; sample percentiles are not guaranteed worst-case bounds.
Engineering plots
Use scatter for independent samples, fill_between for tolerance envelopes, and errorbar for measurement uncertainty. Line plots accept linestyle, linewidth, marker, markersize, and alpha. Widths and marker diameters use CSS pixels; scatter size s is an area in square CSS pixels. Opacity applies to each trace.
fig, ax = subplots()
frequency = [100, 1_000, 10_000]
ax.fill_between(frequency, [0.9, 0.6, 0.08], [1.0, 0.8, 0.12],
label="Tolerance", color="#2563eb")
ax.plot(frequency, [0.95, 0.7, 0.1], linestyle="--", marker="o",
label="Nominal", color="#e11d48")
ax.set(xscale="log", yscale="log", xlabel="Frequency (Hz)", ylabel="Gain")
ax.set_xlim(100, 10_000)
ax.set_ylim(0.05, 2)
ax.axhline(0.707, label="Target gain")
fig.show()set_xlim(left, right) and set_ylim(bottom, top) set the initial and Fit ranges. Bounds must be finite and increasing. Shared x axes use the same explicit range. Logarithmic axes mask nonpositive line and scatter samples; filled shapes, mesh edges, and uncertainty endpoints must all be positive. Histograms use a zero baseline and require a linear y axis.
step(x, y, where="post") plots a sampled control signal. Choose pre, post, or mid for transition placement. stairs(values, edges) uses one more edge than values for precomputed bins. bar(x, height) compares values at numeric x positions, and boxplot(samples) compares distributions using quartiles, medians, whiskers, and outliers. Pass one sample vector or a list of sample vectors to boxplot.
axhline and axvline mark reference values. axhspan and axvspan shade operating regions. These overlays follow zoom, appear in PNG exports, and do not expand the data range.
Two-parameter sweeps
pcolormesh(x_edges, y_edges, values) displays one value per rectangular cell, including unequal cell widths. The matrix has len(y_edges) - 1 rows and len(x_edges) - 1 columns. Edges must be strictly increasing and all values must be finite real numbers.
fig, ax = subplots()
ax.pcolormesh([0, 1, 3], [50, 100, 200], [[90, 94], [88, 92]],
label="Efficiency (%)", vmin=80, vmax=100)
ax.set(xlabel="Load (A)", ylabel="Switching frequency (kHz)")
fig.savefig("efficiency.png")A color scale appears beside each mesh. Use cmap="viridis" for an interpolated five-stop palette or cmap="gray" for grayscale. Explicit vmin and vmax keep colors comparable between figures; values outside this range use the end colors. Put multiple meshes in separate subplots.
imshow(values) uses uniform cells with integer pixel centers. The first row appears at the top by default; use origin="lower" to put it at the bottom. Pass extent=(left, right, bottom, top) to assign increasing data bounds. Cells stretch to the subplot without smoothing or a fixed aspect ratio.
These methods return the axis for chaining. They provide a focused plotting API rather than Matplotlib Artist objects or full Matplotlib compatibility.
Monte Carlo tolerances
Open the RC low-pass example, then add a Python document. This runs 32 reproducible trials with resistor and capacitor values drawn uniformly within ±5%. Each batch allows at most 256 runs. Use mode="zip" to pair one resistance and capacitance per trial; product mode would run every combination.
import numpy as np
sheet = get_sheet().override(V1=ac_source(1))
rng = np.random.default_rng(42)
runs = sheet.sweep(
mode="zip",
R1=10_000 * rng.uniform(0.95, 1.05, 32),
C1=100e-9 * rng.uniform(0.95, 1.05, 32),
).ac("10", "100k", points=40, save="V(vout)")
fig, ax = subplots()
ax.set(xlabel="Frequency (Hz)", ylabel="Gain (dB)", xscale="log")
for run in runs:
ax.plot(run.v("vout").db)
fig.show()For a transient step response, use signal.rise_time(), signal.fall_time(), or signal.settling_time(target=expected_final_value). Select one transition with start and stop when the waveform repeats. Durations use the Signal's x-axis units; transient results use seconds.
Compatibility
The current scripting API is 1.2. Scripts can inspect api_version before using optional helpers.
| Global | Type | Description |
|---|---|---|
api_version | str | The scripting API compatibility version, currently "1.2". |
Exceptions
Catch these exceptions when a script needs to report or handle a failed operation.
OhmSpiceError
Extends Exception
Base class for errors raised by the OhmSpice scripting API.
SimulationError
Extends OhmSpiceError
Raised when a requested simulation does not complete.
Inspect the Console for the complete simulator diagnostic.
SignalNotFoundError
Extends OhmSpiceError, LookupError
Raised when a requested result signal is missing, inactive, or was not saved.
The error lists the human-readable signal paths available in the Result.
Classes and handles
These handles are returned by the top-level helpers and analysis methods. The editor's project-aware completion adds exact sheet, component, and signal names.
Sheet
A run-local handle for one schematic sheet.
Use get_sheet() to obtain a Sheet. Component assignments and analysis calls do not change the saved schematic.
| Property | Type | Description |
|---|---|---|
name | str | None | The selected sheet name, or None for the document context. |
components | tuple[Component, ...] | Read-only component inventory for the selected sheet. |
analyses | tuple[Analysis, ...] | Read-only configured analysis inventory. |
Methods
sheet.component(refdes)
Returns a run-local component override handle.
refdes- Component reference such as
R1.
sheet.override(**components)
Returns an independent sheet handle with scalar or typed-source overrides.
components- Reference-designator keyword values.
sheet.sweep(*, mode="product", **components)
Creates a sweep over combinations of component values.
mode"product"for a Cartesian sweep or"zip"for lock-step sequences.components- Reference-designator sequences; use
V1__dc-style double underscores for a component property.
Calling .op(), .tran(), .ac(), or .dc() on the returned sweep yields a list of Results; each Result carries its parameters mapping.
sheet.run(*, save="all", solver=None, parameters=None, directives=None, timeout=15)
Runs the sheet's configured analysis.
save"all", oneV(...),I(...), or semantic component path, or a sequence of those names.solver- Typed solver configuration returned by
solver(...). parameters- Run-local SPICE parameter values.
directives- Additional SPICE directives for this run.
timeout- Timeout in seconds.
sheet.op(*, save="all", solver=None, parameters=None, directives=None, timeout=15)
Runs a Bias Point (.op) analysis.
save"all", oneV(...),I(...), or semantic component path, or a sequence of those names.solver- Typed solver configuration returned by
solver(...). parameters- Run-local SPICE parameter values.
directives- Additional SPICE directives for this run.
timeout- Timeout in seconds.
sheet.tran(stop, *, step="10u", start=None, max_step=None, uic=False, save="all", solver=None, parameters=None, directives=None, timeout=15)
Runs a transient analysis.
stop- Stop time.
step- Requested print step.
start- Optional record-from time.
max_step- Maximum internal time step.
uic- Use initial conditions without first solving the Bias Point.
save"all", oneV(...),I(...), or semantic component path, or a sequence of those names.solver- Typed solver configuration returned by
solver(...). parameters- Run-local SPICE parameter values.
directives- Additional SPICE directives for this run.
timeout- Timeout in seconds.
sheet.ac(start, stop, *, points=100, sweep="dec", save="all", solver=None, parameters=None, directives=None, timeout=15)
Runs a linear, octave, or decade AC sweep.
start- Start frequency.
stop- Stop frequency.
points- Points per interval.
sweep"dec","oct", or"lin".save"all", oneV(...),I(...), or semantic component path, or a sequence of those names.solver- Typed solver configuration returned by
solver(...). parameters- Run-local SPICE parameter values.
directives- Additional SPICE directives for this run.
timeout- Timeout in seconds.
sheet.dc(source, start, stop, step, *, save="all", solver=None, parameters=None, directives=None, timeout=15)
Runs a DC source sweep.
source- Source reference designator.
start- Start value.
stop- Stop value.
step- Sweep increment.
save"all", oneV(...),I(...), or semantic component path, or a sequence of those names.solver- Typed solver configuration returned by
solver(...). parameters- Run-local SPICE parameter values.
directives- Additional SPICE directives for this run.
timeout- Timeout in seconds.
Sweep
A batch of run-local component overrides.
A product sweep runs every combination; a zip sweep runs corresponding values together. Analysis methods return one Result per point.
Usage
sheet.sweep(R1=["1k", "2k"])
sheet.sweep(mode="zip", R1=["1k", "2k"], C1=["10n", "20n"])Methods
sweep.run(*, save="all", solver=None, parameters=None, directives=None, timeout=15)
Runs the configured analysis for every point in the sweep.
save"all", oneV(...),I(...), or semantic component path, or a sequence of those names.solver- Typed solver configuration returned by
solver(...). parameters- Run-local SPICE parameter values.
directives- Additional SPICE directives for this run.
timeout- Timeout in seconds.
Returns one Result per sweep point in the same order as the generated product or zip sequence.
sweep.op(*, save="all", solver=None, parameters=None, directives=None, timeout=15)
Runs a Bias Point (.op) analysis for every point in the sweep.
save"all", oneV(...),I(...), or semantic component path, or a sequence of those names.solver- Typed solver configuration returned by
solver(...). parameters- Run-local SPICE parameter values.
directives- Additional SPICE directives for this run.
timeout- Timeout in seconds.
sweep.tran(stop, *, step="10u", start=None, max_step=None, uic=False, save="all", solver=None, parameters=None, directives=None, timeout=15)
Runs a transient analysis for every point in the sweep.
stop- Stop time.
step- Requested print step.
start- Optional record-from time.
max_step- Maximum internal time step.
uic- Use initial conditions without first solving the Bias Point.
save"all", oneV(...),I(...), or semantic component path, or a sequence of those names.solver- Typed solver configuration returned by
solver(...). parameters- Run-local SPICE parameter values.
directives- Additional SPICE directives for this run.
timeout- Timeout in seconds.
sweep.ac(start, stop, *, points=100, sweep="dec", save="all", solver=None, parameters=None, directives=None, timeout=15)
Runs a linear, octave, or decade AC sweep for every point in the component sweep.
start- Start frequency.
stop- Stop frequency.
points- Points per interval.
sweep"dec","oct", or"lin".save"all", oneV(...),I(...), or semantic component path, or a sequence of those names.solver- Typed solver configuration returned by
solver(...). parameters- Run-local SPICE parameter values.
directives- Additional SPICE directives for this run.
timeout- Timeout in seconds.
sweep.dc(source, start, stop, step, *, save="all", solver=None, parameters=None, directives=None, timeout=15)
Runs a DC source sweep for every point in the component sweep.
source- Source reference designator.
start- Start value.
stop- Stop value.
step- Sweep increment.
save"all", oneV(...),I(...), or semantic component path, or a sequence of those names.solver- Typed solver configuration returned by
solver(...). parameters- Run-local SPICE parameter values.
directives- Additional SPICE directives for this run.
timeout- Timeout in seconds.
Component
A run-local component handle returned by Sheet.component().
Read the selected component's name, model, and parameter values through this handle. Assigning a supported property affects only the current script run.
| Property | Type | Description |
|---|---|---|
id | str | Stable component identity. |
refdes | str | Reference designator such as R1. |
definition_id | str | Component definition identifier. |
definition_name | str | Display name of the component definition. |
definition | ComponentDefinition | Read-only component definition metadata. |
kind | str | Component behavior kind. |
model | ComponentModel | None | Selected component model, when available. |
parameters | Mapping[str, scalar] | Component parameter values, including defaults. |
properties | Mapping[str, scalar] | Alias for parameters. |
value | scalar | Run-local value override when supported. |
dc | scalar | Run-local DC source override when supported. |
waveform | scalar | Run-local waveform override when supported. |
amplitude | scalar | Run-local source amplitude override when supported. |
frequency | scalar | Run-local source frequency override when supported. |
offset | scalar | Run-local source offset override when supported. |
delay | scalar | Run-local source delay override when supported. |
phase | scalar | Run-local source phase override when supported. |
duty | scalar | Run-local pulse duty-cycle override when supported. |
low | scalar | Run-local pulse low-level override when supported. |
high | scalar | Run-local pulse high-level override when supported. |
rise | scalar | Run-local source rise-time override when supported. |
fall | scalar | Run-local source fall-time override when supported. |
ComponentDefinition
Read-only metadata for a component definition.
| Property | Type | Description |
|---|---|---|
id | str | Definition identifier. |
name | str | Definition name. |
kind | str | Definition behavior kind. |
ComponentModel
Read-only metadata for the selected component model.
| Property | Type | Description |
|---|---|---|
family_id | str | Model family identifier. |
variant_id | str | Selected model variant identifier. |
name | str | Model variant name. |
parameters | Mapping[str, scalar] | Effective model parameter values. |
Analysis
A read-only configured analysis descriptor from the selected sheet.
| Property | Type | Description |
|---|---|---|
id | str | Analysis identifier. |
name | str | Analysis name. |
enabled | bool | Whether the analysis is enabled. |
kind | str | Analysis kind, such as op, tran, ac, or dc. |
analysis | Mapping[str, object] | Read-only analysis settings. |
Result
The signals and metadata returned by one completed analysis.
Access node voltages with v(), default component currents with i(), or semantic component signals through components or signal().
| Property | Type | Description |
|---|---|---|
id | str | Simulation result identifier. |
status | str | Completion status. |
analysis | "op" | "tran" | "ac" | "dc" | Analysis kind. |
elapsed | float | Elapsed simulation time in seconds. |
signals | tuple[str, ...] | Human-readable saved signal paths. |
sample_count | int | Number of samples in the result scale. |
parameters | dict[str, scalar] | Sweep-point component values, or an empty mapping for a single run. |
x | Signal | Result scale Signal. |
time | Signal | Time scale Signal for transient results. |
frequency | Signal | Frequency scale Signal for AC results. |
components | ResultComponents | Semantic component signal groups. |
discontinuities | dict[str, list[dict[str, object]]] | Samples immediately before and after a transient discontinuity, grouped by plot name. PRE identifies the sample before the event; POST identifies the sample after it. |
Methods
result.component(refdes)
Returns the semantic signal groups saved for one component.
refdes- Component reference such as
M1.
The same component is available as result.components.M1. Groups are terminals, device, and power; their fields depend on the active component Model.
result.signal(expression)
Returns an explicitly saved node voltage, default current, or semantic component signal.
expression- Name such as
V(out),I(M1), orM1.device.channel_current.
result.to_csv(*expressions)
Returns CSV text for selected signals, or every returned vector when no expressions are given.
expressions- Optional voltage, default-current, or semantic component signal names.
result.export_csv(filename, *expressions)
Downloads selected result signals as CSV, preserving real and imaginary AC columns.
filename- Download filename;
.csvis added when omitted. expressions- Optional voltage, default-current, or semantic component signal names.
result.v(net)
Returns a node-voltage Signal.
net- Net name.
result.i(refdes)
Returns the component Model's declared default-current Signal.
refdes- Component reference designator. Components without a default-current signal report a clear error.
ResultComponent
Semantic signal groups for one component in a Result.
The available terminals, device, and power fields depend on the active component Model.
| Property | Type | Description |
|---|---|---|
refdes | str | Component reference designator. |
terminals | SignalGroup | Available terminal signals, when defined. |
device | SignalGroup | Available device signals, when defined. |
power | SignalGroup | Available power signals, when defined. |
Methods
component.signal(path)
Returns one saved semantic signal using a component-relative group path.
path- Relative path such as
device.channel_current.
ResultComponents
The semantic component signals in a Result.
Usage
result.components["M1"]
for component in result.components
len(result.components)SignalGroup
A component-relative group of semantic Signals.
Signal fields are generated from the active component Model. Use component.signal(path) when attribute syntax is not suitable.
Signal
A NumPy-backed vector with an optional x axis and measurement helpers.
Signals use float64 or complex128 arrays. Slicing, arithmetic, and derived views preserve the x axis.
| Property | Type | Description |
|---|---|---|
name | str | None | Human-readable signal name. |
unit | str | None | Signal unit, such as V, A, or Hz. |
values | numpy.ndarray | Underlying float64 or complex128 values. |
x | Signal | None | Optional x-axis Signal. |
real | Signal | Real component view. |
imag | Signal | Imaginary component view. |
mag | Signal | Magnitude view. |
db | Signal | 20 log10 magnitude view in dB. |
phase | Signal | Phase view in degrees. |
last | float | complex | Final value; raises ValueError for an empty Signal. |
Usage
signal[index] and signal[start:stop]
signal + other, signal - other, signal * other, signal / other, signal ** other
-signal, +signal, abs(signal), and numpy.asarray(signal)
len(signal) and for value in signalMethods
signal.window(start=None, stop=None)
Returns the samples inside an x-axis window.
start- Optional lower x-axis bound; numeric values or SPICE suffixes such as
4m. stop- Optional upper x-axis bound.
signal.at(x, *, method="linear")
Samples a Signal by linear interpolation or nearest point.
x- X-axis coordinate.
method"linear"or"nearest".
signal.mean(*, start=None, stop=None)
Mean measurement; transient mean/RMS/integral use time weighting.
start- Optional lower x-axis bound; numeric values or SPICE suffixes such as
4m. stop- Optional upper x-axis bound.
signal.rms(*, start=None, stop=None)
Rms measurement; transient mean/RMS/integral use time weighting.
start- Optional lower x-axis bound; numeric values or SPICE suffixes such as
4m. stop- Optional upper x-axis bound.
signal.min(*, start=None, stop=None)
Min measurement; transient mean/RMS/integral use time weighting.
start- Optional lower x-axis bound; numeric values or SPICE suffixes such as
4m. stop- Optional upper x-axis bound.
signal.max(*, start=None, stop=None)
Max measurement; transient mean/RMS/integral use time weighting.
start- Optional lower x-axis bound; numeric values or SPICE suffixes such as
4m. stop- Optional upper x-axis bound.
signal.pkpk(*, start=None, stop=None)
Peak-to-peak measurement; transient mean/RMS/integral use time weighting.
start- Optional lower x-axis bound; numeric values or SPICE suffixes such as
4m. stop- Optional upper x-axis bound.
signal.integral(*, start=None, stop=None)
Integral measurement; transient mean/RMS/integral use time weighting.
start- Optional lower x-axis bound; numeric values or SPICE suffixes such as
4m. stop- Optional upper x-axis bound.
signal.crossings(level=0, *, edge="both")
Returns interpolated rising, falling, or all threshold-crossing x coordinates.
level- Crossing threshold.
edge"rising","falling", or"both".
signal.rise_time(*, low=0.1, high=0.9, start=None, stop=None)
Duration of the first complete transition, using interpolated thresholds relative to the selected window's minimum and maximum. Raises ValueError when no transition is present.
low / high- Fractions of the observed range; require 0 < low < high < 1. Defaults measure 10–90%.
start- Optional lower x-axis bound; numeric values or SPICE suffixes such as
4m. stop- Optional upper x-axis bound.
signal.fall_time(*, low=0.1, high=0.9, start=None, stop=None)
Duration of the first complete transition, using interpolated thresholds relative to the selected window's minimum and maximum. Raises ValueError when no transition is present.
low / high- Fractions of the observed range; require 0 < low < high < 1. Defaults measure 10–90%.
start- Optional lower x-axis bound; numeric values or SPICE suffixes such as
4m. stop- Optional upper x-axis bound.
signal.settling_time(*, target=None, tolerance=0.02, start=None, stop=None)
Elapsed x-axis time after which every remaining sample stays inside the target band. Interpolates the final band entry; raises ValueError if the final sample is outside the band.
target- Final value; defaults to the last sample. Use a known target when checking whether the simulation ran long enough.
tolerance- Fraction of the step from the first sample to target, between 0 and 1. Defaults to 2%.
start- Optional lower x-axis bound; numeric values or SPICE suffixes such as
4m. stop- Optional upper x-axis bound.
signal.fft(*, window="hann", detrend=True)
Resamples adaptive transient data uniformly and returns a complex frequency-domain Signal.
window"hann"orNone.detrend- Remove the mean before transforming.
signal.thd(fundamental, *, harmonics=10, start=None, stop=None)
Computes total harmonic distortion from a transient window.
fundamental- Fundamental frequency.
harmonics- Highest harmonic to include.
start- Optional lower x-axis bound; numeric values or SPICE suffixes such as
4m. stop- Optional upper x-axis bound.
signal.to_numpy(*, copy=False)
Returns the Signal values as a NumPy array.
copy- Copy the values instead of returning the underlying array.
The default returns the underlying array; pass copy=True when the script must own an independent copy.
signal.export_csv(filename)
Downloads this Signal as CSV.
filename- Download filename;
.csvis added when omitted.
Axis
One plotting pane in a Figure.
Plot Signals or numeric x/y sequences, set labels and scales, and place a legend.
Methods
axis.plot(signal_or_x, y=None, *, label=None, color=None, linestyle="-", linewidth=2, marker=None, markersize=6, alpha=1)
Adds a Signal or x/y sequence to an axis and returns the axis.
signal_or_x- Signal, y sequence, or x sequence.
y- Optional y sequence.
label- Legend label.
color- Trace color.
linestyle- Line pattern: -, --, :, -., or none (also solid, dashed, dotted, dashdot).
linewidth- Nonnegative line width in CSS pixels; default 2.
marker- Optional o, s, ^, x, +, or . marker.
markersize- Positive marker diameter in CSS pixels; default 6.
alpha- Opacity from 0 to 1; default 1.
axis.scatter(x, y, *, s=36, marker='o', label=None, color=None, alpha=1)
Plots unconnected points. Size s is marker area in square CSS pixels. Returns the axis.
x- Finite real x coordinates.
y- Y coordinates paired with x.
s- Positive marker area in square CSS pixels; default 36.
marker- o, s, ^, x, +, or .; None disables markers.
label- Legend label.
color- CSS color string.
alpha- Opacity from zero through one, applied per trace.
axis.fill_between(x, y1, y2=0, *, label=None, color=None, alpha=0.25)
Fills the region between y1 and y2. X must be finite and strictly increasing; y bounds accept scalars or matching sequences. Returns the axis.
x- Finite real x coordinates.
y1- Finite real scalar or sequence matching x.
y2- Finite real scalar or sequence matching x; default zero.
label- Legend label.
color- CSS color string.
alpha- Opacity from zero through one, applied per trace.
axis.step(x, y, *, where='pre', label=None, color=None, linewidth=2, alpha=1)
Plots steps with transitions before, after, or midway between samples. Returns the axis.
x- Finite real x coordinates.
y- Y coordinates paired with x.
where- pre, post, or mid; default pre.
label- Legend label.
color- CSS color string.
linewidth- Nonnegative line width in CSS pixels.
alpha- Opacity from zero through one, applied per trace.
axis.stairs(values, edges, *, baseline=0, fill=False, label=None, color=None, alpha=1)
Plots precomputed bins using N values and N+1 strictly increasing edges. Set baseline=None for an open outline. Returns the axis.
values- Finite real data; a vector for stairs or a rectangular matrix for a mesh/image.
edges- Strictly increasing finite edges, one more than values.
baseline- Finite baseline, or None for an open unfilled outline.
fill- Fill the area to the baseline.
label- Legend label.
color- CSS color string.
alpha- Opacity from zero through one, applied per trace.
axis.errorbar(x, y, *, xerr=None, yerr=None, label=None, color=None, marker='o', linewidth=1.5, alpha=1)
Plots measurements and uncertainty segments. Error magnitudes accept a nonnegative scalar, N values, or a (2, N) array of lower and upper magnitudes. Returns the axis.
x- Finite real x coordinates.
y- Y coordinates paired with x.
xerr- Nonnegative horizontal errors: scalar, N values, or (2,N) lower/upper magnitudes.
yerr- Nonnegative vertical errors: scalar, N values, or (2,N) lower/upper magnitudes.
label- Legend label.
color- CSS color string.
marker- o, s, ^, x, +, or .; None disables markers.
linewidth- Nonnegative line width in CSS pixels.
alpha- Opacity from zero through one, applied per trace.
axis.bar(x, height, *, width=0.8, bottom=0, label=None, color=None, alpha=1)
Plots vertical bars at numeric x coordinates. Width, height, and bottom accept scalars or matching sequences; widths must be positive. Returns the axis.
x- Finite real x coordinates.
height- Finite scalar or heights matching x; negative heights are supported.
width- Positive scalar or widths matching x, in x-axis units.
bottom- Finite scalar or bar baselines matching x.
label- Legend label.
color- CSS color string.
alpha- Opacity from zero through one, applied per trace.
axis.boxplot(samples, *, positions=None, widths=0.5, whis=1.5, label=None, color=None)
Plots quartiles, median, whiskers, and outliers for one sample vector or a sequence of sample vectors. Whiskers reach samples within whis times the interquartile range. Returns the axis.
samples- One finite sample vector or a list of nonempty finite sample vectors.
positions- Numeric box centers matching the sample groups; default 1, 2, ... .
widths- Positive scalar or box widths matching the sample groups.
whis- Nonnegative whisker distance in IQR units; default 1.5.
label- Legend label.
color- CSS color string.
axis.pcolormesh(x, y, values, *, cmap='viridis', vmin=None, vmax=None, label=None)
Plots a rectangular color mesh with increasing x/y edges and a finite matrix of shape (len(y)-1, len(x)-1). Includes a color scale; supports viridis and gray, clipped to vmin/vmax. One mesh per subplot. Returns the axis.
x- X coordinates; finite real sequence. Mesh methods take strictly increasing cell edges.
y- Y coordinates paired with x; mesh methods take strictly increasing cell edges.
values- Finite real data; a vector for stairs or a rectangular matrix for a mesh/image.
cmap- viridis (interpolated five-stop palette) or gray.
vmin- Finite minimum color value; default data minimum.
vmax- Finite maximum color value, at least vmin; default data maximum.
label- Legend label; for a mesh, the quantity and units represented by the color scale.
axis.imshow(values, *, extent=None, origin='upper', cmap='viridis', vmin=None, vmax=None, label=None)
Plots a finite 2D matrix as uniformly sized cells. Origin upper puts the first row at the top; lower puts it at the bottom. Extent is (left, right, bottom, top); default pixel centers are integers. Cells stretch to the subplot, without interpolation. Returns the axis.
values- Finite real data; a vector for stairs or a rectangular matrix for a mesh/image.
extent- Increasing (left, right, bottom, top) bounds. Default integer pixel centers.
origin- upper (first row at top, default) or lower.
cmap- viridis (interpolated five-stop palette) or gray.
vmin- Finite minimum color value; default data minimum.
vmax- Finite maximum color value, at least vmin; default data maximum.
label- Legend label; for a mesh, the quantity and units represented by the color scale.
axis.set_xlim(left, right)
Sets finite increasing x limits. Shared axes use the same explicit limits; conflicting limits are rejected. Returns the axis.
left- Finite lower x limit; positive on a logarithmic axis.
right- Finite upper x limit, greater than left.
axis.set_ylim(bottom, top)
Sets finite increasing y limits. Limits on logarithmic axes must be positive. Returns the axis.
bottom- Finite lower y limit; positive on a logarithmic axis.
top- Finite upper y limit, greater than bottom.
axis.set_yscale(scale)
Sets the y scale to linear or log. Nonpositive line/scatter samples are masked; filled geometry and error bars must be entirely positive. Histograms require linear y. Returns the axis.
scale- linear or log.
axis.set_xscale(scale)
Sets the x scale to linear or log. Returns the axis.
scale- linear or log.
axis.axhline(y, *, label=None, color=None)
Adds a labeled horizontal reference line without expanding the data limits. Returns the axis.
y- Finite real y coordinate.
label- Optional label beside the reference.
color- CSS color string.
axis.axhspan(ymin, ymax, *, label=None, color=None, alpha=0.2)
Shades a horizontal data interval across the plot without expanding the data limits. Returns the axis.
ymin- Finite lower y bound.
ymax- Finite upper y bound, greater than ymin.
label- Optional label beside the reference.
color- CSS color string.
alpha- Opacity from zero through one, applied per trace.
axis.axvspan(xmin, xmax, *, label=None, color=None, alpha=0.2)
Shades a vertical data interval across the plot without expanding the data limits. Returns the axis.
xmin- Finite lower x bound.
xmax- Finite upper x bound, greater than xmin.
label- Optional label beside the reference.
color- CSS color string.
alpha- Opacity from zero through one, applied per trace.
axis.hist(samples, bins=40, *, range=None, density=False, label=None, color=None)
Plots a histogram and returns NumPy arrays (counts, bin_edges).
samples- Signal or numeric sample sequence.
bins- 1–4096 equal-width bins, or 2–4097 finite strictly increasing bin edges.
range- Optional (minimum, maximum) bounds for integer bins; ignored for explicit edges.
density- Return and plot probability density instead of counts. Requires at least one sample within the edges.
label- Legend label.
color- Bar color.
Samples must be nonempty, finite, real, and one-dimensional. Bins include their left edge and exclude their right edge, except the final bin includes both. Samples outside the edges are excluded. Density integrates to one over the included samples, including unequal-width bins. A logarithmic x-axis requires all bin edges to be positive.
axis.ecdf(samples, *, label=None, color=None)
Plots the empirical fraction of samples at or below each value and returns the axis.
samples- Signal or numeric sample sequence.
label- Legend label.
color- Trace color.
Uses exact step transitions, combines repeated values, and ends at one. Samples must be nonempty, finite, real, and one-dimensional.
axis.axvline(x, *, label=None, color=None)
Adds a vertical reference line spanning the plot height and returns the axis.
x- Finite real x coordinate.
label- Optional label beside the line.
color- Line and label color.
The line follows zoom and appears in PNG exports. It does not expand the data limits; a line outside the visible x range is hidden.
axis.set(*, title=None, xlabel=None, ylabel=None, xscale=None, yscale=None, xformat=None)
Sets pane labels and scale, then returns the axis.
title- Pane title.
xlabel- X-axis label.
ylabel- Y-axis label.
xscale"linear"or"log".xformat"number"(default) or"time". Time values are seconds; ticks and the axis label automatically use s, ms, µs, ns, or ps. Use an xlabel without units, such as"Time".yscale- linear or log; log axes require positive values.
axis.set_title(title)
Sets the subplot title and returns the axis.
title- Subplot title.
axis.set_xlabel(label)
Sets the subplot x-axis label and returns the axis.
label- X-axis label.
axis.set_ylabel(label)
Sets the subplot y-axis label and returns the axis.
label- Y-axis label.
axis.legend(*, position="above", loc="upper right")
Places the subplot legend above, below, or inside the plotting area.
position"above","below", or"inside".loc- Inside corner:
"upper left","upper right","lower left", or"lower right".
axis.text(text, *, loc="upper left")
Adds a note anchored to a plot corner and returns the axis.
text- Note text.
loc- Corner:
"upper left","upper right","lower left", or"lower right".
axis.annotate(text, xy)
Adds text attached to a data coordinate and returns the axis.
text- Annotation text.
xy- Finite
(x, y)data coordinate.
axis.table(*, columns, rows, loc="upper right")
Adds a text table anchored to a plot corner and returns the axis.
columns- Nonempty column labels.
rows- Nonempty rectangular rows matching the column count. Format cell values as text, including units, before passing them.
loc- Corner:
"upper left","upper right","lower left", or"lower right".
Axes
An indexable collection of plotting panes returned for multi-panel Figures.
subplots() always returns (Figure, axes); the second value is an Axis for 1×1 figures and Axes for larger figures.
| Property | Type | Description |
|---|---|---|
rows | int | Number of rows. |
cols | int | Number of columns. |
flat | Iterator[Axis] | Flat iterator over all panes. |
Usage
axes[row, col]
axes.flat and axes.ravel()
for axis in axesMethods
axes.ravel()
Returns all subplot axes as a flat tuple.
Figure
A session-only collection of plotting panes.
Figure output is temporary and is not saved with the project.
| Property | Type | Description |
|---|---|---|
title | str | None | Figure title. |
sharex | bool | Whether panes share the x axis. |
rows | int | Number of rows. |
cols | int | Number of columns. |
axes | Axes | Indexable plotting panes. |
Methods
figure.suptitle(title)
Sets the title above the complete figure and returns the figure.
title- Figure title.
figure.show(title=None)
Opens the figure as a script output tab.
title- Optional title override.
figure.savefig(filename, *, title=None)
Opens the figure output and downloads all of its panes as one PNG.
filename- Download filename;
.pngis added when omitted. title- Optional title override.
Top-level functions
Call these functions directly; no import is needed.
get_sheet(sheet_name=None)
Returns a schematic handle for run-local component overrides and simulations.
sheet_name- Optional project-tree sheet name.
Omit the name to use the script document's current sheet. Assigning sheet.R1 = "2.2k" changes only subsequent script runs.
dc_source(value=0)
Creates a typed DC source override.
value- DC source value.
ac_source(magnitude=1, *, phase=0, dc=0)
Creates a typed small-signal AC source override.
magnitude- Small-signal magnitude.
phase- Phase in degrees.
dc- DC bias used for linearization.
sine_source(amplitude, frequency, *, offset=0, delay=0, phase=0)
Creates a typed sinusoidal source override.
amplitude- Peak amplitude.
frequency- Frequency in Hz or SPICE notation.
offset- DC offset.
delay- Start delay.
phase- Phase in degrees.
pulse_source(low, high, frequency, *, duty=50, delay=0, rise=0, fall=0)
Creates a typed periodic pulse source override.
low- Low level.
high- High level.
frequency- Pulse frequency.
duty- Duty cycle in percent.
delay- Start delay.
rise- Rise time.
fall- Fall time.
solver(*, method=None, preset=None, **options)
Builds a validated solver configuration without raw .options text.
method"trap"or"gear".preset"power"or"tight"tolerance preset.options- Validated numeric ngspice solver options.
Common options include reltol, abstol, vntol, trtol, gmin, itl1, itl4, and maxord.
subplots(rows=1, cols=1, *, title=None, sharex=False)
Creates a figure and one axis or an indexable multi-panel axes collection.
rows- Row count.
cols- Column count.
title- Figure title.
sharex- Whether panes share the x axis.
A 1×1 figure returns one Axis. Multi-panel figures support axes[row, col], flat iteration, ravel(), and tuple unpacking. Figure and pane titles are optional.
export_csv(filename, *signals)
Downloads derived Signals that share an x axis as CSV.
filename- Download filename;
.csvis added when omitted. signals- One or more Signals or numeric sequences.
plot(signal_or_x, y=None, *, label=None, color=None, linestyle="-", linewidth=2, marker=None, markersize=6, alpha=1)
Adds a Signal or x/y sequence to the default figure.
signal_or_x- Signal, y sequence, or x sequence.
y- Optional y sequence.
label- Legend label.
color- Trace color.
linestyle- Line pattern: -, --, :, -., or none (also solid, dashed, dotted, dashdot).
linewidth- Nonnegative line width in CSS pixels; default 2.
marker- Optional o, s, ^, x, +, or . marker.
markersize- Positive marker diameter in CSS pixels; default 6.
alpha- Opacity from 0 to 1; default 1.
A Signal uses its own x axis automatically; complex y data plots magnitude. Numeric x and y inputs must be one-dimensional and the x values must be real.
show(*, title=None, xlabel=None, ylabel=None, xscale=None, xformat=None)
Opens the default figure as a script output tab.
title- Figure title.
xlabel- X-axis label.
ylabel- Y-axis label.
xscale"linear"or"log".xformat"number"(default) or"time". Time values are seconds; ticks and the axis label automatically use s, ms, µs, ns, or ps. Use an xlabel without units, such as"Time".