neuromancer.psl package

Submodules

neuromancer.psl.autonomous module

Nonlinear ODEs. Wrapper for emulator dynamical models

  • Internal Emulators - in house ground truth equations

  • External Emulators - third party models

References

class neuromancer.psl.autonomous.Autoignition(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_Autonomous

ODE describing pulsating instability in open-ended combustor.

  • Koch, J., Kurosaka, M., Knowlen, C., Kutz, J.N., “Multiscale physics of rotating detonation waves: Autosolitons and modulational instabilities,” Physical Review E, 2021

equations(t, x)[source]
property params
class neuromancer.psl.autonomous.Brusselator1D(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_Autonomous

Brusselator

equations(t, x)[source]
property params
class neuromancer.psl.autonomous.ChuaCircuit(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_Autonomous

Chua’s circuit

equations(t, x)[source]
property params
class neuromancer.psl.autonomous.DoublePendulum(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_Autonomous

Double Pendulum

equations(t, x)[source]
property params
class neuromancer.psl.autonomous.Duffing(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_Autonomous

Duffing equation

equations(t, x)[source]
property params
class neuromancer.psl.autonomous.LorenzSystem(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_Autonomous

Lorenz System

equations(t, x)[source]
property params
class neuromancer.psl.autonomous.LotkaVolterra(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_Autonomous

Lotka–Volterra equations Also known as the predator–prey equations

equations(t, x)[source]
property params
class neuromancer.psl.autonomous.Pendulum(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_Autonomous

Simple pendulum

equations(t, x)[source]
property params
class neuromancer.psl.autonomous.RosslerAttractor(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_Autonomous

Rössler attractor

equations(t, x)[source]
property params
class neuromancer.psl.autonomous.ThomasAttractor(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_Autonomous

Thomas’ cyclically symmetric attractor

equations(t, x)[source]
property params
class neuromancer.psl.autonomous.UniversalOscillator(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_Autonomous

Harmonic oscillator

equations(t, x)[source]
property params
class neuromancer.psl.autonomous.VanDerPol(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_Autonomous

Van der Pol oscillator

equations(t, x)[source]
property params

neuromancer.psl.base module

Base classes for dynamic systems.

class neuromancer.psl.base.Backend(backend)[source]

Bases: object

backends = {'numpy': {'cast': <built-in function array>, 'cat': <function concatenate>, 'core': <module 'numpy' from '/Users/birm560/opt/anaconda3/envs/neuromancer/lib/python3.10/site-packages/numpy/__init__.py'>, 'grad': <function Backend.<lambda>>, 'odeint': functools.partial(<function odeint>, tfirst=True)}, 'torch': {'cast': <built-in method tensor of type object>, 'cat': <built-in method cat of type object>, 'core': <module 'torch' from '/Users/birm560/opt/anaconda3/envs/neuromancer/lib/python3.10/site-packages/torch/__init__.py'>, 'grad': <function grad>, 'odeint': <function odeint>}}
numpy_backend = {'cast': <built-in function array>, 'cat': <function concatenate>, 'core': <module 'numpy' from '/Users/birm560/opt/anaconda3/envs/neuromancer/lib/python3.10/site-packages/numpy/__init__.py'>, 'grad': <function Backend.<lambda>>, 'odeint': functools.partial(<function odeint>, tfirst=True)}
torch_backend = {'cast': <built-in method tensor of type object>, 'cat': <built-in method cat of type object>, 'core': <module 'torch' from '/Users/birm560/opt/anaconda3/envs/neuromancer/lib/python3.10/site-packages/torch/__init__.py'>, 'grad': <function grad>, 'odeint': <function odeint>}
class neuromancer.psl.base.EmulatorBase(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ABC, Module

add_missing_parameters()[source]
change_backend(backend=<module 'torch' from '/Users/birm560/opt/anaconda3/envs/neuromancer/lib/python3.10/site-packages/torch/__init__.py'>)[source]
denormalize(data, normalizer=None, key=None)[source]
Parameters:
  • data

  • normalizer

  • key

Returns:

get_x0()[source]

Randomly sample an initial condition

Parameters:

box – Dictionary with keys ‘min’ and ‘max’ and values np.arrays with shape=(nx,)

normalize(data, normalizer=None, key=None)[source]
Parameters:
  • data – (Tensor, ndarray, or dict of tensor or ndarray)

  • normalizer

  • key

Returns:

property params
restore_random_state(rng_state=None)[source]

Load random state

save_random_state()[source]

Save random state for later use

set_params(parameters, requires_grad=False, cast=True)[source]
set_stats(x0=None, U=None, D=None, nsim=None, sim=None)[source]

Get a hyperbox defined by min and max values on each of nx axes. Used to sample initial conditions for simulations. Box is generated by simulating system with step size ts for nsim steps and then taking the min and max along each axis

Parameters:
  • system – (psl.ODE_NonAutonomous)

  • ts – (float) Timestep interval size

  • nsim – (int) Number of simulation steps to use in defining box

show(data=None, figname=None)[source]

By default will plot the data used to generate initial system statistics from the canonical 1000 step simulation.

Parameters:
  • data – (dict {str: Tensor or ndarray}) Will plot data from any system simulation given via this argument

  • figname – (str) Optional name for figure. By default uses class name and saves figure as .png.

abstract simulate()[source]
class neuromancer.psl.base.EquationWrapper(Time, U, equations, backend)[source]

Bases: object

The interface for odeint methods in torch and scipy does not handle exogenous inputs. This wrapper allows us to index control inputs by time point.

class neuromancer.psl.base.ODE_Autonomous(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: EmulatorBase

base class autonomous ODE

abstract equations()[source]
forward(x, t)[source]

Defines the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

simulate(nsim=None, Time=None, ts=None, x0=None)[source]
Parameters:
  • nsim – (int) Number of steps for open loop response

  • ninit – (float) initial simulation time

  • ts – (float) step size, sampling time

  • Time – (Sequence of float) Optional timesteps to integrate over.

  • x0 – (float) state initial conditions

Returns:

The response matrices, i.e. X

class neuromancer.psl.base.ODE_NonAutonomous(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: EmulatorBase

base class non-autonomous ODE

add_missing_parameters()[source]
abstract equations()[source]
forward(x, u)[source]

For compatibility with the System class for open/closed loop simulations

Parameters:
  • x – 2d Matrix (1, nx) # for torch backend generalize to (batchsize, nx)

  • t – (1, 1)

  • u – (1, nu)

Returns:

x_next (1, nx)

get_R(nsim)[source]

For sampling a sequence of reference trajectories

Parameters:

nsim – (int) Length of sequence

Returns:

Matrix nsim X nx0

get_U(nsim, umin=None, umax=None, signal=None, **signal_kwargs)[source]

For sampling a sequence of control actions :param nsim: length of sequence :return: Matrix nsim X nU

get_simulation_args(nsim, Time, ts, x0, U)[source]
simulate(nsim=None, Time=None, ts=None, x0=None, U=None)[source]
Parameters:
  • nsim – (int) Number of steps for open loop response

  • Time – (Sequence of float) Optional timesteps to integrate over.

  • ts – (float) step size, sampling time

  • x0 – (float) state initial conditions

Returns:

Dictionary containing X, Y, U

neuromancer.psl.base.cast_backend(method)[source]

Decorator to cast numerics to appropriate backend.

Parameters:

method

Returns:

neuromancer.psl.base.download(url, dst)[source]

Function is used by FileEmulator and BuildingEnvelope classes to retrieve data we don’t want to host on github.

Parameters:
  • url – (str) Url to retrieve data from

  • dst – (str pathlike) Where to store the data on disk

neuromancer.psl.base.grad(tensor, requires_grad)[source]

Helper function to set gradient of tensors for pytorch backend :param tensor: :param requires_grad: :return:

neuromancer.psl.building_envelope module

class neuromancer.psl.building_envelope.BuildingEnvelope(seed=59, exclude_norms=['Time'], backend='numpy', requires_grad=False, system='Reno_full', set_stats=True, *args, **kwargs)[source]

Bases: ODE_NonAutonomous

building envelope heat transfer model linear building envelope dynamics and bilinear heat flow input dynamics for different building types are downloaded as needed and stored at buildings_parameters/*.mat Models obtained from: https://github.com/drgona/BeSim

T_dist_idx = {'HollandschHuys_ROM100': [221], 'HollandschHuys_full': [221], 'Old_ROM40': [40], 'Old_full': [40], 'RenoLight_ROM40': [40], 'RenoLight_full': [40], 'Reno_ROM40': [40], 'Reno_full': [40], 'SimpleSingleZone': [0]}
equations(x, u, d)[source]
forward(x, u, d)[source]

For compatibility with the System class for open/closed loop simulations

Parameters:
  • x – 2d Matrix (1, nx) # for torch backend generalize to (batchsize, nx)

  • u – (1, nu)

  • d – (1, nd)

Returns:

x_next (1, nx), y_next (1, ny)

get_D(nsim)[source]
get_D_obs(nsim)[source]
get_R(nsim)[source]

For sampling a sequence of reference trajectories

Parameters:

nsim – (int) Length of sequence

Returns:

Matrix nsim X nx0

get_U(nsim, signal=None, **signal_kwargs)[source]

For sampling a sequence of control actions :param nsim: length of sequence :return: Matrix nsim X nU

get_q(u)[source]
get_simulation_args(nsim, x0, U, D)[source]
get_xy()[source]
property params

Four dicts (str: numeric) parameters (could be optimized), variables (exogenous inputs), constants (don’t vary from system to system), Meta-data (physical units, system type, etc.)

Type:

return

property path

Path where model parameter file is stored

simulate(nsim=None, U=None, D=None, x0=None, *args, **kwargs)[source]

Simulate at a minimum needs the number of simulation steps. You can optionally supply U, D, and x0 with or without nsim. If supplying U and D need to supply an extra time step of data.

Parameters:
  • nsim – (int) Number of simulation steps

  • U – (2D array or tensor)

  • D

  • x0

Returns:

systems = ['SimpleSingleZone', 'Reno_full', 'Reno_ROM40', 'RenoLight_full', 'RenoLight_ROM40', 'Old_full', 'Old_ROM40', 'HollandschHuys_full', 'HollandschHuys_ROM100']
property umax

maximal nominal mass flow l/h, maximal temperature difference deg C

property umin

minimal nominal mass flow l/h, minimal temperature difference deg C

property url

Remote github location for model parameter data

class neuromancer.psl.building_envelope.LinearBuildingEnvelope(seed=59, exclude_norms=['Time'], backend='numpy', requires_grad=False, system='Reno_full', set_stats=True, *args, **kwargs)[source]

Bases: BuildingEnvelope

get_U(nsim, signal=None, **signal_kwargs)[source]

For sampling a sequence of control actions :param nsim: length of sequence :return: Matrix nsim X nU

get_q(u)[source]
property umax

maximal nominal mass flow l/h, maximal temperature difference deg C

property umin

minimal nominal mass flow l/h, minimal temperature difference deg C

neuromancer.psl.coupled_systems module

class neuromancer.psl.coupled_systems.Boids(backend='numpy', set_stats=False, coherence=0.05, separation=0.01, alignment=0.05, avoidance_range=0.2, visual_range=None, nx=50, x0=None, seed=59)[source]

Bases: Coupled_ODE

equations(t, x)[source]
get_x0(nx=None, rseed=None)[source]

Randomly sample an initial condition

Parameters:

box – Dictionary with keys ‘min’ and ‘max’ and values np.arrays with shape=(nx,)

message_passing(receivers, senders, t)[source]

Stub function for message passing operation Systems that inherit should compute interactions between corresponding rows of receivers and senders :return messages from senders to receivers np.array of shape(len(receivers), **)

Parameters:
  • receivers – _description_

  • senders – _description_

  • t – _description_

normalize_max(x, length)[source]
pos_idx = [0, 1]
simulate(nsim=None, Time=None, ts=None, x0=None)
Parameters:
  • nsim – (int) Number of steps for open loop response

  • ninit – (float) initial simulation time

  • ts – (float) step size, sampling time

  • Time – (Sequence of float) Optional timesteps to integrate over.

  • x0 – (float) state initial conditions

Returns:

The response matrices, i.e. X

vel_idx = [2, 3]
class neuromancer.psl.coupled_systems.Coupled_NonAutonomous(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed=59, set_stats=False, adj=None, nx=1)[source]

Bases: ODE_NonAutonomous

equations(t, x, u)[source]
message_passing(receivers, senders, t, u)[source]

Stub function for message passing operation Systems that inherit should compute interactions between corresponding rows of receivers and senders: (receivers[i], senders[i]) are coupled :return messages from senders to receivers np.array of shape(len(receivers), **)

Parameters:
  • receivers – Receiving agents

  • senders – Sending agents

  • t – time step

  • u – Control Variables

property params
class neuromancer.psl.coupled_systems.Coupled_ODE(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed=59, set_stats=True, adj=None, nx=1)[source]

Bases: ODE_Autonomous

equations(t, x)[source]
message_passing(receivers, senders, t)[source]

Stub function for message passing operation Systems that inherit should compute interactions between corresponding rows of receivers and senders :return messages from senders to receivers np.array of shape(len(receivers), **)

Parameters:
  • receivers – _description_

  • senders – _description_

  • t – _description_

property params
class neuromancer.psl.coupled_systems.Gravitational_System(backend='numpy', set_stats=False, G=6.67e-11, adj=None, nx=4, seed=59, x0=None)[source]

Bases: Coupled_ODE

equations(t, x)[source]
get_x0()[source]

Randomly sample an initial condition

Parameters:

box – Dictionary with keys ‘min’ and ‘max’ and values np.arrays with shape=(nx,)

static make_4_body(nsim=10000)[source]
Returns:

A system with 3 satelites orbiting one larger body

mass_idx = [0]
message_passing(receivers, senders, t)[source]

Stub function for message passing operation Systems that inherit should compute interactions between corresponding rows of receivers and senders :return messages from senders to receivers np.array of shape(len(receivers), **)

Parameters:
  • receivers – _description_

  • senders – _description_

  • t – _description_

pos_idx = [1, 2]
simulate(nsim=None, Time=None, ts=None, x0=None)
Parameters:
  • nsim – (int) Number of steps for open loop response

  • ninit – (float) initial simulation time

  • ts – (float) step size, sampling time

  • Time – (Sequence of float) Optional timesteps to integrate over.

  • x0 – (float) state initial conditions

Returns:

The response matrices, i.e. X

vel_idx = [3, 4]
class neuromancer.psl.coupled_systems.RC_Network(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed=59, set_stats=False, adj=None, nx=1, R=None, C=None, U=None)[source]

Bases: Coupled_NonAutonomous

equations(t, x, u)[source]
get_C(num=1)[source]
get_U(nsim, periods=None)[source]

For sampling a sequence of control actions :param nsim: length of sequence :return: Matrix nsim X nU

get_resistances(adj_list, Rval=3.5, amax=20, amin=0, symmetric=True)[source]
get_x0()[source]

Randomly sample an initial condition

Parameters:

box – Dictionary with keys ‘min’ and ‘max’ and values np.arrays with shape=(nx,)

static make_5_room(nsim=10000)[source]
message_passing(receivers, senders, t, u)[source]

Stub function for message passing operation Systems that inherit should compute interactions between corresponding rows of receivers and senders: (receivers[i], senders[i]) are coupled :return messages from senders to receivers np.array of shape(len(receivers), **)

Parameters:
  • receivers – Receiving agents

  • senders – Sending agents

  • t – time step

  • u – Control Variables

neuromancer.psl.coupled_systems.multidim(is_autonomous)[source]

neuromancer.psl.file_emulator module

This module implements an emulator interface for recorded datasets. The FileEmulator class facilitates sampling a wide range of initial conditions across the state space. Users can interact with a FileEmulator almost exactly how they interact with any other psl Emulator objects.

Data files are expected to be in .csv or .mat format with columns named by prefix indicating x) state, y) observation, u) system input, d) system disturbance.

See psl/psl/data for example files of recorded datasets.

class neuromancer.psl.file_emulator.FileEmulator(seed=59, path=None, system=None)[source]

Bases: EmulatorBase

An emulator interface for recorded datasets. The FileEmulator class facilitates sampling a wide range of initial conditions across the state space.

find_nearest(array, value)[source]
get_batch(nsim, startidx=0)[source]
property params
property path

Path where model parameter file is stored

retrieve_data()[source]
simulate(nsim=None, x0=None)[source]
Parameters:
  • nsim – (int) Number of steps for open loop response

  • ninit – (float) initial simulation time

  • x0 – (float) state initial conditions

Returns:

X, Y, U, D

property url

Remote github location for model parameter data

neuromancer.psl.file_emulator.read_file(file_or_dir)[source]

neuromancer.psl.gym module

neuromancer.psl.nonautonomous module

Non-autonomous dynamic systems. Reference for Chaotic nonlinear ODEs

class neuromancer.psl.nonautonomous.Actuator(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_NonAutonomous

These are the actuator dynamics from the IVER systems. Since the equations are linear they are a good sanity check for your modeling implementations.

equations(t, x, u)[source]
  • States (8): [delta_u, delta_q, delta_r]

  • Inputs (3): [delta_uc, delta_qc, delta_rc] (thrust speed/deflections, normalized)

get_U(nsim, signal=None, **signal_kwargs)[source]

For sampling a sequence of control actions :param nsim: length of sequence :return: Matrix nsim X nU

property params
class neuromancer.psl.nonautonomous.CSTR(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_NonAutonomous

Continuous Stirred Tank Reactor model Original code obtained from APMonitor

equations(t, x, u)[source]
Inputs (1):
  • Temperature of cooling jacket (K)

Disturbances (2):
  • Tf = Feed Temperature (K)

  • Caf = Feed Concentration (mol/m^3)

States (2):
  • Concentration of A in CSTR (mol/m^3)

  • Temperature in CSTR (K)

get_U(nsim, signal=None, **signal_kwargs)[source]

For sampling a sequence of control actions :param nsim: length of sequence :return: Matrix nsim X nU

get_x0(rand=False)[source]

Randomly sample an initial condition

Parameters:

box – Dictionary with keys ‘min’ and ‘max’ and values np.arrays with shape=(nx,)

property params
class neuromancer.psl.nonautonomous.DuffingControl(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_NonAutonomous

Duffing equation with driving force as a function of control inputs not time Source

equations(t, x, u)[source]
get_U(nsim, signal=None, **signal_kwargs)[source]

For sampling a sequence of control actions :param nsim: length of sequence :return: Matrix nsim X nU

property params
class neuromancer.psl.nonautonomous.HindmarshRose(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_NonAutonomous

Hindmarsh–Rose model of neuronal activity

equations(t, x, u)[source]
get_U(nsim, signal=None, **signal_kwargs)[source]

For sampling a sequence of control actions :param nsim: length of sequence :return: Matrix nsim X nU

property params
class neuromancer.psl.nonautonomous.InvPendulum(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_NonAutonomous

Inverted Pendulum dynamics * states: \(x = [ heta \dot{ heta}]\);

  • :math:` heta` is angle from upright equilibrium

  • input: u = input torque

equations(t, x, u)[source]
get_U(nsim, signal=None, **signal_kwargs)[source]

For sampling a sequence of control actions :param nsim: length of sequence :return: Matrix nsim X nU

property params
class neuromancer.psl.nonautonomous.IverSimple(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_NonAutonomous

Dynamic model of Unmanned Underwater Vehicle (modified from Stankiewicz et al) – Excludes rolling, sway, currents, Includes: hydrostate/dynamic terms, control surface deflections/propeller thrust, and actuator dynamics with non-kinematic output

equations(t, x, u)[source]
  • States (8): [theta, psi, uu, q, r, delta_u, delta_q, delta_r]

  • Inputs (3): [delta_uc, delta_qc, delta_rc] (thrust speed/deflections, normalized)

get_U(nsim, signal=None, **signal_kwargs)[source]

For sampling a sequence of control actions :param nsim: length of sequence :return: Matrix nsim X nU

property params
class neuromancer.psl.nonautonomous.LorenzControl(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_NonAutonomous

equations(t, x, u)[source]
get_U(nsim, signal=None, **signal_kwargs)[source]

For sampling a sequence of control actions :param nsim: length of sequence :return: Matrix nsim X nU

property params
u_fun(t)[source]
class neuromancer.psl.nonautonomous.SEIR_population(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_NonAutonomous

Susceptible, Exposed, Infected, and Recovered (SEIR) population population model. Used to model COVID-19 spread. Source of the model

states:

  • Susceptible (s): population fraction that is susceptible to the virus

  • Exposed (e): population fraction is infected with the virus but does not transmit to others

  • Infectious (i): population fraction that is infected and can infect others

  • Recovered (r): population fraction recovered from infection and is immune from further infection

equations(t, x, u)[source]
  • Inputs (1): social distancing (u=0 (none), u=1 (total isolation))

  • States (4):
    • Susceptible (s): population fraction that is susceptible to the virus

    • Exposed (e): population fraction is infected with the virus but does not transmit to others

    • Infectious (i): population fraction that is infected and can infect others

    • Recovered (r): population fraction recovered from infection and is immune from further infection

get_U(nsim, signal=None, **signal_kwargs)[source]

For sampling a sequence of control actions :param nsim: length of sequence :return: Matrix nsim X nU

property params
class neuromancer.psl.nonautonomous.SwingEquation(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_NonAutonomous

Power Grid Swing Equation. The second-order swing equation is converted to two first-order ODEs

equations(t, x, u)[source]
get_U(nsim, signal=None, **signal_kwargs)[source]

For sampling a sequence of control actions :param nsim: length of sequence :return: Matrix nsim X nU

property params
class neuromancer.psl.nonautonomous.Tank(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_NonAutonomous

Single Tank model Original code obtained from APMonitor

equations(t, x, u)[source]
  • States (1): level in the tanks

  • Inputs u(1): c - valve coefficient (kg/s / %open)

  • Inputs u(2): valve in % [0-100]

get_U(nsim, signal=None, **signal_kwargs)[source]

For sampling a sequence of control actions :param nsim: length of sequence :return: Matrix nsim X nU

get_x0()[source]

Randomly sample an initial condition

Parameters:

box – Dictionary with keys ‘min’ and ‘max’ and values np.arrays with shape=(nx,)

property params
class neuromancer.psl.nonautonomous.ThomasAttractorControl(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_NonAutonomous

Thomas’ cyclically symmetric attractor control input: dissipativity parameter b Source

equations(t, x, u)[source]
get_U(nsim, signal=None, **signal_kwargs)[source]

For sampling a sequence of control actions :param nsim: length of sequence :return: Matrix nsim X nU

property params
class neuromancer.psl.nonautonomous.TwoTank(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_NonAutonomous

Two Tank model. Original code obtained from APMonitor

equations(t, x, u)[source]
get_U(nsim, signal=None, **signal_kwargs)[source]

For sampling a sequence of control actions :param nsim: length of sequence :return: Matrix nsim X nU

get_x0()[source]

Randomly sample an initial condition

Parameters:

box – Dictionary with keys ‘min’ and ‘max’ and values np.arrays with shape=(nx,)

property params
property umax

Note that although the theoretical upper bound is 1.0, this results in numerical instability in the integration.

property umin
class neuromancer.psl.nonautonomous.VanDerPolControl(exclude_norms=['Time'], backend='numpy', requires_grad=False, seed: int | Generator = 59, set_stats=True)[source]

Bases: ODE_NonAutonomous

Van der Pol oscillator

equations(t, x, u)[source]
get_U(nsim, signal=None, **signal_kwargs)[source]

For sampling a sequence of control actions :param nsim: length of sequence :return: Matrix nsim X nU

property params

neuromancer.psl.norms module

class neuromancer.psl.norms.StandardScaler(stats)[source]

Bases: object

This class subsumes some boiler plate code translating between numpy and pytorch. All normalized and denormalized data should be returned as the same type.

inverse_transform(Z)[source]
transform(X)[source]
neuromancer.psl.norms.denormalize()[source]
neuromancer.psl.norms.normalize()[source]

neuromancer.psl.perturb module

Base Control Profiles for System excitation # TODO: All signals should be nsim X nx np.arrays of type np.float64. # TODO: Any signals bounded by xmin and xmax should be tested to ensure this. # TODO: No camel case functions # TODO: No random seed setting # TODO: Only variables with upper case should be arrays which are matrices (this is discouraged but acceptable)

neuromancer.psl.perturb.Periodic(nx=1, nsim=100, numPeriods=1, xmax=1, xmin=0, form='sin', rseed=1)[source]

periodic signals, sine, cosine :param nx: (int) Number signals :param nsim: (int) Number time steps :param numPeriods: (int) Number of periods :param xmax: (int/list/ndarray) signal maximum value :param xmin: (int/list/ndarray) signal minimum value :param form: (str) form of the periodic signal ‘sin’ or ‘cos’ :param rseed: (int) Set random seed

neuromancer.psl.perturb.RandomWalk(nx=1, nsim=100, xmax=1, xmin=0, sigma=0.05, rseed=1)[source]
Parameters:
  • nx – (int) State space dimension

  • nsim – (int) Number of simulation steps

  • xmax – (float) Upper bound on state values

  • xmin – (float) Lower bound on state values

  • sigma – (float) Variance of normal distribution

  • rseed – (int) Set random seed

Returns:

neuromancer.psl.perturb.Sawtooth(nx=1, nsim=100, numPeriods=1, xmax=1, xmin=0, rseed=1)[source]

ramp change :param nx: (int) Number signals :param nsim: (int) Number time steps :param numPeriods: (int) Number of periods :param xmax: (int/list/ndarray) signal maximum value :param xmin: (int/list/ndarray) signal minimum value :param rseed: (int) Set random seed

neuromancer.psl.perturb.SplineSignal(nsim=500, values=None, xmin=0, xmax=1, rseed=1)[source]

Generates a smooth cubic spline trajectory by interpolating between data points

Parameters:
  • nsim – (int) Number of simulation steps

  • values – (np.array) values to interpolate

  • xmin – (float) Minimum value of time series

  • xmax – (float) Maximum value of time series

  • rseed – (int) Set random seed.

Returns:

neuromancer.psl.perturb.Step(nx=1, nsim=100, tstep=50, xmax=1, xmin=0, rseed=1)[source]

step change :param nx: (int) Number signals :param nsim: (int) Number time steps :param tstep: (int) time of the step :param xmax: (int/list/ndarray) signal maximum value :param xmin: (int/list/ndarray) signal minimum value :param rseed: (int) Set random seed

neuromancer.psl.perturb.Steps(nx=1, nsim=100, values=None, randsteps=5, xmax=1, xmin=0, rseed=1)[source]
Parameters:
  • nx – (int) Number signals

  • nsim – (int) Number time steps

  • values – (list/ndarray) sequence of step changes, e.g., [0.4, 0.8, 1, 0.7, 0.3, 0.0]

  • randsteps – (int) number of random step changes if values is None

  • xmax – (int/ndarray) signal maximum value

  • xmin – (int/ndarray) signal minimum value

  • rseed – (int) Set random seed

Returns:

neuromancer.psl.perturb.WhiteNoise(nx=1, nsim=100, xmax=1, xmin=0, rseed=1)[source]

White Noise :param nx: (int) Number signals :param nsim: (int) Number time steps :param xmax: (int/list/ndarray) signal maximum value :param xmin: (int/list/ndarray) signal minimum value :param rsee: (int) Set random seed

neuromancer.psl.perturb.random_walk(nsim, d, min=0.0, max=1.0, sigma=0.05)[source]

Gaussian random walk for arbitrary number of dimensions scaled between min/max bounds TODO: Test within min and max. Test nsim, d, edge case d = 1. :param nsim: (int) Number of simulation steps :param d: (int) Number of dimensions for the random walk :param min: (float or 1-d array) Lower bound on values :param max: (float or 1-d array) Upper bound on values :param sigma: (float or 1-d array) Variance of normal distribution :return: (np.array shape=(nsim, d)) Random walk time series of dimension nx and length nsim

neuromancer.psl.perturb.white_noise(nsim, d, min=0.0, max=1.0, sigma=0.05)[source]

Gaussian random walk for arbitrary number of dimensions scaled between min/max bounds :param nsim: (int) Number of simulation steps :param d: (int) Number of dimensions for the random walk :param min: (float or 1-d array) Lower bound on values :param max: (float or 1-d array) Upper bound on values :param sigma: (float or 1-d array) Variance of normal distribution :return: (np.array shape=(nsim, d)) Random walk time series of dimension nx and length nsim

neuromancer.psl.plot module

# TODO: stream plots for phase spaces of ODEs # TODO: generate correlation network - https://python-graph-gallery.com/327-network-from-correlation-matrix/ # TODO: plot information-theoretic measures for time series data - https: // elife - asu.github.io / PyInform / timeseries.html

neuromancer.psl.plot.get_colors(k)[source]

Returns k colors evenly spaced across the color wheel. :param k: (int) Number of colors you want. :return:

neuromancer.psl.plot.pltCL(Y, U=None, D=None, X=None, R=None, Ymin=None, Ymax=None, Umin=None, Umax=None, figname=None)[source]

plot trained open loop dataset Ytrue: ground truth training signal Ytrain: trained model response

neuromancer.psl.plot.pltCorrelate(X, figname=None)[source]

plot correlation matrices of time series data https://realpython.com/numpy-scipy-pandas-correlation-python/

neuromancer.psl.plot.pltOL(Y, Ytrain=None, U=None, D=None, X=None, figname=None)[source]

plot trained open loop dataset Ytrue: ground truth training signal Ytrain: trained model response

neuromancer.psl.plot.pltPhase(X, Xtrain=None, figname=None)[source]

plot phase space for 2D and 3D state spaces

https://matplotlib.org/3.2.1/gallery/images_contours_and_fields/plot_streamplot.html https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.streamplot.html https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.quiver.html http://kitchingroup.cheme.cmu.edu/blog/2013/02/21/Phase-portraits-of-a-system-of-ODEs/ http://systems-sciences.uni-graz.at/etextbook/sw2/phpl_python.html

neuromancer.psl.plot.pltRecurrence(X, figname=None)[source]

plot recurrence of time series data https://pyts.readthedocs.io/en/stable/auto_examples/image/plot_rp.html https://pyts.readthedocs.io/en/stable/auto_examples/multivariate/plot_joint_rp.html#sphx-glr-auto-examples-multivariate-plot-joint-rp-py https://pyts.readthedocs.io/en/stable/auto_examples/image/plot_mtf.html https://arxiv.org/pdf/1610.07273.pdf https://pyts.readthedocs.io/en/stable/auto_examples/image/plot_gaf.html#sphx-glr-auto-examples-image-plot-gaf-py

neuromancer.psl.signals module

Random signals to simulate arbitrary sequence of control actions or disturbances.

neuromancer.psl.signals.arma(nsim, d, min=0.0, max=1.0, q=10, p=10, bound=True, rng=Generator(PCG64) at 0x7FA1E30727A0)[source]

Random autoregressive moving average signal.

Parameters:
  • nsim – (int) Number of simulation steps

  • d – (int) Number of dimensions

  • min – (float or 1-d array) Lower bound on values

  • max – (float or 1-d array) Upper bound on values

Returns:

(np.array shape=(nsim, d)) ARMA time series

neuromancer.psl.signals.beta(nsim, d, min=0.0, max=1.0, alpha: float = 2, beta: float = 2, rng=Generator(PCG64) at 0x7FA1E3072960)[source]

roughly upside down parabola shaped probability with a=b=2, support (0,1). The beta distribution is flexible with parameters a,b. It always has support (0,1).

Parameters:
  • nsim – (int) Number of simulation steps

  • d – (int) Number of dimensions

  • min – (float or 1-d array) Lower bound on values

  • max – (float or 1-d array) Upper bound on values

  • alpha – (float) parameter of beta distribution

  • beta – (float) parameter of beta distribution

  • rng – (np.random.Generator) random number generator

Returns:

(np.array shape=(nsim, d)) scatter of beta distributed points

neuromancer.psl.signals.beta_walk_max_step(nsim, d, min: float | ~numpy.ndarray = 0.0, max: float | ~numpy.ndarray = 1.0, max_step: float | ~numpy.ndarray | None = None, x0: float | ~numpy.ndarray | None = None, dtype: ~numpy.dtype = <class 'numpy.float32'>, alpha: float = 2, beta: float = 2, p: float = 0.3, rng=Generator(PCG64) at 0x7FA1E3072C00) ndarray[source]

Generate a random walk from a beta distribution with parameters (2,2). between min and max, with a maximum step size of max_step. No truncation is necessary, beta distro is bounded.

Parameters:
  • nsim – (int) Number of simulation steps

  • d – (int) Number of dimensions

  • min – (float or 1-d array) Lower bound on values

  • max – (float or 1-d array) Upper bound on values

  • max_step – (float or 1-d array) Maximum step size

  • x0 – (float or 1-d array) Initial value

  • dtype – (dtype) Data type of output

  • alpha – (float) alpha parameter of beta distribution

  • beta – (float) beta parameter of beta distribution

  • p – (float) probability of stepping

  • rng – (np.random.Generator) Random number generator

Returns:

(np.ndarray) Random walk

neuromancer.psl.signals.beta_walk_mean(nsim, d, min: float | ~numpy.ndarray = 0.0, max: float | ~numpy.ndarray = 1.0, max_step: float | ~numpy.ndarray | None = None, x0: float | ~numpy.ndarray | None = None, dtype: ~numpy.dtype = <class 'numpy.float32'>, ab: float = 8, p: float = 0.5, q: float = 0.5, rng=Generator(PCG64) at 0x7FA1E3072B20) ndarray[source]

Generate a random walk from a beta distribution with parameters alpha beta set so that the mean is the current position and the pdf is frown-like when the other parameter is 2.

Parameters:
  • nsim – (int) Number of simulation steps

  • d – (int) Number of dimensions

  • min – (float or 1-d array) Lower bound on values

  • max – (float or 1-d array) Upper bound on values

  • max_step – (float or 1-d array) Maximum step size

  • x0 – (float or 1-d array) Initial value

  • dtype – (dtype) Data type of output

  • ab – (float) alpha or beta parameter of beta distribution

  • p – (float) probability of any step

  • q – (float) probability of individual beta step

  • rng – (np.random.Generator) Random number generator

Returns:

(np.array shape=(nsim, d)) Random walk

neuromancer.psl.signals.nd_walk(nsim, d, min: float | ~numpy.ndarray = 0.0, max: float | ~numpy.ndarray = 1.0, x0: float | ~numpy.ndarray | None = None, max_step: float | ~numpy.ndarray | None = None, p: float = 0.3, avoid_edge: bool = True, granularity: int = 0, dtype: ~numpy.dtype = <class 'numpy.float32'>, rng=Generator(PCG64) at 0x7FA1E3072CE0) ndarray[source]

random walk which avoids the edge by default. If granularity is 0 takes uniform random steps, if granularity is 1 always takes max_step.

Parameters:
  • nsim – (int) Number of simulation steps

  • d – (int) Number of dimensions

  • min – (float or 1-d array) Lower bound on values

  • max – (float or 1-d array) Upper bound on values

  • x0 – (float or 1-d array) Initial value

  • max_step – (float or 1-d array) Maximum step size

  • p – (float) probability of stepping

  • avoid_edge – (bool) whether to avoid the edge

  • granularity – (int) granularity of steps (0 is uniform random, 1 is max_step, >1 takes a step of length n*max_step/granularity where n is random int 1<=n<=granularity.

  • dtype – (dtype) Data type of output

  • rng – (np.random.Generator) Random number generator

Returns:

(np.ndarray) Random walk

neuromancer.psl.signals.noise(nsim, d, min=0.0, max=1.0, sigma=0.05, bound=True, rng=Generator(PCG64) at 0x7FA1E3072340)[source]

Independent Gaussian noise for arbitrary number of dimensions scaled between min/max bounds

Parameters:
  • nsim – (int) Number of simulation steps

  • d – (int) Number of dimensions

  • min – (float or 1-d array) Lower bound on values

  • max – (float or 1-d array) Upper bound on values

  • sigma – (float or 1-d array) Variance of normal distribution

  • bound – (bool) Whether to scale signal to between min and max

Returns:

(np.array shape=(nsim, d)) White noise time series of dimension d and length nsim

neuromancer.psl.signals.np_softmax(x, dim)[source]
neuromancer.psl.signals.periodic(nsim, d, min=0.0, max=1.0, periods=30, form='sin', phase_offset=False, rng=Generator(PCG64) at 0x7FA1E3072500)[source]

periodic signals, sine, cosine

Parameters:
  • nsim – (int) Number of simulation steps

  • d – (int) Number of dimensions

  • min – (float or 1-d array) Lower bound on values

  • max – (float or 1-d array) Upper bound on values

  • periods – (int) Number of periods taking place across nsim

Returns:

(np.array shape=(nsim, d)) Periodic time-series

neuromancer.psl.signals.prbs(nsim, d, min=0.0, max=1.0, p=0.9, rng=Generator(PCG64) at 0x7FA1E3072880)[source]

pseudo-random binary signal taking values min or max.

Parameters:
  • nsim – (int) Number of simulation steps

  • d – (int) Number of dimensions

  • min – (float or 1-d array) Lower bound on values

  • max – (float or 1-d array) Upper bound on values

  • p – (float) probability of switching from min to max or vice versa.

Returns:

(np.array shape=(nsim, d)) PRBS time series

neuromancer.psl.signals.sines(nsim, d, min=0.0, max=1.0, periods=30, nwaves=20, form='sin', rng=Generator(PCG64) at 0x7FA1E30725E0)[source]

sum of sines

Parameters:
  • nsim – (int) Number of simulation steps

  • d – (int) Number of dimensions

  • min – (float or 1-d array) Lower bound on values

  • max – (float or 1-d array) Upper bound on values

  • periods – (int) Number of periods taking place across nsim

Returns:

(np.array shape=(nsim, d)) Periodic time-series

neuromancer.psl.signals.spline(nsim, d, min=0.0, max=1.0, values=None, n_interpolants=30, rng=Generator(PCG64) at 0x7FA1E30726C0)[source]

Generates a smooth cubic spline trajectory by interpolating between data points

Parameters:
  • nsim – (int) Number of simulation steps

  • d – (int) Number of dimensions

  • min – (float or 1-d array) Lower bound on values

  • max – (float or 1-d array) Upper bound on values

  • n_interpolants – (int) Number of values to interpolate between

Returns:

(np.array shape=(nsim, d)) Periodic time-series

neuromancer.psl.signals.step(nsim, d, min=0.0, max=1.0, randsteps=30, values=None, rng=Generator(PCG64) at 0x7FA1E3072420)[source]

Random step function for arbitrary number of dimensions

Parameters:
  • nsim – (int) Number of simulation steps

  • d – (int) Number of dimensions

  • min – (float or 1-d array) Lower bound on values

  • max – (float or 1-d array) Upper bound on values

  • randsteps – (int) Number of random steps in time series (will infer from values if values is not None)

  • values – (np.array) An ordered list of values for each step change

Returns:

(np.array shape=(nsim, d)) Time series of random steps

neuromancer.psl.signals.walk(nsim, d, min=0.0, max=1.0, sigma=0.05, bound=True, rng=Generator(PCG64) at 0x7FA1E3072260)[source]

Gaussian random walk for arbitrary number of dimensions scaled between min/max bounds

Parameters:
  • nsim – (int) Number of simulation steps

  • d – (int) Number of dimensions

  • min – (float or 1-d array) Lower bound on values

  • max – (float or 1-d array) Upper bound on values

  • sigma – (float or 1-d array) Variance of normal distribution

  • bound – (bool) Whether to scale signal to between min and max

Returns:

(np.array shape=(nsim, d)) Random walk time series of dimension d and length nsim

neuromancer.psl.system_emulator module

neuromancer.psl.system_emulator.system_to_psl(nm_model, psl_system)[source]
Parameters:
  • nm_model – (neuromancer.System)

  • psl_system – (neuromancer.psl.BuildingEnvelope)

Returns:

(SystemPSL) An instance of class SystemPSL

Module contents