============
Create plots
============

.. image:: ../img/colorCode.svg

SLiCAP output displayed on this manual page, is generated with the script: ``plots.py``, imported by ``Manual.py``.

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 1-10
    :lineno-start: 1

.. image :: /API/img/myPassiveNetwork.svg
    :width: 800
    
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 <../reference/SLiCAPplots.html>`_.

SLiCAP plots are hierarchically structured:

- A `figure <../reference/SLiCAPplots.html#SLiCAP.SLiCAPplots.figure>`_ object is the main object that can be plotted using its ``.plot()`` method.
- The figure's ``.axis`` attribute is a list of lists with `axis <../reference/SLiCAPplots.html#SLiCAP.SLiCAPplots.axis>`_ objects for each row, from left to right.
- The ``.traces`` attribute of each ``axis`` object is a list with `trace <../reference/SLiCAPtraces.html#SLiCAP.SLiCAPtraces.trace>`_ objects that will be plotted the axis. Trace xdata, ydata, lables, colors, markers, etc, are all attributes of a ``trace`` object.

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:

- `plotSweep() <../reference/SLiCAPplots.html#SLiCAP.SLiCAPplots.plotSweep>`_
- `plotPZ() <../reference/SLiCAPplots.html#SLiCAP.SLiCAPplots.plotPZ>`_
- `plot() <../reference/SLiCAPplots.html#SLiCAP.SLiCAPplots.plot>`_

SLiCAP plot functions use the Python module `matplotlib <https://matplotlib.org/>`_. When using SLiCAP built-in plot functions, knowledge about matplotlib is not required.

Built-in plot types
===================

plotSweep()
-----------

`plotSweep() <../reference/SLiCAPplots.html#SLiCAP.SLiCAPplots.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() <../reference/SLiCAPplots.html#SLiCAP.SLiCAPplots.plotPZ>`_ displays X-Y scatter plots. These plots are configured for plotting the results of pole-zero analysis. 

plot()
------

`plot() <../reference/SLiCAPplots.html#SLiCAP.SLiCAPplots.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.

.. code-block::

    >>> 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
    
.. admonition:: note
    :class: 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``:

.. code-block::

    >>> 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/
    
.. admonition:: Important
    :class: note
    
    Plots are always saved, independent of the value of the keyword argument ``show``.
    
Frequency-characteristics
=========================

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 12-14
    :lineno-start: 12

Magnitude
---------

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 16-18
    :lineno-start: 16
    
.. image:: /API/img/f_mag.svg
    :width: 500px

dB Magnitude
------------

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 20-22
    :lineno-start: 20

.. image:: /API/img/f_dBm.svg
    :width: 500px

Phase
-----

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 24-26
    :lineno-start: 24

.. image:: /API/img/f_phs.svg
    :width: 500px

Group delay
-----------

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 28-31
    :lineno-start: 28

.. image:: /API/img/f_del.svg
    :width: 500px

Polar Magnitude-phase
---------------------

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 33-35
    :lineno-start: 33

.. image:: /API/img/p_mag.svg
    :width: 500px

Polar dB magnitude-phase
------------------------

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 37-40
    :lineno-start: 37

.. image:: /API/img/p_dBm.svg
    :width: 500px

Time-domain plots
=================

Unit impulse response
---------------------

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 44-47
    :lineno-start: 44

.. image:: /API/img/delta_t.svg
    :width: 500px

Unit Step response
------------------

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 49-52
    :lineno-start: 49

.. image:: /API/img/mu_t.svg
    :width: 500px

Time-domain response
--------------------

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 54-57
    :lineno-start: 54

.. image:: /API/img/v_time.svg
    :width: 500

Periodic pulse response
-----------------------

Modify trace data and label
~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 59-63
    :lineno-start: 59

.. image:: /API/img/pp_time.svg
    :width: 500px
    
Noise spectrum
==============

Detector-referred noise
-----------------------

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 65-69
    :lineno-start: 65

.. image:: /API/img/onoise_f.svg
    :width: 500px

Contributions to detector-referred noise
----------------------------------------

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 71-74
    :lineno-start: 71

.. image:: /API/img/all_onoise_f.svg
    :width: 500px

Source-referred noise
---------------------

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 76-78
    :lineno-start: 76

.. image:: /API/img/inoise_f.svg
    :width: 500px

Swept parameter plots
=====================

In the circuit model used for this page the parameter :math:`C_b` is defined as a function of the frequency :math:`f_s`.

This function can be plotted using a swept parameter plot.

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 79-86
    :lineno-start: 79

.. image:: /API/img/Cb_fs.svg
    :width: 500px
    
Pole-zero plots
===============

Poles
-----

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 90-92
    :lineno-start: 90

.. image:: /API/img/p_plot.svg
    :width: 350px
    
Zeros
-----

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 94-96
    :lineno-start: 94

.. image:: /API/img/z_plot.svg
    :width: 350px

Observable and controllable poles and zeros
-------------------------------------------

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 98-102
    :lineno-start: 98

.. image:: /API/img/pz_plot.svg
    :width: 350px

Multiple results in one plot
============================

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 104-107
    :lineno-start: 104

.. image:: /API/img/ppzz_plot.svg
    :width: 350px

Parameter stepping
==================

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 109-115
    :lineno-start: 109

Stepped plotSweep()
-------------------

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 117-122
    :lineno-start: 117
    
.. image:: /API/img/f_dBmStepped.svg
    :width: 500px
    
Stepped plotPZ(): root locus plots
----------------------------------

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 124-128
    :lineno-start: 124

A stepped pole-zero plot shows:

- The start end en locations of poles as :math:`\times` and :math:`+`, respectively
- For each step value a dot at the pole location
- The start end en locations of zeros as :math:`\circ` and :math:`\square`, respectively
- For each step value a dot at the zero location

.. image:: /API/img/pzStepped.svg
    :width: 350px
    
Stepped parameter sweep
-----------------------

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 130-142
    :lineno-start: 130
    
.. image:: /API/img/Cb_fs_L.svg
    :width: 500
    
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() <../reference/SLiCAPtraces.html#SLiCAP.SLiCAPtraces.makeDataset>`__
   collects the signals of one or more results in a data set.
#. `make_traces() <../reference/SLiCAPtraces.html#SLiCAP.SLiCAPtraces.make_traces>`__
   makes traces from expressions of those signals.
   `measure() <../reference/SLiCAPtraces.html#SLiCAP.SLiCAPtraces.measure>`__
   takes single values from them.
#. `traceAxis() <../reference/SLiCAPplots.html#SLiCAP.SLiCAPplots.traceAxis>`__,
   `sweepAxis() <../reference/SLiCAPplots.html#SLiCAP.SLiCAPplots.sweepAxis>`__
   and `pzAxis() <../reference/SLiCAPplots.html#SLiCAP.SLiCAPplots.pzAxis>`__
   make axes.
   `makeFigure() <../reference/SLiCAPplots.html#SLiCAP.SLiCAPplots.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 <../../GUI/plots/plots.html>`__ 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
---------

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 181-190
    :lineno-start: 181

``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()``), ``onoise`` and ``inoise``
  (``doNoise()``), and ``time``, ``impulse`` and ``stepResp`` (``doTime()``,
  ``doImpulse()``, ``doStep()``). A noise result also gives one signal per
  noise source, such as ``N.onoise_I_noise_R1``. The circuit parameters are
  available as ``H.R_s``.
- A filter made with ``makeFilter()``: ``H_fs`` and ``H_fz``, the frequency
  responses of its Laplace transfer and of its z-transfer, and ``impulse``
  and ``stepResp``, its sampled responses (see
  `Response of a designed filter <../../system/filters.html>`__).
- 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``, ``num`` and ``method``. The method is ``"log"`` in
  frequency and ``"lin"`` in time, unless you give it. A limit may name a
  parameter whose value is given in ``params``.
- 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() <../reference/SLiCAPtraces.html#SLiCAP.SLiCAPtraces.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: ``dB`` for ``dB()``, ``deg`` for ``phase()``, ``V^2/Hz`` for
  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_10`` gives 10·log10, for a power.
- ``phase``: phase in degrees, unwrapped. ``angle`` gives 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``:

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 206-214
    :lineno-start: 206

.. image:: /API/img/minimum_versus_fs.svg
    :width: 500px

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:

.. code-block:: python

    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:

.. code-block:: python

    >>> 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
-------

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 192-204
    :lineno-start: 192

.. image:: /API/img/traces_axes_figure.svg
    :width: 800px

``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.

- ``shareX`` and ``shareY`` give 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.
- ``title`` is a heading drawn inside the image. It may hold LaTeX.
- The figure is saved as ``img/<fileName>.svg`` and ``img/<fileName>.pdf``.
  The plot window shows the file name in its title bar.
- ``show=True`` opens a plot window, and ``cursors=True`` gives it A/B
  cursors.

Work with traces
================

Extract traces from a figure
----------------------------

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 144-145
    :lineno-start: 144

The function `fig2traces() <../reference/SLiCAPplots.html#SLiCAP.SLiCAPplots.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:

.. code-block:: python

    # 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() <../reference/SLiCAPplots.html#SLiCAP.SLiCAPplots.traces2fig>`_ adds traces to a figure.

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 147-157
    :lineno-start: 147

.. image:: /API/img/all_onoise.svg
    :width: 500
    
Create and plot a dictionary with traces
----------------------------------------

.. literalinclude:: ../plots.py
    :linenos:
    :lines: 159-179
    :lineno-start: 159

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

.. code-block:: python

    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 <balanced.html>`_).

.. image:: /API/img/powers_x.svg
    :width: 500

.. image:: /API/img/colorCode.svg
