Create plots
SLiCAP output displayed on this manual page, is generated with the script: plots.py, imported by Manual.py.
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3"""
4plots.py: SLiCAP scripts for the HTML help file
5"""
6import SLiCAP as sl
7from copy import deepcopy
8import numpy as np
9
10cir = sl.makeCircuit("sch/myPassiveNetwork.slicap_sch")
SLiCAP provides a number of plot functions for pre-formatted plotting of instruction results. Plot types, axis types, trace colors, markers, labels and plot legends are automatically selected from the instruction settings.
Plot functions are collected in the SLiCAP module SLiCAPplots.py.
SLiCAP plots are hierarchically structured:
A figure object is the main object that can be plotted using its
.plot()method.The figure’s
.axisattribute is a list of lists with axis objects for each row, from left to right.The
.tracesattribute of eachaxisobject is a list with trace objects that will be plotted the axis. Trace xdata, ydata, lables, colors, markers, etc, are all attributes of atraceobject.
SLiCAP built-in figures are single-axis figures. Figures with several axes, and traces made from expressions of several results, are composed as described in Traces, axes and figures.
SLiCAP has three built-in plot functions:
SLiCAP plot functions use the Python module matplotlib. When using SLiCAP built-in plot functions, knowledge about matplotlib is not required.
Built-in plot types
plotSweep()
plotSweep() displays traces from expressions with one symbolic variable. It can be used for plotting time-domain responses, frequency-domain responses and swept parameter plots.
plotPZ()
plotPZ() displays X-Y scatter plots. These plots are configured for plotting the results of pole-zero analysis.
plot()
plot() generates X-Y line plots from a dictionary with traces. Such dictionaries can be generated from data from other applications, such as, LTspice, SImetrix, NGspice, or Cadence, or from .csv files.
Plot settings
Plot settings are found in the [plot] section of the SLiCAP.ini file in the project directory. These settings can be changed from within the Python environment.
>>> import SLiCAP as sl
>>> sl.ini.dump("plot")
PLOT
----
ini.gain_colors_gain = b
ini.gain_colors_loopgain = k
ini.gain_colors_asymptotic = r
ini.gain_colors_servo = m
ini.gain_colors_direct = g
ini.gain_colors_vi = c
ini.axis_height = 5
ini.axis_width = 7
ini.line_width = 2
ini.line_type = -
ini.plot_fontsize = 12
ini.marker_size = 7
ini.legend_loc = best
ini.default_colors = ['r', 'b', 'g', 'c', 'm', 'y', 'k']
ini.default_markers = ['']
ini.plot_file_type = svg
ini.svg_margin = 1
ini.plot_points = 4000
note
Pole-zero plots are square plots: the axis width is set to the axis height.
Creating and updating plots
The three built-in plot functions create a figure object. After creation, traces can be added to a plot and the figure objects needs to be updated. The method figure.plot() recreates the plot.
Showing plots
All plot functions have a keyword argument show=False by default. In this way they don’t pop up running a script blocking further execution of the script during pop-up.
Large traces
A trace with more than twice ini.plot_points points, such as an NGspice transient with millions of samples, is drawn reduced. The visible range is cut into ini.plot_points bins and every bin contributes its minimum and its maximum, in order. The envelope and every peak survive at any zoom, as on an oscilloscope. The reduction is redone on every zoom, pan and home. When the visible range holds fewer points than twice the bins, the samples themselves are drawn. The saved image holds the reduced trace of the full range. The A/B cursors read the full data. The crosshair reads the reduced line. Only a trace whose x values are monotonic, a time or frequency sweep, is reduced. Set plotpoints to 0 in the [plot] section of SLiCAP.ini to draw every point.
Saving plots
All plot functions by default store a .pdf graphics file and a graphics file of the type set by ini.plot_file_type in the project image folder set by ini.img_path:
>>> import SLiCAP as sl
>>> sl.ini.dump("paths")
ini.project_path = /home/USR/DATA/SLiCAP/SLiCAP_github/SLiCAP_python/docs/
ini.html_path = html/
ini.cir_path = cir/
ini.img_path = img/
ini.poster_path = posters/
ini.csv_path = csv/
ini.results_path = results/
ini.txt_path = txt/
ini.tex_path = tex/
ini.user_lib_path = lib/
ini.sphinx_path = sphinx/
ini.tex_snippets = tex/SLiCAPdata/
ini.html_snippets = sphinx/SLiCAPdata/
ini.rst_snippets = sphinx/SLiCAPdata/
ini.myst_snippets = sphinx/SLiCAPdata/
ini.md_snippets = sphinx/SLiCAPdata/
Important
Plots are always saved, independent of the value of the keyword argument show.
Frequency-characteristics
12# Swept variable plots
13# Laplace analysis
14laplaceResult = sl.doLaplace(cir, pardefs="circuit", numeric=True)
Magnitude
16# Magnitude
17f_mag = sl.plotSweep("f_mag", "Magnitude plot", laplaceResult, 0.01, 100, 500,
18 sweepScale="M", yUnits="V")
dB Magnitude
20# dB Magnitude
21f_dBm = sl.plotSweep("f_dBm", "dB magnitude plot", laplaceResult, 0.01, 100,
22 500, sweepScale="M", yUnits="V", funcType="dBmag")
Phase
24# Phase
25f_phs = sl.plotSweep("f_phs", "Phase plot", laplaceResult, 0.01, 100, 500,
26 sweepScale="M", yUnits="V", funcType="phase")
Group delay
28# Group delay
29f_del = sl.plotSweep("f_del", "Group delay plot", laplaceResult, 0.01, 100,
30 500, sweepScale="M", yUnits="V", yScale="u",
31 funcType="delay")
Polar Magnitude-phase
33# Magnitude-polar
34p_mag = sl.plotSweep("p_mag", "Magnitude-phase plot", laplaceResult, 0.01, 100,
35 500, axisType="polar", sweepScale="M", yUnits="V")
Polar dB magnitude-phase
37# dB magnitude-polar
38p_dBm = sl.plotSweep("p_dBm", "dB magnitude-phase plot", laplaceResult, 0.01,
39 100, 500, axisType="polar", sweepScale="M", yUnits="V",
40 funcType="dBmag")
Time-domain plots
Unit impulse response
44# Impulse
45impulseResp = sl.doImpulse(cir, pardefs="circuit", numeric=True)
46delta_t = sl.plotSweep("delta_t", "Unit-impulse response", impulseResp,
47 0, 5, 500, sweepScale="u", yScale="M")
Unit Step response
49# Step
50stepResp = sl.doStep(cir, pardefs="circuit", numeric=True)
51mu_t = sl.plotSweep("mu_t", "Unit-step response", stepResp, 0, 5, 500,
52 sweepScale="u")
Time-domain response
54# Time
55timeResp = sl.doTime(cir, pardefs="circuit", numeric=True)
56v_time = sl.plotSweep("v_time", "Time-domain response", timeResp, 0, 5, 500,
57 sweepScale="u")
Periodic pulse response
Modify trace data and label
59# Periodic pulse
60stepResp.stepResp = sl.step2PeriodicPulse(stepResp.stepResp, 20e-9, 1e-6, 3)
61stepResp.label = "3 Pulses response"
62pp_time = sl.plotSweep("pp_time", "Periodic pulse response", stepResp, 0, 5,
63 1000, sweepScale="u")
Noise spectrum
Detector-referred noise
65# Noise spectrum
66noiseResult = sl.doNoise(cir, pardefs="circuit", numeric=True)
67onoise_f = sl.plotSweep("onoise_f", "Detector-referred noise spectrum",
68 noiseResult, 0.01, 100, 500, funcType="onoise",
69 sweepScale="M", yUnits="$V^2/Hz$")
Contributions to detector-referred noise
71all_onoise_f = sl.plotSweep("all_onoise_f", "Contributions to detector-referred noise",
72 noiseResult, 0.01, 100, 500, funcType="onoise",
73 sweepScale="M", yUnits="$V^2/Hz$",
74 noiseSources="all")
Source-referred noise
76inoise_f = sl.plotSweep("inoise_f", "Source-referred noise spectrum",
77 noiseResult, 0.01, 100, 500, funcType="inoise",
78 sweepScale="M", yUnits="$V^2/Hz$")
Swept parameter plots
In the circuit model used for this page the parameter \(C_b\) is defined as a function of the frequency \(f_s\).
This function can be plotted using a swept parameter plot.
79
80# Swept parameter plots
81# Create an instruction result object for plotting
82parResult = sl.doParams(cir)
83# Create the swept-parameter plot
84Cb_fs = sl.plotSweep("Cb_fs", "$C_b$ versus $f_s$", parResult, 1, 5, 100,
85 axisType="semilogy", funcType="param", sweepVar="f_s",
86 sweepScale="M", xUnits="Hz", yVar="C_b", yScale="n",
Pole-zero plots
Poles
90# Plot the poles
91polesResult = sl.doPoles(cir, pardefs="circuit", numeric=True)
92p_plot = sl.plotPZ("p_plot", "Poles", polesResult, xscale="M", yscale="M")
Zeros
94# Plot the zeros
95zerosResult = sl.doZeros(cir, pardefs="circuit", numeric=True)
96z_plot = sl.plotPZ("z_plot", "Zeros", zerosResult, xscale="M", yscale="M")
Observable and controllable poles and zeros
98# Only observable and controllable
99pzResult = sl.doPZ(cir, pardefs="circuit", numeric=True)
100pz_plot = sl.plotPZ("pz_plot", "Observable and controllable poles and zeros",
101 pzResult, xscale="M", yscale="M", xmin=-11, xmax=1,
102 ymin=-6, ymax=6)
Multiple results in one plot
104# Multiple results in one plot
105all_pz = sl.plotPZ("ppzz_plot", "All poles and zeros",
106 [polesResult, zerosResult], xscale="M", yscale="M",
107 xmin=-11, xmax=1, ymin=-6, ymax=6)
Parameter stepping
109# Parameter stepping
110# Define the step parameters
111step_dict = {"params": "f_s",
112 "method": "lin",
113 "start": "1M",
114 "stop": "5M",
115 "num": 5}
Stepped plotSweep()
117# dB Magnitude stepped
118laplaceStepped = sl.doLaplace(cir, pardefs="circuit", stepdict=step_dict,
119 numeric=True)
120f_dBmStepped = sl.plotSweep("f_dBmStepped", "dB magnitude plot", laplaceStepped,
121 0.01, 100, 500, sweepScale="M", yUnits="V",
122 funcType="dBmag")
Stepped plotPZ(): root locus plots
124# Root-locus plots
125pzStepped = sl.doPZ(cir, pardefs="circuit", stepdict=step_dict,
126 numeric=True)
127pz_stepped = sl.plotPZ("pzStepped", "Stepped PZ plot", pzStepped, xscale="M",
128 yscale="M", xmin=-11, xmax=1, ymin=-6, ymax=6)
A stepped pole-zero plot shows:
The start end en locations of poles as \(\times\) and \(+\), respectively
For each step value a dot at the pole location
The start end en locations of zeros as \(\circ\) and \(\square\), respectively
For each step value a dot at the zero location
Stepped parameter sweep
130# Stepped parameter sweep
131# Define the step parameters
132step_dict = {"params": "L",
133 "method": "lin",
134 "start": "1u",
135 "stop": "5u",
136 "num": 5}
137# Create an instruction result object for plotting with parameter stepping
138parResult = sl.doParams(cir, stepdict=step_dict)
139Cb_fs_L = sl.plotSweep("Cb_fs_L", "$C_b$ versus $f_s$", parResult, 1, 5, 100,
140 axisType="semilogy", funcType="param", sweepVar="f_s",
141 sweepScale="M", xUnits="Hz", yVar="C_b", yScale="n",
142 yUnits="F")
Traces, axes and figures
The built-in plot functions make a figure with one axis from one result. Everything else is composed in three layers:
makeDataset() collects the signals of one or more results in a data set.
make_traces() makes traces from expressions of those signals. measure() takes single values from them.
traceAxis(), sweepAxis() and pzAxis() make axes. makeFigure() places axes in a grid and saves the figure.
The Traces, Axes and Figures dialogs of the GUI write these same calls (see Traces, axes and figures in the GUI manual).
Two words have a precise meaning here. A signal is a named output of an
analysis: the vector v(out) of an NGspice run, the attribute
laplace of a doLaplace() result, the stored signal Ix of a
system run. A trace is a curve built from signals with an expression.
Users of LTspice or SIMetrix call both a trace.
Data sets
181# Traces, axes and figures
182# A data set of two results; the keys are the names used in expressions
183D1 = sl.makeDataset({"H": laplaceResult, "N": noiseResult}, x="frequency",
184 start="10k", stop="100M", num=500)
185# Traces: expressions of the signals, evaluated by numpy
186TR1 = sl.make_traces(D1, [{"y": "dB(mag(H.laplace))", "label": "gain"},
187 {"y": "phase(H.laplace)", "label": "phase"},
188 {"y": "N.onoise", "label": "output noise"}])
189# One value with its units: the gain at 1 MHz
190A_1M = sl.measure(D1, "Y_AT_X(dB(mag(H.laplace)), 1e6)", units="dB")
makeDataset() takes a dictionary of results. Its keys are the names the
expressions use: with the key H, the transfer of laplaceResult is
the signal H.laplace. The signals of each kind of result:
A SLiCAP result:
laplace(doLaplace()),numer(doNumer()),denom(doDenom()),onoiseandinoise(doNoise()), andtime,impulseandstepResp(doTime(),doImpulse(),doStep()). A noise result also gives one signal per noise source, such asN.onoise_I_noise_R1. The circuit parameters are available asH.R_s.A filter made with
makeFilter():H_fsandH_fz, the frequency responses of its Laplace transfer and of its z-transfer, andimpulseandstepResp, its sampled responses (see Response of a designed filter).An expression in s, f or t: the signal has the name of its key.
An NGspice result: its saved vectors, such as
AC1.v(out).A system run: the data set of one clock domain,
R1.dataset("CK1").
SLiCAP results, filters and expressions are functions: they are evaluated at the points you ask for. NGspice and system runs are data: they have their own points.
Without data, you give the range:
x("frequency"or"time"),start,stop,numandmethod. The method is"log"in frequency and"lin"in time, unless you give it. A limit may name a parameter whose value is given inparams.With data, a function is evaluated at the points of the data. A function of s or f fits frequency data, a function of t fits time data. In this way a simulation is compared with the expression that models it.
Data of several results must lie on the same points.
A function applies to every run of stepped data.
makeDataset() raises an error for results that do not fit together. It
checks the x variable only. Whether a combination means something is up to
you.
sweepData()
makes the data set of one SLiCAP result. Its signals have fixed names:
H_s for the transfer, N_s and D_s for its numerator and
denominator. makeDataset() is the general form, and the GUI writes it.
Traces
make_traces(data, specs, variables) returns a dictionary of traces,
keyed by their labels. Each entry of specs describes one trace:
"y": the expression to plot, for example"dB(mag(H.laplace))"."x": what to plot it against. By default it is the x variable of the data set."label": the legend text and the key of the trace. Two traces with the label"gain"get the keys"gain"and"gain (2)"."color","yUnits","xUnits": without them, the colour is chosen automatically, and the units follow from the expression and the result:dBfordB(),degforphase(),V^2/Hzfor output noise.Any other key is set as an attribute of the trace, for example
"marker": "o".
Expressions are evaluated by numpy, on numbers. This is numeric
post-processing after the analysis. The whole numpy namespace is
available: every function, and constants such as pi and inf.
pi is therefore the number 3.14159…, not a SymPy symbol, and units are
not tracked. Symbolic work belongs to the SLiCAP functions that act on the
result itself. These functions are added:
mag,abs: magnitude.dB: 20·log10 of a magnitude.dB_10gives 10·log10, for a power.phase: phase in degrees, unwrapped.anglegives radians.delay: group delay.real,imag,sqrt,exp,log,log10.
A complex signal without a function is plotted as its magnitude.
A goal function, written in capitals, reduces a run to one number:
MAX, MIN, MEAN, RMS, RMS_NOISE, INT, SUM,
Y_AT_X(y, x0), X_AT_MAX_Y(y), X_AT_MIN_Y(y),
X_AT_NTH_Y(y, y0, n). The function goal_names() lists them.
A stepped result gives one trace per run, labelled with the step value. A
goal function gives one value per run, and the trace then runs over the
step parameter. Here, the frequency of the notch of laplaceStepped,
stepped over f_s:
206# A goal function reduces each run of a stepped result to one number
207D2 = sl.makeDataset({"HS": laplaceStepped}, x="frequency", start="500k",
208 stop="10M", num=2000)
209TR2 = sl.make_traces(D2, [{"y": "X_AT_MIN_Y(dB(mag(HS.laplace)))",
210 "label": "minimum", "marker": "o"}])
211AX5 = sl.traceAxis("", "lin", TR2, xName="$f_s$", xScale="M", xUnits="Hz",
212 yName="frequency of the minimum", yScale="M",
213 yUnits="Hz")
214FIG2 = sl.makeFigure([[AX5]], "minimum_versus_fs")
NGspice names its vectors v(out), i(v1), onoise_r1. Those are not
Python names. The argument variables gives them one, here for a
simulation compared with its model:
D3 = sl.makeDataset({"AC1": AC1, "LAPLACE1": LAPLACE1})
TR3 = sl.make_traces(D3, [{"y": "dB(mag(AC1.V_out)) - dB(mag(LAPLACE1.laplace))"}],
variables={"AC1.V_out": "AC1.v(out)"})
LAPLACE1 is evaluated at the frequencies of AC1, so no range is
needed. make_traces() also accepts an NGspice result directly, without
a data set: sl.make_traces(AC1, [{"y": "dB(mag(V_out))"}],
variables={"V_out": "v(out)"}).
Measurements
measure(data, expression, step=None, run=None, variables=None,
units="") returns one value with its units, a measurement. The
expression must give one number, so it uses a goal function. In the
example above:
>>> print(A_1M)
-17.918 dB
A dictionary of expressions gives a dictionary of measurements. For stepped
data, step={"f_s": "2M"} or run=2 selects the run to measure.
Axes
traceAxis(title, axisType, plotData, ...) makes an axis with traces.
plotData is a dictionary of traces, a single trace such as
TR1["gain"], or a list of dictionaries. axisType is "lin",
"semilogx", "semilogy", "log" or "polar".
The axis label is made of the name, the scale factor and the units:
xName="frequency", xScale="M", xUnits="Hz" gives
frequency [MHz]. Scale factors belong to the axis, not to the trace.
The trace data stays in base units, so the same trace can be placed on
several axes with different scales. xLim and yLim fix the limits.
sweepAxis() is plotSweep() without the figure, and pzAxis() is
plotPZ() without the figure. They make an axis directly from SLiCAP
results.
Figures
192# Axes: the scale factors belong to the axis, not to the trace
193AX1 = sl.traceAxis("Gain", "semilogx", TR1["gain"], xName="frequency",
194 xScale="M", xUnits="Hz", yName="gain", yUnits="dB")
195AX2 = sl.traceAxis("", "semilogx", TR1["phase"], xName="frequency",
196 xScale="M", xUnits="Hz", yName="phase", yUnits="deg")
197AX3 = sl.traceAxis("Output noise", "log", TR1["output noise"],
198 xName="frequency", xScale="M", xUnits="Hz",
199 yName="noise", yUnits="V^2/Hz")
200AX4 = sl.pzAxis("Poles and zeros", pzResult, xscale="M", yscale="M",
201 xmin=-11, xmax=1, ymin=-6, ymax=6)
202# A figure: a grid of axes; AX1 and AX2 share their x axis
203FIG1 = sl.makeFigure([[AX1, AX3], [AX2, AX4]], "traces_axes_figure",
204 shareX=[[AX1, AX2]], title="One figure, four axes")
makeFigure(axes, fileName, ...) places axes in a grid: a list of rows,
each a list of axes. An empty string is an empty cell. The same axis in
adjacent cells spans them. The cells of a span must form a rectangle.
shareXandshareYgive axes one x or one y axis: a list of groups, such as[[AX1, AX2]], or"col","row"or"all". Shared axes zoom together. A shared column is drawn as one stack: tick labels and axis label on the outer axis only, and only the first title.titleis a heading drawn inside the image. It may hold LaTeX.The figure is saved as
img/<fileName>.svgandimg/<fileName>.pdf. The plot window shows the file name in its title bar.show=Trueopens a plot window, andcursors=Truegives it A/B cursors.
Work with traces
Extract traces from a figure
144# Extract traces from plots
145onoise_trace = onoise_f.traceDict
The function fig2traces()
returns the traces of a figure as a dictionary that can directly be passed
to plot(), optionally filtered by trace label. This works for any
figure, including figures created with plotSweep(), so traces from
different analysis types can be combined in one plot:
# Overlay selected traces from two existing figures in a new plot
sl.plot("cmp", "Compare", "semilogx",
{**sl.fig2traces(fig_a), **sl.fig2traces(fig_b, ["V_out"])})
Add a dictionary with traces to an existing plot
The function traces2fig() adds traces to a figure.
147# Add onoise_trace to a copy of all_onoise_f
148# Create a deepcopy of the figure
149all_oonoise_f = deepcopy(all_onoise_f)
150# Change the file name so we don't overwrite the original
151all_oonoise_f.fileName = "all_onoise"
152# Add the onoise trace to the new figure
153sl.traces2fig(onoise_trace, all_oonoise_f)
154# Don't show it, just save the figure
155all_oonoise_f.show = False
156# Generate and save the figure
157all_oonoise_f.plot()
Create and plot a dictionary with traces
159# Create traces
160x = np.linspace(-1, 1, 100)
161
162y1 = sl.trace([x, x])
163y1.label = "$y=x$"
164
165y2 = sl.trace([x, x**2])
166y2.label = "$y=x^2$"
167
168y3 = sl.trace([x, x**3])
169y3.label = "$y=x^3$"
170
171y4 = sl.trace([x, x**4])
172y4.label = "$y=x^4$"
173
174trc_dict = {"y1": y1, "y2": y2, "y3": y3, "y4": y4}
175
176# Plot a dictionary with traces
177
178pwrs_x = sl.plot("powers_x", "Powers of $x$", "lin", trc_dict,
179 xName = "x", yName="y")
Derived traces: expressions of simulation results
A trace can be computed from the signals of a simulation, as a waveform
expression in LTspice or SIMetrix. make_traces() does this: the
common-mode output voltage of a transient analysis is
TR = sl.make_traces(TRAN1, [{"y": "(V_1 + V_2)/2", "label": "$V_{cm}$"}],
variables={"V_1": "v(1)", "V_2": "v(2)"})
See Traces, axes and figures. For SLiCAP, balanced circuits can also be
converted into differential-mode and common-mode equivalents with the
convtype argument (see Balanced circuits).