"""
.. inheritance-diagram:: pyopus.simulator.vacask
:parts: 1
**VACASK batch mode interface (PyOPUS subsystem name: VASI)**
VACASK is a free Verilog-A based circuit simulator. This module uses it in
batch mode.
The circuit is loaded and elaborated once per job group. Simulator options,
circuit variables (parameters), and save directives are set in the control
block for every job separately. Consequently jobs with identical circuit
definitions are joined in the same job group.
The ``temperature`` parameter represents the circuit's temperature in degrees
centigrade (``temp`` simulator option). The ``temp`` simulator option is not
allowed to appear in the simulator options list.
A job sequence in VACASK is a list of lists containing the indices of jobs
belonging to individual job groups.
Every job produces one raw file holding one plot. See
:mod:`pyopus.simulator.rawfile` module for the details on the result files.
The analysis command of a job is a Python expression that evaluates to a
tuple (*sweeps*, *analysis*, *sweepDepth*). *sweeps* is a list of VACASK
sweep directives (outermost first) that are written in front of the
analysis, *analysis* is the analysis specification, and *sweepDepth* is
the number of outer sweeps whose sweep points are split into separate
results. Swept analyses are built with ``an()`` (:func:`an_general`) and
``sweep()`` (:func:`an_sweep`). Sweep points are accessed with the
:meth:`~VacaskSimulationResults.sweepPointCount`,
:meth:`~VacaskSimulationResults.sweepPoint`, and
:meth:`~VacaskSimulationResults.sweepVars` methods of
:class:`VacaskSimulationResults`.
"""
import subprocess
from .base import Simulator, SimulationResults
from .rawfile import raw_read
import os
import re
import platform
import shutil
import numpy as np
import copy
from ..misc.env import environ
from ..misc.debug import DbgMsgOut, DbgMsg
from .. import PyOpusError
__all__ = [ 'ipath', 'save_all', 'save_voltage', 'save_current',
'save_dvoltage', 'save_dcurrent', 'save_property',
'an_op', 'an_dc', 'an_tf', 'an_ac', 'an_tran', 'an_noise', 'an_sweep', 'an_general', 'Vacask',
'VacaskSimulationResults' ]
simulatorDescription=("Vacask", "VACASK")
"""
For detecting simulators.
"""
def _quoteName(name):
"""
Returns *name* as a VACASK identifier. Names that are not valid unquoted
identifiers are put in single quotes.
"""
name=str(name)
if re.fullmatch(r'[A-Za-z_$][A-Za-z0-9_$]*', name):
return name
else:
return "'"+name.replace("'", "''")+"'"
def _valueStr(value):
"""
Converts a Python value to its VACASK representation.
* ``bool`` becomes ``1`` or ``0``
* integers and reals are converted with :func:`str`
* strings are double quoted
* lists and NumPy arrays become vectors (``[...]``)
* tuples become lists (``{...}``)
"""
if isinstance(value, (bool, np.bool_)):
return '1' if value else '0'
elif isinstance(value, (int, float, np.integer, np.floating)):
return str(value)
elif isinstance(value, str):
return '"'+value.replace('\\', '\\\\').replace('"', '\\"')+'"'
elif isinstance(value, (list, np.ndarray)):
return '['+', '.join([_valueStr(v) for v in value])+']'
elif isinstance(value, tuple):
return '{'+', '.join([_valueStr(v) for v in value])+'}'
else:
raise PyOpusError(DbgMsg("VASI", "Cannot convert value of type '"+type(value).__name__+"'."))
[docs]
def ipath(input, outerHierarchy=None, innerHierarchy=None, objectType='inst'):
"""
Constructs a hierarchical path for the instance with name given by *input*.
The object is located within *outerHierarchy* (a list of instances with
innermost instance listed first). *innerHierarchy* a list of names
specifying the instance hierarchy inner to the *input* instance. The
innermost instance name is listed first. If *outerHierarchy* is not given
*input* is assumed to be the outermost element in the hierarchy. Similarly
if *innerHierarchy* is not given *input* is assumed to be the innermost
element in the hierarchy.
Returns a string representing a hierarchical path.
If *input* is a list the return value is also a list representing
hierarchical paths corresponding to elements in *input*.
*innerHierarchy* and *outerHierarchy* can also be ordinary strings
(equivalent to a list with only one string as a member).
The *objectType* argument is for compatibility with other simulators.
Because VACASK treats the hierarchical paths of all objects in the
same way, the return value does not depend on *objectType*. The available
values of *objectType* are ``'inst'``, ``'mod'``, and ``'node'``.
VACASK hierarchical paths begin with the outermost instance followed
by its enclosed instances. Colon (``:``) is used as the separator between
instances in the hierarchy. So ``x2:x1:m1`` is an instance named ``m1``
that is a part of ``x1`` (inside ``x1``) which in turn is a part of ``x2``
(inside ``x2``).
Some examples:
* ``ipath('m1', ['x1', 'x2'])`` - instance named ``m1`` inside ``x1``
inside ``x2``. Returns ``'x2:x1:m1'``.
* ``ipath('x1', innerHierarchy=['m0', 'x0'])`` - instance ``m0`` inside
``x0`` inside ``x1``. Returns ``'x1:x0:m0'``.
* ``ipath(['m1', 'm2'], ['x1', 'x2']) - instances ``m1`` and ``m2`` inside
``x1`` inside ``x2``. Returns ``['x2:x1:m1', 'x2:x1:m2']``.
* ``ipath(['xm1', 'xm2'], ['x1', 'x2'], 'm0')`` - instances named ``m0``
inside paths ``x2:x1:xm1`` and ``x2:x1:xm2``. Returns
``['x2:x1:xm1:m0', 'x2:x1:xm2:m0']``.
"""
if outerHierarchy is None:
prefStr=''
else:
if type(outerHierarchy) is str:
prefStr=outerHierarchy+':'
else:
prefStr=':'.join(reversed(outerHierarchy))+':'
if innerHierarchy is None:
suffStr=''
else:
if type(innerHierarchy) is str:
suffStr=':'+innerHierarchy
else:
suffStr=':'+':'.join(reversed(innerHierarchy))
if type(input) is not list:
return prefStr+input+suffStr
else:
result=[]
for inst in input:
result.append(prefStr+inst+suffStr)
return result
[docs]
def save_all():
"""
Returns a save directive that saves all results the analysis normally
saves in its output.
Equivalent of VACASK ``save default`` simulator command.
"""
return [ 'default' ]
[docs]
def save_voltage(what):
"""
If *what* is a string it returns a save directive that instructs the
simulator to save the voltage of node named *what* in simulator output.
If *what* is a list of strings multiple save directives are returned
instructing the simulator to save the voltages of nodes with names given
by the *what* list.
Applies to op, dc, and tran analyses and to the operating point results
of small signal analyses.
Equivalent of VACASK ``save v(what)`` simulator command.
"""
compiledList=[]
if type(what) is list:
input=what
else:
input=[what]
for name in input:
compiledList.append('v('+_quoteName(name)+')')
return compiledList
[docs]
def save_current(what):
"""
If *what si a string it returns a save directive that instructs the
simulator to save the current flowing through instance names *what* in
simulator output. If *what* is a list of strings multiple save diretives
are returned instructing the simulator to save the currents flowing
through instances with names given by the *what* list.
Applies to op, dc, and tran analyses and to the operating point results
of small signal analyses.
Equivalent of VACASK ``save i(what)`` simulator command.
"""
compiledList=[]
if type(what) is list:
input=what
else:
input=[what]
for name in input:
compiledList.append('i('+_quoteName(name)+')')
return compiledList
[docs]
def save_dvoltage(what):
"""
If *what* is a string it returns a save directive that instructs the
simulator to save the small signal voltage of node named *what* in
simulator output. If *what* is a list of strings multiple save directives
are returned instructing the simulator to save the small signal voltages
of nodes with names given by the *what* list.
Applies to ac analysis.
Equivalent of VACASK ``save dv(what)`` simulator command.
"""
compiledList=[]
if type(what) is list:
input=what
else:
input=[what]
for name in input:
compiledList.append('dv('+_quoteName(name)+')')
return compiledList
[docs]
def save_dcurrent(what):
"""
If *what is a string it returns a save directive that instructs the
simulator to save the small signal current flowing through instance
names *what* in simulator output. If *what* is a list of strings multiple
save diretives are returned instructing the simulator to save the small
signal currents flowing through instances with names given by the *what*
list.
Applies to ac analysis.
Equivalent of VACASK ``save di(what)`` simulator command.
"""
compiledList=[]
if type(what) is list:
input=what
else:
input=[what]
for name in input:
compiledList.append('di('+_quoteName(name)+')')
return compiledList
[docs]
def save_property(devices, params, indices=None):
"""
Saves the properties given by the list of property names in *params* of
instances with names given by the *devices* list.
If *params* and *devices* have n and m memebrs, n*m save directives are
returned describing all combinations of device name and property name.
VACASK does not support vector properties. Specifying *indices* raises
an error.
Equvalent of VACASK ``save p(device, property)`` simulator command.
"""
compiledList=[]
if type(devices) is list:
inputDevices=devices
else:
inputDevices=[devices]
if type(params) is list:
inputParams=params
else:
inputParams=[params]
if indices is not None:
raise PyOpusError(DbgMsg("VASI", "Vector properties are not supported."))
for name in inputDevices:
for param in inputParams:
compiledList.append('p('+_quoteName(name)+', '+_quoteName(param)+')')
return compiledList
def _sweepSpec(start, stop, sweep, points):
"""
Returns the VACASK sweep range specification. For ``'lin'`` sweeps
*points* is the number of points (VACASK uses the number of intervals).
"""
if sweep == 'lin':
return 'from='+str(start)+' to='+str(stop)+' mode="lin" points='+str(points-1)
elif sweep == 'dec':
return 'from='+str(start)+' to='+str(stop)+' mode="dec" points='+str(points)
elif sweep == 'oct':
return 'from='+str(start)+' to='+str(stop)+' mode="oct" points='+str(points)
else:
raise PyOpusError(DbgMsg("VASI", "Bad sweep type."))
def _outSpec(outp, outn, outcur, anName):
"""
Returns the VACASK output specification.
"""
if outcur is not None and outp is None and outn is None:
return _valueStr(str(outcur)+':flow(br)')
elif outcur is None and outp is not None and outn is None:
return _valueStr(str(outp))
elif outcur is None and outp is not None and outn is not None:
return _valueStr([str(outp), str(outn)])
else:
raise PyOpusError(DbgMsg("VASI", "Bad output specification for "+anName+" analysis."))
[docs]
def an_op():
"""
Generates the VACASK simulator command that invokes the operating
point analysis.
Equivalent of VACASK ``analysis name op`` simulator command.
Analysis generators return a tuple (sweeps, analysis, depth). *sweeps*
is a list of sweep statements, outermost first. *analysis* is the
analysis type followed by analysis parameters. *depth* is the number of
outer sweeps whose sweep points are split into separate results. Sweeps
that form the scale of the analysis (e.g. the sweep of a DC analysis)
are not counted in *depth*.
"""
return [], 'op', 0
[docs]
def an_dc(start, stop, sweep, points, name, parameter, index=None):
"""
Generates the VACASK simulator command that invokes the operating point
sweep (DC) analysis. *start* and *stop* give the initial and the final value
of the swept parameter.
*sweep* can be one of
* ``'lin'`` - linear sweep with the number of points given by *points*
* ``'dec'`` - logarithmic sweep with points per decade
(scale range of 1..10) given by *points*
* ``'oct'`` - logarithmic sweep with points per octave
(scale range of 1..2) given by *points*
*name* gives the name of the instance whose *parameter* is swept. If
*name* is ``None`` and *parameter* is ``'temperature'`` the circuit
temperature is swept. VACASK does not support vector parameters so
*index* must not be given.
VACASK cannot sweep an instance parameter that is bound to an
expression. The swept parameter must be given a literal value in the
netlist (e.g. ``dc=0``).
The swept values are stored in vector ``dcsweep``.
Equivalent of VACASK
``sweep dcsweep instance="name" parameter="param" from=start to=stop mode="sweep" points=points``
followed by ``analysis name op`` simulator command.
"""
if index is not None:
raise PyOpusError(DbgMsg("VASI", "Vector parameters are not supported."))
if name is None:
if parameter=='temperature':
devStr='option="temp"'
else:
raise PyOpusError(DbgMsg("VASI", "Bad sweep parameter."))
else:
devStr='instance='+_valueStr(str(name))+' parameter='+_valueStr(str(parameter))
return [ 'sweep dcsweep '+devStr+' '+_sweepSpec(start, stop, sweep, points) ], 'op', 0
[docs]
def an_tf(src, outp=None, outn=None, outcur=None):
"""
Generates the VACASK simulator command that invokes the small signal
(TF) analysis.
*src* is the name of the independent voltage/current source that
generates the input signal. VACASK computes the transfer functions from
all independent sources so *src* is used only for retrieving the results.
*outp* and *outn* give the voltage that is used as the output voltage. If
only *outp* is given the output voltage is the voltage at node *outp*. If
*outn* is also given, the output voltage is the voltage between nodes
*outp* and *outn*. If *outcur* is given the current flowing through the
instance with that name (``outcur:flow(br)``) is considered to be the
output.
The transfer functions are small-signal DC transfer functions
evaluated at the operating point which VACASK computes before the
analysis.
The results are stored in vectors ``tf(src)``, ``zin(src)``, and
``yin(src)``.
Equivalent of VACASK ``analysis name dcxf out=...`` simulator command.
"""
return [], 'dcxf out='+_outSpec(outp, outn, outcur, 'TF'), 0
[docs]
def an_ac(start, stop, sweep, points):
"""
Generates the VACASK simulator command that invokes the small signal
(AC) analysis. The range of the frequency sweep is given by *start* and
*stop*. *sweep* is one of
* ``'lin'`` - linear sweep with the number of points given by *points*
* ``'dec'`` - logarithmic sweep with points per decade
(scale range of 1..10) given by *points*
* ``'oct'`` - logarithmic sweep with points per octave
(scale range of 1..2) given by *points*
Equivalent of VACASK
``analysis name ac from=start to=stop mode="sweep" points=points``
simulator command.
"""
return [], 'ac '+_sweepSpec(start, stop, sweep, points), 0
[docs]
def an_tran(step, stop, start=0.0, maxStep=None, uic=False):
"""
Generates the VACASK simulator command that invokes the transient
analysis. The range of the time sweep is given by *start* and *stop*.
*step* is the intiial time step. The upper limit on the time step is given
by *maxStep*. If the *uic* flag is set to ``True`` the initial conditions
are used as the first point of the transient analysis instead of the
operating point analysis results.
If *uic* is ``True`` and *maxStep* is not given, the default value
*maxStep* is *step*.
Equivalent of VACASK
``analysis name tran step=step stop=stop start=start maxstep=maxStep [icmode="uic"]``
simulator command.
"""
if uic:
if maxStep is None:
maxStep=step
return [], 'tran step='+str(step)+' stop='+str(stop)+' start='+str(start)+' maxstep='+str(maxStep)+' icmode="uic"', 0
else:
if maxStep is None:
return [], 'tran step='+str(step)+' stop='+str(stop)+' start='+str(start), 0
else:
return [], 'tran step='+str(step)+' stop='+str(stop)+' start='+str(start)+' maxstep='+str(maxStep), 0
[docs]
def an_noise(start, stop, sweep, points, input, outp=None, outn=None, outcur=None, ptsSum=1):
"""
Generates the VACASK simulator command that invokes the small signal
noise analysis. The range of the frequency sweep is given by *start* and
*stop*. *sweep* is one of
* ``'lin'`` - linear sweep with the number of points given by *points*
* ``'dec'`` - logarithmic sweep with points per decade
(scale range of 1..10) given by *points*
* ``'oct'`` - logarithmic sweep with points per octave
(scale range of 1..2) given by *points*
*input* is the name of the independent voltage/current source that is
used for calculating the input referred noise. *outp* and *outn* give the
voltage that is used as the output voltage. If only *outp* is given the
output voltage is the voltage at node *outp*. If *outn* is also given,
the output voltage is the voltage between nodes *outp* and *outn*.
If *outcur* is given the current flowing through the instance with that
name (``outcur:flow(br)``) is considered to be the output.
*ptsSum* is ignored.
VACASK computes only output referred noise spectra: the total
(vector ``onoise``) and the partial spectra of instances
(``n(inst)``) and their contributions (``n(inst,contrib)``). The
power gain from *input* to the output is stored in vector ``gain``.
Input referred spectra (total and partial) are obtained by dividing
the output referred spectra by ``gain`` (see
:meth:`VacaskSimulationResults.ns`).
Equivalent of VACASK
``analysis name noise out=... in="input" from=start to=stop mode="sweep" points=points``
simulator command.
"""
return [], 'noise out='+_outSpec(outp, outn, outcur, 'NOISE')+' in='+_valueStr(str(input))+' '+_sweepSpec(start, stop, sweep, points), 0
[docs]
def an_sweep(name, args={}):
"""
Constructs a VACASK sweep named *name* with arguments given by *args*.
Keys of *args* are sweep parameter names. Values are converted to
VACASK values (strings are quoted, lists and arrays become vectors,
tuples become lists).
VACASK cannot sweep an instance parameter that is bound to an
expression. A parameter swept with ``instance=...`` and
``parameter=...`` must be given a literal value in the netlist.
Equivalent of VACASK ``sweep name arg1=value1 arg2=value2 ...``
statement. The result can be passed as a member of the *sweeps* list
in :func:`an_general`.
"""
return 'sweep '+_quoteName(str(name))+''.join(' '+str(k)+'='+_valueStr(v) for k, v in args.items())
[docs]
def an_general(anType, args={}, sweeps=[], sweepDepth=None):
"""
Constructs an arbitrary VACASK analysis of type *anType* with arguments
given by *args* dictionary and optional sweeps given by *sweeps* list.
Keys of *args* are analysis parameter names. Values are converted to
VACASK values (strings are quoted, lists and arrays become vectors,
tuples become lists).
*sweeps* is a list of complete VACASK sweep statements
(``sweep name ...``), outermost sweep first.
*sweepDepth* is the number of outermost sweeps whose sweep points
are split into separate results (see
:meth:`VacaskSimulationResults.sweepPoint`). The remaining (innermost)
sweeps are treated as part of the analysis, i.e. the first of them
becomes the default scale. If *sweepDepth* is not given all sweeps
are split (*sweepDepth* equals the length of *sweeps*).
Equivalent of VACASK sweep statements given by *sweeps* followed by
``analysis name anType arg1=value1 arg2=value2 ...`` simulator command.
"""
if sweepDepth is None:
sweepDepth=len(sweeps)
elif sweepDepth<0 or sweepDepth>len(sweeps):
raise PyOpusError(DbgMsg("VASI", "Sweep depth must be between 0 and the number of sweeps."))
return (
[ str(s) for s in sweeps ],
str(anType)+''.join(' '+str(k)+'='+_valueStr(v) for k, v in args.items()),
sweepDepth
)
[docs]
class Vacask(Simulator):
"""
A class for interfacing with the VACASK simulator in batch mode.
*binary* is the path to the VACASK simulator binary. If it is not given
the ``VACASKHOME`` environmental variable is used as the path to the
VACASK installation. The simulator is assumed to be in ``VACASKHOME/bin``.
If ``VACASKHOME`` is not defined the system path is searched. If the
binary is not found there it is assumed to be in the current working
directory.
*args* specifies a list of additional arguments passed to the simulator
binary at startup.
If *debug* is greater than 0 debug messages are printed at the standard
output. If it is above 1 a part of the simulator output is also printed.
If *debug* is above 2 full simulator output is printed.
*timeout* is the maximal time in seconds a simulator run (one job group)
may take. If it is exceeded the simulator is killed and the run is
reported as failed. ``None`` (default) means no limit.
The save directives from the simulator job description are evaluated in an
environment where the following objects are available:
* ``all`` - a reference to the :func:`save_all` function
* ``v`` - a reference to the :func:`save_voltage` function
* ``i`` - a reference to the :func:`save_current` function
* ``dv`` - a reference to the :func:`save_dvoltage` function
* ``di`` - a reference to the :func:`save_dcurrent` function
* ``p`` - a reference to the :func:`save_property` function
* ``ipath`` - a reference to the :func:`ipath` function
Similarly the environment for evaluating the analysis command given in the
job description consists of the following objects:
* ``op`` - a reference to the :func:`an_op` function
* ``dc`` - a reference to the :func:`an_dc` function
* ``tf`` - a reference to the :func:`an_tf` function
* ``ac`` - a reference to the :func:`an_ac` function
* ``tran`` - a reference to the :func:`an_tran` function
* ``noise`` - a reference to the :func:`an_noise` function
* ``an`` - a reference to the :func:`an_general` function
* ``sweep`` - a reference to the :func:`an_sweep` function
* ``ipath`` - a reference to the :func:`ipath` function
* ``param`` - a dictionary containing the members of the ``params`` entry
in the simulator job description together with the parameters from the
dictionary passed at the last call to the :meth:`setInputParameters`
method. The parameters values given in the job description take
precedence over the values passed to the :meth:`setInputParameters`
method.
Values of simulator options (``options`` entry of the job
description) and parameters (``params`` entry and the values passed
to :meth:`setInputParameters`) are converted to VACASK syntax:
* ``bool`` becomes ``1`` or ``0``
* integers and reals are converted with :func:`str`
* strings are double quoted
* lists and NumPy arrays become vectors (``[...]``)
* tuples become lists (``{...}``)
The same rules apply to the values in the *args* dictionaries of
:func:`an_general` and :func:`an_sweep`.
For every job group one simulator input file is generated. It
includes the circuit definitions, followed by a control block with
one section per job. Every section clears the settings of the
previous job, sets the simulator options, circuit variables, and save
directives, and runs the job's analysis. See :meth:`writeFile` for
details.
"""
def __init__(self, binary=None, args=[], debug=0, timeout=None):
Simulator.__init__(self, binary, args, debug)
self.timeout = timeout
self.sweepDepth={}
self._compile()
[docs]
@classmethod
def findSimulator(cls):
"""
Finds the simulator. Location is defined by the VACASKHOME
environmental variable. If VACASKHOME is not set the system path
is used.
"""
if 'VACASKHOME' in environ:
vacaskpath=os.path.join(environ['VACASKHOME'], 'bin')
if platform.system()=='Windows':
vacaskbinary=os.path.join(vacaskpath, 'vacask.exe')
else:
vacaskbinary=os.path.join(vacaskpath, 'vacask')
else:
if platform.system()=='Windows':
vacaskbinary=shutil.which("vacask.exe")
else:
vacaskbinary=shutil.which("vacask")
if vacaskbinary is None:
return None
elif os.path.isfile(vacaskbinary):
return vacaskbinary
else:
return None
def _compile(self):
"""
Prepares internal structures.
* dictionaries of functions for evaluating save directives and analysis
commands
* constructs the binary name for invoking the simulator
"""
self.saveLocals={
'all': save_all,
'v': save_voltage,
'i': save_current,
'dv': save_dvoltage,
'di': save_dcurrent,
'p': save_property,
'ipath': ipath,
}
self.analysisLocals={
'op': an_op,
'dc': an_dc,
'tf': an_tf,
'ac': an_ac,
'tran': an_tran,
'noise': an_noise,
'an': an_general,
'sweep': an_sweep,
'ipath': ipath,
'param': {},
}
if self.binary is None:
self.binary=Vacask.findSimulator()
if self.binary is None:
if platform.system()=='Windows':
self.binary=os.path.join(".", 'vacask.exe')
else:
self.binary=os.path.join(".", 'vacask')
def __getstate__(self):
state=self.__dict__.copy()
del state['saveLocals']
del state['analysisLocals']
state['simulatorID']=None
return state
def __setstate__(self, state):
self.__dict__.update(state)
if self.simulatorID is None:
self.generateSimulatorID()
self._compile()
def _createSaves(self, saveDirectives, variables):
"""
Creates a list of save directives by evaluating the members of the
*saveDirectives* list. *variables* is a dictionary of extra
variables that are available during directive evaluation. In case of
a name conflict the variables from *saveDirectives* take precedence.
"""
evalEnv={}
evalEnv.update(variables)
evalEnv.update(self.saveLocals)
compiledList=[]
for saveDirective in saveDirectives:
saveList=eval(saveDirective, globals(), evalEnv)
if type(saveList) is not list:
raise PyOpusError(DbgMsg("VASI", "Save directives must evaluate to a list of strings."))
for save in saveList:
if type(save) is not str:
raise PyOpusError(DbgMsg("VASI", "Save directives must evaluate to a list of strings."))
compiledList+=saveList
return list(set(compiledList))
def _analysisName(self, j):
"""
Returns the VACASK analysis name for the *j*-th job.
The name is ``simulatorID.jobj.jobName``.
"""
return self.simulatorID+".job"+str(j)+"."+self.jobList[j]['name']
def _rawFileName(self, j):
"""
Returns the name of the raw file produced by the *j*-th job.
"""
return self._analysisName(j)+'.raw'
[docs]
def writeFile(self, i):
"""
Prepares the simulator input file for running the *i*-th job group.
The file is named ``simulatorID.groupi.sim`` where *i* is the index
of the job group.
System description modules are converted to ``include`` directives.
They are followed by a ``control`` block holding the commands for
all jobs in the job group.
Every job starts with a ``clear`` command that clears save
directives, circuit variables, and simulator options set by the
previous job. Next the ``rawfile="binary"`` and ``strictoutput=2``
simulator options are set. Consequently all output files with
simulation results are .raw files in binary format.
Simulator options are set with the ``options`` simulator command.
Values are converted to VACASK syntax (booleans to 0/1, strings are
quoted, lists and arrays become vectors, tuples become lists).
The parameters set with the last call to :meth:`setInputParameters`
method are joined with the parameters in the job description. The
values from the job description take precedence over the values
specified with the :meth:`setInputParameters` method. All parameters
are written to the input file in form of ``var`` simulator commands.
The ``temperature`` parameter is written as the ``temp`` simulator
option.
Save directives are written as a series of ``save`` simulator commands.
Every analysis command is evaluated in its corresponding environment
taking into account the parameter values passed to the
:meth:`setInputParameters` method. The resulting sweep statements
are written in front of the ``analysis`` command. The sweep depth
is stored for :meth:`readResults`.
The analysis is named by :meth:`_analysisName`. The name is quoted
if it is not a valid VACASK identifier. The analysis results are
stored in a file named after the analysis with the ``.raw``
extension.
The function returns the name of the simulator input file it generated.
"""
fileName=self.simulatorID+".group"+str(i)+'.sim'
if self.debug>0:
DbgMsgOut("VASI", "Writing job group '"+str(i)+"' to file '"+fileName+"'")
with open(fileName, 'w') as f:
f.write('Simulator input file for job group '+str(i)+'\n\n')
jobGroup=self.jobGroup(i)
repJob=self.jobList[jobGroup[0]]
for definition in repJob['definitions']:
if 'section' in definition:
f.write('include '+_valueStr(definition['file'])+' section='+definition['section']+'\n')
else:
f.write('include '+_valueStr(definition['file'])+'\n')
f.write('\n')
f.write('control\n')
for j in jobGroup:
job=self.jobList[j]
if self.debug>0:
DbgMsgOut("VASI", " job '"+job['name']+"'")
evalEnv={}
evalEnv.update(job['variables'])
evalEnv.update(self.analysisLocals)
analysisParams={}
analysisParams.update(self.inputParameters)
if 'params' in job:
analysisParams.update(job['params'])
f.write('// '+job['name']+'\n')
f.write('clear\n')
f.write('options rawfile="binary" strictoutput=2\n')
if 'options' in job:
for (option, value) in job['options'].items():
f.write('options '+option+'='+_valueStr(value)+'\n')
for (param, value) in analysisParams.items():
if param!="temperature":
f.write('var '+param+'='+_valueStr(value)+'\n')
else:
f.write('options temp='+_valueStr(value)+'\n')
if 'saves' in job:
saves=self._createSaves(job['saves'], job['variables'])
count=0
for save in saves:
if count == 0:
f.write('save ')
f.write(save+' ')
count+=1
if count == 10:
count=0
f.write('\n')
f.write('\n')
self.analysisLocals['param'].clear()
self.analysisLocals['param'].update(analysisParams)
anSweeps, anSpec, anDepth=eval(job['command'], globals(), evalEnv)
self.sweepDepth[j]=anDepth
for line in anSweeps:
f.write(line+'\n')
f.write('analysis '+_quoteName(self._analysisName(j))+' '+anSpec+'\n\n')
f.write('endc\n')
return fileName
[docs]
def cleanupResults(self, i):
"""
Removes all result files that were produced during the simulation of
the *i*-th job group. Simulator input files are left untouched.
"""
if self.debug>0:
DbgMsgOut("VASI", "Cleaning up result for job group "+str(i))
jobGroup=self.jobGroup(i)
for j in jobGroup:
try:
os.remove(self._rawFileName(j))
except KeyboardInterrupt:
DbgMsgOut("VASI", "Keyboard interrupt")
raise
except:
None
[docs]
def runFile(self, fileName):
"""
Runs the simulator on the input file given by *fileName*.
Returns ``True`` if the simulation finished successfully.
This does not mean that any results were produced.
It only means that the return code from the simuator was 0 (OK).
"""
if self.debug>0:
DbgMsgOut("VASI", "Running file '"+fileName+"'")
cmdLineList=[self.binary, '-sp', '-qp']+self.cmdline+[fileName]
if self.debug>3:
with open(fileName) as dbgf:
DbgMsgOut("VASI", dbgf.read())
DbgMsgOut("VASI", "Starting simulator: "+str(cmdLineList))
spawnOK=True
p=None
try:
p=subprocess.Popen(
cmdLineList,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL
)
try:
msgs, _ = p.communicate(timeout=self.timeout)
self.messages=msgs.decode("utf-8")
except subprocess.TimeoutExpired:
if self.debug>1:
DbgMsgOut("VASI", "Simulation timeout")
p.kill()
msgs, _ = p.communicate()
self.messages=msgs.decode("utf-8")
spawnOK = False
if self.debug>2:
DbgMsgOut("VASI", self.messages)
elif self.debug>1:
DbgMsgOut("VASI", self.messages[-400:])
retcode=p.wait()
if retcode!=0:
spawnOK=False
except KeyboardInterrupt:
DbgMsgOut("VASI", "Keyboard interrupt")
try:
p.kill()
except:
pass
raise KeyboardInterrupt
except:
spawnOK=False
if not spawnOK and self.debug>0:
DbgMsgOut("VASI", " run FAILED")
return spawnOK
[docs]
def runJobGroup(self, i):
"""
Runs the *i*-th job group.
First calls the :meth:`writeFile` method followed by the
:meth:`cleanupResults` method that removes any old results produced by
previous runs of the jobs in *i*-th job group. Finally the
:meth:`runFile` method is invoked. Its return value is stored in the
:attr:`lastRunStatus` member.
The function returns a tuple (*jobIndices*, *status*) where
*jobIndices* is a list of job indices corresponding to the *i*-th job
group. *status* is the status returned by the :meth:`runFile` method.
"""
filename=self.writeFile(i)
self.cleanupResults(i)
self.lastRunStatus=self.runFile(filename)
jobIndices=self.jobGroup(i)
return (jobIndices, self.lastRunStatus)
[docs]
def readResults(self, jobIndex, runOK=None):
"""
Read results of a job with given *jobIndex*.
*runOK* specifies the status returned by the :meth:`runJobGroup`
method which produced the results. If not specified the run status
stored by the simulator is used.
Returns an object of the class :class:`VacaskSimulationResults`.
If the run failed or the results file cannot be read the ``None``
is returned.
The sweep depth of the job (the third member of the tuple returned
by the analysis generator, recorded by :meth:`writeFile`) is passed
to the :class:`VacaskSimulationResults` constructor. It determines
how the results are split into sweep points. If :meth:`writeFile`
was not yet called for the job group containing the job (e.g.
results of an earlier run are read with a new simulator object)
the sweep depth is unknown and 0 is used, i.e. the whole result
is treated as a single sweep point.
"""
if runOK is None:
runOK=self.lastRunStatus
job=self.jobList[jobIndex]
if runOK:
fileName=self._rawFileName(jobIndex)
if self.debug>1:
DbgMsgOut("VASI", "Reading results from '"+fileName+"'.")
try:
rawData=raw_read(
fileName
)
except:
rawData=None
else:
rawData=None
if self.debug>0:
if rawData is not None:
DbgMsgOut("VASI", "Job '"+str(job['name'])+"' OK")
else:
DbgMsgOut("VASI", "Job '"+str(job['name'])+"' FAILED")
if rawData is None:
return None
else:
params={}
params.update(self.inputParameters)
params.update(job['params'])
return VacaskSimulationResults(
rawData, params=params, variables=job['variables'],
sweepDepth=self.sweepDepth.get(jobIndex, 0)
)
[docs]
def jobGroupCount(self):
"""
Returns the number of job groups.
"""
return len(self.jobSequence)
[docs]
def jobGroup(self, i):
"""
Returns a list of job indices corresponding to the jobs in *i*-th job
group.
"""
return self.jobSequence[i]
[docs]
def unoptimizedJobSequence(self):
"""
Returns the unoptimized job sequence. If there are n jobs the job list
the following list of lists is returned: ``[[0], [1], ..., [n-1]]``.
This means we have n job groups with one job per job group.
"""
seq=[[0]]*len(self.jobList)
for i in range(len(self.jobList)):
seq[i]=[i];
return seq
[docs]
def optimizedJobSequence(self):
"""
Returns the optimized job sequence.
Jobs in a job group have identical circuit definitions. Simulator
options, parameters, and save directives are set for every job
separately.
"""
for job in self.jobList:
for option in job['options'].keys():
if option.lower()=='temp':
raise PyOpusError(DbgMsg("VASI", "TEMP option is not allowed. Use temperature parameter."))
jobCount=len(self.jobList)
candidates=set(range(jobCount))
seq=[]
while len(candidates)>0:
i1=candidates.pop()
jobGroup=[i1]
peerCandidates=list(candidates)
for i2 in peerCandidates:
if self.jobList[i1]['definitions']==self.jobList[i2]['definitions']:
jobGroup.append(i2)
candidates.remove(i2)
jobGroup.sort()
seq.append(jobGroup)
return seq
[docs]
class VacaskSimulationResults(SimulationResults):
"""
Objects of this class hold VACASK simulation results.
*rawData* is the list of plots returned by
:func:`~pyopus.simulator.rawfile.raw_read`. VACASK raw files hold
only one result (one plot) so only the first plot is used.
*params* and *variables* are the parameters and Python variables of
the job that produced the results. *results* is passed to the
:class:`~pyopus.simulator.base.SimulationResults` constructor.
*sweepDepth* is the number of outer sweeps whose sweep points are
split into separate results. The first *sweepDepth* vectors in the
raw file are the sweep variables (outermost first). A new sweep point
starts wherever the value of any of these vectors changes. The default
scale is the vector that follows the sweep variables. If *sweepDepth*
is 0 the whole result is one sweep point and the default scale is the
first vector in the raw file.
By default all accessor methods return the data of all sweep points.
:meth:`sweepPoint` returns a shallow copy of the results object
restricted to a single sweep point. The copy shares the raw data with
the original object. Calling :meth:`sweepPoint` on such a copy raises
an error.
The values of the sweep variables are returned by :meth:`sweepVars`.
For results of small-signal analyses (e.g. AC, noise) these values are
complex because all vectors in the raw file are complex.
"""
def __init__(self, rawData, params={}, variables={}, results={}, sweepDepth=0):
SimulationResults.__init__(self, params, variables, results)
self.rawData=rawData
# Store sweep depth
self.sweepDepth=sweepDepth
# Sweep point boundaries
self.i1=None
self.i2=None
# Active range
self.range1 = None
self.range2 = None
# Sweep variable values per sweep points (dictionary of vectors)
self.sweepVars_={}
# Default scale name
self.dflScaleName=None
# Assume there is only a single plot in a raw file.
# Vectors are in a dictionary.
# Dictionary preserves the order in which entries were added.
# First sweepDepth vectors are sweep scales.
# Find sweep point boundaries (i1, i2)
if rawData is not None:
vecs=rawData[0][0]
names=list(vecs.keys())
if sweepDepth>=len(names):
raise PyOpusError("Sweep depth exceeds the number of vectors.")
# Default scale is the first vector after sweep scales
if sweepDepth>0:
self.dflScaleName=names[sweepDepth]
else:
self.dflScaleName=rawData[0][1]
n=len(vecs[rawData[0][1]])
ends=[np.array([n], dtype=np.int64)]
for ii in range(sweepDepth):
var=vecs[names[ii]]
ends.append(np.where(var[1:]!=var[:-1])[0]+1)
# unique() sorts the unique values.
self.i2=np.unique(np.concatenate(ends))
self.i1=np.hstack([0, self.i2[:-1]]).astype(np.int64)
# Default active range is full range
self.range1=0
self.range2=len(vecs[names[0]])
# Collect sweep variable values, keep sweep ordering
for ii in range(sweepDepth):
name=names[ii]
self.sweepVars_[name]=vecs[name][self.i1]
[docs]
def sweepPointCount(self):
"""
Return the number of sweep points.
Returns 0 if there are no results or if the object was obtained
with :meth:`sweepPoint` (i.e. it already holds a single sweep
point).
"""
return len(self.i1) if self.i1 is not None else 0
[docs]
def sweepVars(self):
"""
Return the values of sweep variables in a dictionary. Keys are
sweep names, ordered from the outermost to the innermost sweep.
For the full results object the values are arrays with one entry
per sweep point. For an object obtained with :meth:`sweepPoint`
the values are scalars belonging to that sweep point.
For results of small-signal analyses (e.g. AC, noise) the values
are complex. If *sweepDepth* is 0 the dictionary is empty.
"""
return self.sweepVars_
[docs]
def sweepPoint(self, index=0):
"""
Return simulation results for the sweep point with given *index*
(0 to :meth:`sweepPointCount`-1).
The returned object is a shallow copy of this object. It shares
the raw data with this object, but all its accessor methods
return only the part of the vectors that belongs to the selected
sweep point. Its :meth:`sweepVars` method returns the values of
the sweep variables for that sweep point.
If *sweepDepth* is 0 there is one sweep point holding the whole
result.
Raises an error if there are no results or if this object was
itself obtained with :meth:`sweepPoint`.
"""
if self.i1 is None:
raise PyOpusError("No sweep points found.")
# Shallow copy
obj=copy.copy(self)
# Set range
obj.range1=self.i1[index]
obj.range2=self.i2[index]
# Remove sweep boundaries
obj.i1=None
obj.i2=None
# Sweep variables dictionary
# (create new one to keep the original intact)
newDict = { k: v[index] for k, v in self.sweepVars_.items() }
obj.sweepVars_ = newDict
return obj
[docs]
def title(self):
"""
Return the title of the plot.
"""
if self.rawData is None:
raise PyOpusError("No results.")
return self.rawData[0][3]
[docs]
def date(self):
"""
Return the date of the plot.
"""
if self.rawData is None:
raise PyOpusError("No results.")
return self.rawData[0][4]
[docs]
def name(self):
"""
Return the name of the plot.
"""
if self.rawData is None:
raise PyOpusError("No results.")
return self.rawData[0][5]
[docs]
def vectorNames(self):
"""
Returns the names of available vectors.
"""
if self.rawData is None:
raise PyOpusError("No results.")
return list(self.rawData[0][0].keys())
[docs]
def vector(self, name):
"""
Returns vector named *name*.
"""
if self.rawData is None:
raise PyOpusError("No results.")
resGrp=self.rawData[0]
if name in resGrp[0]:
return resGrp[0][name][self.range1:self.range2]
else:
raise PyOpusError(f"Vector '{name}' not found.")
[docs]
def scaleName(self, vecName=None):
"""
If *vecName* is specified returns the name of the scale vector
corresponding to the specified vector. Usually this is the
default scale.
If *vecName* is not specified returns the name of the vector
holding the default scale.
"""
if self.rawData is None:
raise PyOpusError("No results.")
resGrp=self.rawData[0]
if vecName not in resGrp[2]:
return self.dflScaleName
else:
return resGrp[2][vecName]
[docs]
def scale(self, vecName=None):
"""
If *vecName* is specified returns the scale corresponding to
the specified vector. Usually this is the default scale.
If *vecName* is not specified returns the default scale.
"""
name=self.scaleName(vecName)
return self.vector(name)
[docs]
def v(self, node1, node2=None):
"""
Retrieves the voltage corresponding to *node1* (voltage between nodes
*node1* and *node2* if *node2* is also given).
Also used for retrieving results of tf analysis. Set *node1* to
``tf(src)``, ``zin(src)``, or ``yin(src)``.
"""
if node2 is None:
return self.vector(node1)
else:
return self.vector(node1)-self.vector(node2)
[docs]
def i(self, name):
"""
Retrieves the current flowing through instance *name*.
Equivalent to VACASK vector ``name:flow(br)``.
"""
return self.vector(name+":flow(br)")
[docs]
def p(self, name, parameter, index=None):
"""
Retrieves the property named *parameter* belonging to instance named
*name*. VACASK does not support vector properties so *index* must
not be given.
Note that this works only of the property was saved with a
corresponding save directive.
Equivalent to VACASK vector ``name.parameter``.
"""
if index is not None:
raise PyOpusError("Vector properties are not supported.")
return self.vector(name+'.'+parameter)
[docs]
def ns(self, reference, name=None, contrib=None):
"""
Retrieves the noise spectrum density of contribution *contrib* of
instance *name* to the output noise spectrum density. *reference*
can be ``'input'`` or ``'output'``.
If *name* and *contrib* are not given the total output or the
equivalent total input noise spectrum density is returned (depending
on the value of *reference*).
Partial and total noise spectra are returned as squared noise
(in V^2/Hz or A^2/Hz). VACASK computes only output referred spectra.
Input referred spectra (total and partial) are obtained by dividing
the output referred spectra by the power gain from the input source
to the output (vector ``gain``).
"""
if reference not in ('input', 'output'):
raise PyOpusError("Bad noise reference.")
if name is None:
spec=self.vector('onoise')
elif contrib is None:
spec=self.vector("n("+str(name)+")")
else:
spec=self.vector("n("+str(name)+","+str(contrib)+")")
if reference=='input':
spec=spec/self.vector('gain')
return spec
[docs]
def driverTable(self):
"""
Returns a dictionary of available driver functions for
accessing simulation results.
They are used for measurement evaluation in
:class:`~pyopus.evaluator.performance.PerformanceEvaluator` objects
where they appear as a part of the environment for evaluating the
measures. The following functions (dictionary key names) are
available:
* ``ipath`` - a reference to the :func:`ipath` function for
constructing object paths in hierarchical designs
* ``scaleName`` - the :meth:`scaleName` method
* ``scale`` - the :meth:`scale` method
* ``vectorNames`` - the :meth:`vectorNames` method
* ``vector`` - the :meth:`vector` method
* ``v`` - the :meth:`v` method
* ``i`` - the :meth:`i` method
* ``p`` - the :meth:`p` method
* ``ns`` - the :meth:`ns` method
* ``sweepPointCount`` - the :meth:`sweepPointCount` method
* ``sweepPoint`` - the :meth:`sweepPoint` method. The returned
object provides the same methods (e.g. ``sweepPoint(k).v('out')``)
restricted to the *k*-th sweep point.
* ``sweepVars`` - the :meth:`sweepVars` method
The functions apply to the whole result (all sweep points) if this
object was not obtained with :meth:`sweepPoint`. Otherwise they apply
to the sweep point held by this object.
"""
return {
'ipath': ipath,
'scaleName': self.scaleName,
'scale': self.scale,
'vectorNames': self.vectorNames,
'vector': self.vector,
'v': self.v,
'i': self.i,
'p': self.p,
'ns': self.ns,
'sweepPointCount': self.sweepPointCount,
'sweepPoint': self.sweepPoint,
'sweepVars': self.sweepVars,
}