SLiCAPtraces.py
Trace objects and post-processing of numeric simulation results.
A trace holds the numeric data of ONE run - x values, y values - together
with the presentation attributes that belong to the data itself (label,
colour, marker, line style). Traces are placed on an axis and axes on a
figure; both live in SLiCAP.SLiCAPplots.
This module is deliberately backend neutral: it knows about named numeric arrays, sweeps, runs, expressions and goal functions - never about NGspice, raw files, sympy result types or matplotlib. Dependencies point one way only:
producers (NGspice, csv, LTspice, Cadence, SLiCAP results)
-> SLiCAPtraces (data)
-> SLiCAPplots (axis, figure, rendering)
See TRACES.md for the architecture and the phased plan.
trace is re-exported by SLiCAP.SLiCAPplots, so both
from SLiCAP.SLiCAPplots import trace and sl.trace keep working.
- as_dataset(obj)
A
datasetfor obj, or None when nothing can convert it.Accepts a dataset unchanged and asks the registered producer adapters (NGspice results, …) for anything else.
- automatic_color(index, gain_type=None, single_run=True)
The colour a trace gets when its specification names none.
SLiCAP colours the gain types of the asymptotic-gain model by CONVENTION - asymptotic red, gain blue, loopgain black, servo magenta, direct green (
ini.gain_colors_*) - which is what makes a set of five transfers readable in one plot.plotSweephas always done this; the new path did not, so five results each holding one trace all came out red (Anton,The colour identifies the RESULT, so EVERY trace built from a named gain type gets it - a magnitude and a phase of the same transfer are the same thing seen twice, and they land on different axes ( with two expressions per set the colours went red/blue again). Only the RUNS of a stepped result take the cycle instead: those must be told apart from each other on one axis.
- Parameters:
index (int) – position of the trace in its set.
gain_type (str, NoneType) – gain type of the result it came from, None for data that has none (an NGspice run, a csv import).
single_run (bool) – False when the result was stepped - then the runs are distinguished by the colour cycle instead.
- Returns:
matplotlib colour.
- Return type:
str
- axis_label(name, scale='', units='')
The text of an axis label:
name [scale units], with the units set as text throughSLiCAP.SLiCAPmath.units2text()(Ohm as the ohm sign, the prefix u as the micro sign, exponents as superscripts). The ONE builder of axis labels (2026-09-12): plotSweep, plotPZ, plot and the GUI axes dialog all call it, so a script and the GUI write the same label.- Parameters:
name (str) – quantity, may contain Matplotlib mathtext (‘$V_{out}$’).
scale (str) – scale factor letter (‘’, ‘k’, ‘u’, …).
units (str) – units in SLiCAP spelling (‘V’, ‘V^2/Hz’, ‘rad/s’, ‘Ohm’).
- Returns:
the label, ‘’ when name, scale and units are all empty.
- Return type:
str
- class dataset(x_name=None, x_data=None, signals=None, step_params=None, params=None, units=None, gain_type=None, sampled=False)
Numeric arrays of one analysis, backend neutral.
Producers (NGspice, measurement import, evaluated SLiCAP results) build a dataset;
make_traces()turns it into traces. Stating the provenance explicitly replaces guessing it back from array lengths.- Parameters:
x_name (str, NoneType) – Name of the sweep variable, None for an OP result.
x_data (numpy.ndarray, NoneType) – Sweep values, shape (n_sweep,); None for an OP result.
signals (dict) –
{name: array}; 1-D for an un-stepped sweep or a stepped OP, 2-D (n_runs, n_sweep) for a stepped sweep.step_params (dict) –
{name: one value per run}. Empty when the analysis was not stepped; more than one entry for multi-parameter (array) stepping.params (dict) –
{name: value}of the circuit parameters as they were SIMULATED - the circuit’s definitions with the per-instructionparams=overrides applied. Numeric (float): the producer resolves the symbolic definitions, this layer only substitutes. A stepped parameter is not here but in step_params, because it has a value per run.units (dict) –
{signal name: units}for what only the PRODUCER can know - SLiCAP’slaplaceis detector units over source units,onoiseis detUnits^2/Hz ( units are a property of the trace variable, and a name convention cannot answer these). The abscissa is in here under its own name. Signals not listed fall back to the naming conventions ofunits_of().gain_type (str, NoneType) – gain type of the analysis this came from (‘gain’, ‘asymptotic’, ‘loopgain’, ‘servo’, ‘direct’, ‘vi’), None for data that has none. It decides the automatic trace COLOUR, SLiCAP’s convention for the five transfers of the asymptotic-gain model.
sampled (bool) – True when the signals are samples at discrete instants, such as the time-domain response of a discrete filter:
make_traces()then draws them as points, unless a trace specification gives a style (Anton, 2026-11-24).
- property n_runs
Number of runs: 1 when the analysis was not stepped.
- property stepped
True when the analysis has more than one run.
- default_color(index)
The index-th colour of the default cycle (
ini.default_colors).ONE definition of the cycle:
make_traces()colours a trace with it and a GUI previews the same colour, so the swatch cannot disagree with the plot.- Parameters:
index (int) – position of the trace in its set.
- Returns:
matplotlib colour.
- Return type:
str
- function_names()
The functions a trace expression may use, as
{name: description}.The one place the list is defined: the GUI’s “Insert Function” menu and the manual read it from here, so a function added to
_TRACE_FUNCTIONSappears in both without further work - the same arrangement asgoal_names().- Returns:
{name: description}- Return type:
dict
- goal_names()
The goal functions as an expression writes them: the registry’s display name in upper case with the spaces as underscores (‘y at x’ ->
Y_AT_X), with the parameters that follow the signal.Upper case for two reasons: it marks a token as REDUCING one run to one number, and
max/minare already taken by the builtins the expression layer needs. A goal function added to a goal function appears in expressions - and in the GUI menu, which reads its names from here - without further work.- Returns:
{name: [(parameter label, default), …]}- Return type:
dict
- makeDataset(sources, x=None, start=None, stop=None, num=None, method=None, params=None)
Builds ONE
SLiCAPtraces.datasetfrom named results, forSLiCAPtraces.make_traces()andSLiCAPtraces.measure()(TRACES.md phase 9, Anton, 2026-11-25). Its columns carry dotted names, the names of the Design data, so one expression can combine several results:D1 = sl.makeDataset({"AC1": AC1, "LAPLACE1": LAPLACE1}) TR1 = sl.make_traces(D1, [{"y": "dB(mag(AC1.V_out)) - dB(mag(LAPLACE1.laplace))"}], variables={"AC1.V_out": "AC1.v(out)"}) D2 = sl.makeDataset({"FLT1": FLT1, "FLT2": FLT2}, x="frequency", start="79.99M", stop="80.01M", num=500, method="lin") TR2 = sl.make_traces(D2, [{"y": "dB(mag(FLT1.H_fs + FLT2.H_fs))"}])
A source is DATA or gives FUNCTIONS:
data: an NGspice run, a system run’s dataset (
R1.dataset("ref")) or any dataset: its signals asNAME.signal, on its own points;a filter made with
makeFilter(): in frequency the functionsNAME.H_fsandNAME.H_fz; in time DATA,NAME.impulseandNAME.stepRespat the sample times k Ts from start to stop;a SLiCAP result:
NAME.laplace,NAME.numer,NAME.denom,NAME.onoise,NAME.inoiseandNAME.onoise_<source>(frequency) orNAME.time,NAME.impulse,NAME.stepResp(time), one row per run when it is stepped;an expression in s, f or t, such as
FLT1.H_fs + FLT2.H_fs: the columnNAME.
Functions are evaluated where the data lie: an expression in s or f on a frequency axis (s = j 2 pi f), one in t on a time axis. Data of several sources must lie on the same points; resampling was REJECTED (Anton, 2026-11-25): interpolation is not exact. Without data the range is given: x (“frequency” or “time”), start, stop, num and method (“log” or “lin”, default “log” in frequency and “lin” in time); a limit may name a parameter of params, as in sweepData() (Anton, 2026-11-09). The circuit parameters of a source are
NAME.parameter. Data without an axis (an operating point) can only stand alone: its signals are measured, not combined.Errors, not warnings, like makeFilter(): the dataset is used further on. The tool checks the abscissa only, never the units or the meaning (Anton, 2026-11-25).
- Parameters:
sources (dict) –
{name: source}; a name is a Python identifierx (str, NoneType) – “frequency” or “time” when no data source fixes the axis
start – start of the range, SLiCAP notation; for the sample times of a filter in time also with data
stop – end of the range, as start
num – number of points, without data
method – “log” or “lin”, without data
params (dict, NoneType) – parameter definitions for limits that name a parameter, the dict
selectPars()returns
- Returns:
the dataset
- Return type:
- Raises:
ValueError – a source it cannot use, or sources that do not match
- make_traces(data, specs=None, variables=None)
Builds a dictionary of
traceobjects from adataset.- Parameters:
data (SLiCAPtraces.dataset, SLiCAPinstruction.instruction) – the numeric arrays and their step provenance - a
dataset, or an analysis result a registered producer can convert (an NGspice op/dc/ac/tran/noise result).specs (list, NoneType) –
list of trace specifications; a plain string is shorthand for
{"y": name}. Defaults to None: one spec per signal.y: signal name, or an EXPRESSION over the named signals, the circuit parameters and the goal functions (see below).x: expression for the ABSCISSA, evaluated exactly likey. Defaults to None: the sweep variable, or the step parameter / run number whenyreduces each run to one value. Both sides must agree in shape - two arrays give a parametric curve per run, two reduced values give one trace whose points are the runs (a design-space curve). Data order is kept, never sorted.label: label of the trace; defaults to None, the label of the table in the manual, or the expression itself.other keys: attributes set on the trace object (
color,marker,lineWidth, …)
variables (dict, NoneType) –
{python_name: simulator_vector}- what the signals are CALLED in expressions. The simulator writes its own vector names (v(out),@q1[gm],x1.mid,onoise_q1_rb), which are not Python identifiers; this mapping is chosen AFTER the run, when the vectors are known (it used to sit in the analysis call, where it could only guess). A vector not listed keeps its own name and stays usable when that name happens to be an identifier.
- Returns:
{label: trace}- Return type:
dict
Expressions are evaluated by numpy, on numbers. This is the numeric post-processing layer: the arrays are
numpy.ndarrayand nothing is symbolic, so an expression may use the whole numpy namespace - every function (sqrt,exp,fft.rfft,convolve, …) and every constant (pi,e,inf,nan).piis therefore the float 3.141592…, not the sympy symbol of a SLiCAP expression, and units are not tracked. Usesl.doLaplaceand the SLiCAP math functions where symbolic results are wanted.An expression is written over IDENTIFIER names: the signals named with
variables=, the sweep variable, the circuit parameters as simulated, the step parameters (their value for the run), and the goal functions in upper case (RMS,MEAN,Y_AT_X, …;sl.RMSis accepted as well). Raw simulator names -v(out),@q1[gm]- are not identifiers: assign them a Python name withvariables=.The names are bound in this order: numpy, goal functions, circuit parameters, step parameters, sweep variable, signals. The DATA therefore wins on a clash - a signal or parameter of your own called
pishadows the numpy constant, so a circuit’s names can never be captured by a numpy spelling.An expression is evaluated PER RUN and its result decides the outcome: an array gives one trace per run, a number per run gives one trace against the step parameter, and an
(x, y)pair brings its own abscissa.The default label is
y vs x, which is what a plot shows, with the step parameter appended per run when there is one.trace.xNameandtrace.yName- the column headings oftrace.makeTable()- carry the two expressions, so an exported table is readable.- Example:
>>> T = sl.make_traces(AC1, [{"y": "V_outp - V_outn", "color": "r"}, ... {"y": "RMS(I_V1**2*R_a)"}, ... {"y": "Y_AT_X(V_outp, 1e3)"}]) >>> P = sl.make_traces(AC1, [{"x": "real(V_out)", "y": "imag(V_out)"}]) >>> D = sl.make_traces(AC1, [{"x": "RMS(I_V1)**2*R_a", "y": "MAX(V_out)", ... "label": "gain vs dissipation"}])
- measure(data, expression, step=None, run=None, variables=None, units='')
Measures ONE value from a simulation result - or several, given a dict.
A measurement is n x 1: n variables at one condition. The expression is the SAME language the traces use - the goal functions reduce a run to one number, the circuit parameters and the assigned Python names are in scope - and step / run say WHICH condition, which is data selection rather than mathematics.
- Parameters:
data (SLiCAPtraces.dataset, SLiCAPinstruction.instruction) – the result, or a
dataset.expression (str, dict) – one expression, or
{name: expression}for several values of the same result (an operating point).step (dict, float, NoneType) – the condition, by step VALUE:
{"C_c": 18e-12}, or the bare value when one parameter was stepped.run (int, NoneType) – the condition, by run number (1-based) - for array stepping, where there is no single value to name.
variables (dict, NoneType) –
{python_name: simulator_vector}, as inmake_traces().units (str, dict) – units of the value, or
{name: units}for a dict of expressions. User-assigned; SLiCAP does not derive them.
- Returns:
a
measurement, or{name: measurement}; None (or an empty dict) when the expression cannot be measured.- Return type:
SLiCAPtraces.measurement, dict, NoneType
- Example:
>>> V_n = sl.measure(NOISE1, "RMS_NOISE(onoise_spectrum)", units="V") >>> A_0 = sl.measure(AC1, "Y_AT_X(dB_20(V_out), 1e3)", ... step={"C_c": 18e-12}, ... variables={"V_out": "v(out)"}, ... units="dB") >>> OP = sl.measure(OP1, {"I_c": "i(v2)", "V_ce": "v(c) - v(e)"}, ... units={"I_c": "A", "V_ce": "V"})
- class measurement(value, units='')
One measured value: a number taken from a simulation result, with its units.
A measurement is an n x 1 object - n variables at ONE condition - where a trace is 1 x m: one variable across m conditions (Anton, A trace is therefore a row of measurements of the same variable, and this class is one entry of such a row.
It carries only what DISPLAY needs. Where the number came from - which result, which expression, which step - is the call that produced it, in the instruction file, and that call is re-executed on every run: SLiCAP auto-updates, so a copy of the provenance on the object could only go stale.
- Parameters:
value (float) – the measured number.
units (str) – units of the value, assigned by the user (‘V’, ‘A’, ‘V^2/Hz’, ‘dB’); SLiCAP does not derive them.
- Example:
>>> V_n = sl.measure(NOISE1, "RMS_NOISE(onoise_spectrum)", units="V") >>> print(V_n) 1.71812e-06 V
- value
The measured number (float).
- reduces(expression, signals=None)
True when expression collapses a run to one number, judged from its STRUCTURE: every reference to run data sits inside a goal-function call.
Used to pre-fill the x axis in the GUI: as soon as y reduces, the natural abscissa is the step parameter instead of the sweep variable. Searching the text for a goal name cannot answer this -
V_out/MAX(V_out)mentions a goal but stays a curve against the sweep variable, because the bareV_outis evaluated per sweep point.The real behaviour of
make_traces()follows the SHAPE the expression returns, which is authoritative; this is the static approximation of it.- Parameters:
expression (str) – trace expression in numpy syntax.
signals (list, set, NoneType) – names that hold run data. Circuit parameters and constants are scalars and do not stop a reduction, so
RMS(V_out)/R_areduces. Defaults to None: every name is taken to be run data, the conservative reading.
- Returns:
True when the expression reduces a run to a single value.
- Return type:
bool
- Example:
>>> names = ["V_out"] >>> sl.reduces("RMS(V_out)", names), sl.reduces("RMS(V_out)/R_a", names) (True, True) >>> sl.reduces("V_out/MAX(V_out)", names), sl.reduces("V_out*2", names) (False, False)
- register_dataset_adapter(function)
Register
function(obj) -> dataset or None, used byas_dataset()to accept a producer’s result object.
- register_units_hint(function)
Register
function(name, result) -> units str or None, asked byunits_of()for the producer’s own signal spellings.
- run_table(data, columns=False)
The step parameters per run: what a multi-parameter stepped label cannot carry.
With more than one step parameter a trace label can only hold the run number, so the values belong in a table - in the figure caption or in the running text. It comes from the same data set as the traces, so the table and the labels cannot drift apart.
- Parameters:
data (SLiCAPtraces.dataset, SLiCAPinstruction.instruction) – data set or analysis result.
columns (bool) – False (default) returns one dict per run, with ‘run’ first. True returns
(names, columns): the parameter names and a list of values per parameter - the argument pair taken by thestepArray()method of the RST, LaTeX and TXT formatters.
- Returns:
list of dicts, or (names, columns); empty when not stepped.
- Return type:
list, tuple
- Example:
>>> OP4 = sl.op("amp", step={"method": "array", "params": ["V_S", "TEMP"], ... "values": [[9, 0], [12, 25], [15, 50]]}) >>> sl.run_table(OP4) [{'run': 1, 'V_S': 9.0, 'TEMP': 0.0}, ...] >>> names, cols = sl.run_table(OP4, columns=True) >>> rst.stepArray(names, cols, caption="Run parameters").save("runs")
- sweepData(results, sweepStart, sweepStop, sweepNum, sweepMethod='auto', sweepVar='auto', params=None)
Evaluates a SLiCAP result over a sweep and returns the numbers as a
SLiCAPtraces.dataset, ready forSLiCAPtraces.make_traces()andSLiCAPtraces.measure().A SLiCAP result is SYMBOLIC - laplace is an expression in s - so it has no sweep of its own; NGspice hands over numbers, SLiCAP hands over a formula. This function supplies the missing sweep, which is why the traces dialog asks for start / stop / points
It lives in SLiCAPtraces: building a dataset is the entry of the traces layer (producers -> traces -> plots). It was in SLiCAPplots and MOVED here (Anton, 2026-11-25).
The signals are named after what they are (
SWEEP_SIGNAL_NAMES):H_s, N_s, D_s: the transfer (
laplace), its numerator (numer) and its denominator (denom), COMPLEX arrays with s replaced by 2*pi*j*f (ini.hz) or j*omega.mag(...),dB(mag(...)),phase(...)anddelay(...)give the magnitude, the magnitude in dB, the phase and the group delay;noise:
onoiseandinoise(V^2/Hz), plus one signal per noise source fromonoiseTerms/inoiseTerms, namedonoise_<source>- the symbolic counterpart of NGspice’sonoise_r1;time, impulse, step: real arrays over t.
A stepped result carries one expression per run, so its signals become 2-D (n_runs, n_sweep) and
step_paramsholds the step values - exactly like a stepped NGspice sweep. The circuit’s numeric parameter definitions becomedataset.params.A filter made with
makeFilter()and several results together are combined bymakeDataset(). Two forms of this function built during 6.5.0 were REMOVED (Anton, 2026-11-25): a plain expression with the fixed name H_s, and a filter with the columns H_s, H_z, impulse, step.Trace data stays in BASE UNITS (Hz, s, V): scaling belongs to the axis, never to the trace, so this function has no counterpart of
plotSweep’s sweepScale.- Parameters:
results (SLiCAPinstruction.instruction) – result of one SLiCAP instruction.
sweepStart (str, float, int) – start of the sweep; SLiCAP notation (‘10’, ‘1M’), or the name of a parameter,
"f_min", resolved from the parameter definitions of the result (thepardefsof the instruction) with params on top. A sweep limit then follows the specs like a component value does (Anton, 2026-11-09).sweepStop (str, float, int) – end of the sweep; as sweepStart.
sweepNum (str, int) – number of points.
sweepMethod (str) – ‘lin’ or ‘log’; ‘auto’ takes ‘log’ for a frequency sweep and ‘lin’ for a time sweep.
sweepVar (str) – name of the swept parameter for
dataType='params'; ‘auto’ for the frequency or time sweep of the other data types.params (dict, NoneType) – parameter definitions for the sweep limits, on top of those of the result: the dictionary
selectPars()returns,params=sl.selectPars(cir, specs, specs=["t_settle"]), for a specification the instruction itself did not select.
- Returns:
the evaluated data, or None when the result cannot be swept.
- Return type:
SLiCAPtraces.dataset, NoneType
- Example:
>>> D = sl.sweepData(LAPLACE1, 10, "1M", 200) >>> TR = sl.make_traces(D, [{"y": "dB(mag(H_s))"}]) >>> A_0 = sl.measure(D, "Y_AT_X(dB(mag(H_s)), 1e3)", units="dB")
- class trace(traceData)
Trace prototype.
Traces are plotted on axes, which are part of a figure.
- Parameters:
traceData (list) – list with list array-like X and Y data of the trace.
- Example:
>>> x_data = np.linspace(0, 2*np.pi, 50) >>> y_data = np.sin(x_data) >>> sin_trace = trace([x_data, y_data])
- color
Trace color (str) in matplotlib format. Defaults to False.
- label
Trace label (str) that will be displayed in legend box. Defaults to ‘’.
- lineType
Line type (str) in matplotlib format. Defaults to ‘-‘.
- lineWidth
Line width (int) in pixels. Defaults to 2.
- makeTable()
Returns a table with trace data in CSV format.
- Returns:
table: CSV table with column headings and x-data and y-data in columns
- Return type:
str
- Example:
>>> x_data = np.linspace(0, 2*np.pi, 10) >>> y_data = np.sin(x_data) >>> sin_trace = trace([x_data, y_data]) >>> sin_trace.yName = 'sin(x)' >>> print(sin_trace.makeTable()) x,sin(x) 0.000000000000e+00, 0.000000000000e+00 6.981317007977e-01, 6.427876096865e-01 1.396263401595e+00, 9.848077530122e-01 2.094395102393e+00, 8.660254037844e-01 2.792526803191e+00, 3.420201433257e-01 3.490658503989e+00, -3.420201433257e-01 4.188790204786e+00, -8.660254037844e-01 4.886921905584e+00, -9.848077530122e-01 5.585053606382e+00, -6.427876096865e-01 6.283185307180e+00, -2.449293598295e-16
- marker
Marker type (str) in matplotlib format. Defaults to False.
- markerColor
Marker color (str) in matplotlib format. Defaults to False.
- markerFaceColor
Marker face color (str) in matplotlib format. Defaults to ‘none’.
- markerSize
Marker size (int). Defaults to 7.
- xData
Array-like data for the x-axis of the trace. On a polar axes this is the angle in radians.
- xName
Heading (str) for the x column of a table. Defaults to ‘x’.
- xUnits
Units of self.xData
- yData
Array-like data for the y-axis of the trace. On a polar axes this is the radius.
- yName
Heading (str) for the y column of a table. Defaults to ‘y’.
- yUnits
Units of self.yData
- units_of(name, result=None, known=None)
The units the NAME name implies, or ‘’ when no convention says so.
Used to pre-fill the units field of an axis. It is a SUGGESTION: the user states the units, and this saves the typing where a name carries its meaning:
frequency -> Hz (rad/s) V_out, v(out) -> V time, t -> s I_V1, i(v1) -> A abs(V_out)**2/R_a -> '' (an expression)
The empty answer is the important one - a guess in a units field is worse than an empty field.
- Parameters:
name (str) – signal, abscissa or expression name.
result (SLiCAPinstruction.instruction, NoneType) – the analysis result the name came from, when available. A producer hint may need it - the units of SLiCAP’s
onoisefollow the DETECTOR, not the name.known (dict, NoneType) –
{name: units}the producer supplied (a dataset’sunits). Consulted FIRST: what the producer knows beats any convention.
- Returns:
units, or ‘’ when nothing knows them.
- Return type:
str