Skip to content

Dynamic models

Model classes, one module per category key of the model dictionary.

gen

GenEvents

GenEvents(mdl)

Bases: ModelEvents

Source code in src/tops/events.py
def __init__(self, mdl):
    self.mdl = mdl

actions class-attribute instance-attribute

actions = ('connect', 'disconnect')

connect

connect(gen_name)

Connect a generator to its bus. It is kept in step with the bus while disconnected, so it connects without a large transient, at the mechanical power its governor gives at that moment.

Parameters:

Name Type Description Default
gen_name

Name of the generator.

required

Returns:

Type Description

The change in the admittance matrix.

Source code in src/tops/dyn_models/gen.py
def connect(self, gen_name):
    """Connect a generator to its bus. It is kept in step with the bus while disconnected, so it connects without
    a large transient, at the mechanical power its governor gives at that moment.

    :param gen_name: Name of the generator.
    :return: The change in the admittance matrix.
    """
    idx = self._unit_idx(gen_name)
    if self.mdl.connected[idx]:
        return []
    self.mdl.connected[idx] = True
    return [self.mdl.admittance_change(idx, sign=1)]

disconnect

disconnect(gen_name)

Disconnect a generator from its bus. It then runs at no load, with its exciter, and a synchronizer keeps its speed and angle in step with the bus (see GEN).

Parameters:

Name Type Description Default
gen_name

Name of the generator.

required

Returns:

Type Description

The change in the admittance matrix.

Source code in src/tops/dyn_models/gen.py
def disconnect(self, gen_name):
    """Disconnect a generator from its bus. It then runs at no load, with its exciter, and a synchronizer keeps its
    speed and angle in step with the bus (see ``GEN``).

    :param gen_name: Name of the generator.
    :return: The change in the admittance matrix.
    """
    idx = self._unit_idx(gen_name)
    if not self.mdl.connected[idx]:
        return []
    self.mdl.connected[idx] = False
    return [self.mdl.admittance_change(idx, sign=-1)]

GEN

GEN(*args, **kwargs)

Bases: DAEModel

Synchronous machine (sixth order).

A generator can be out of service: from the start, with the optional connected column, or after a disconnect event. It then gives no current, its terminal voltage is its own open-circuit voltage (so that its exciter keeps regulating it), and its mechanical power is ignored: a synchronizer, a critically damped second-order loop with natural frequency sync_omega (rad/s, default 2), drives its speed and angle to those of the bus voltage, so that it can be connected again at any time.

Source code in src/tops/dyn_models/gen.py
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.connected = read_connected(self.par)

    for req_attr, default in zip(['PF_n', 'N_par', 'R', 'X_l'], [1, 1, 0, 0]):
        if not req_attr in self.par.dtype.names:
            new_field = np.ones(len(self.par), dtype=[(req_attr, float)])
            new_field[req_attr] *= default
            self.par = dps_uf.combine_recarrays(self.par, new_field)

    fix_idx = self.par['V_n'] == 0
    gen_bus_idx = dps_uf.lookup_strings(self.par['bus'], self.sys_par['bus_names'])
    self.par['V_n'][fix_idx] = self.sys_par['bus_v_n'][gen_bus_idx][fix_idx]

    fix_idx = self.par['S_n'] == 0
    self.par['S_n'][fix_idx] = self.sys_par['s_n']

    self.bus_idx = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.bus_idx_red = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])

events_class class-attribute instance-attribute

events_class = GenEvents

sync_omega class-attribute instance-attribute

sync_omega = 2.0

connected instance-attribute

connected = read_connected(self.par)

par instance-attribute

par = dps_uf.combine_recarrays(self.par, new_field)

bus_idx instance-attribute

bus_idx = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

bus_idx_red instance-attribute

bus_idx_red = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

bus_ref_spec

bus_ref_spec()
Source code in src/tops/dyn_models/gen.py
def bus_ref_spec(self):
    return {'terminal': self.par['bus']}

load_flow_pv

load_flow_pv()
Source code in src/tops/dyn_models/gen.py
def load_flow_pv(self):
    # Generators out of service are left out of the load flow
    on = self.connected
    return self.bus_idx['terminal'][on], -self.par['P'][on]*self.par['N_par'][on], self.par['V'][on]

load_flow_q_share

load_flow_q_share()
Source code in src/tops/dyn_models/gen.py
def load_flow_q_share(self):
    # Reactive power at a bus is shared between generators in proportion to their ratings
    on = self.connected
    return self.par['S_n'][on]*self.par['N_par'][on]

init_from_load_flow

init_from_load_flow(x_0, v_0, S)
Source code in src/tops/dyn_models/gen.py
def init_from_load_flow(self, x_0, v_0, S):

    self.V_n = self.sys_par['bus_v_n'][self.bus_idx_red['terminal']]
    self.I_n = self.sys_par['s_n']/(np.sqrt(3) * self.V_n)

    X_0 = self.local_view(x_0)

    fix_idx = self.par['V_n'] == 0
    self.par['V_n'][fix_idx] = self.sys_par['bus_v_n'][self.bus_idx['terminal']][fix_idx]

    fix_idx = self.par['S_n'] == 0
    self.par['S_n'][fix_idx] = self.sys_par['s_n']

    p = self.par

    # Generators out of service are not in the load flow: they start at no load, in step with their bus, with their
    # open-circuit voltage at their voltage setpoint
    S_all = np.zeros(self.n_units, dtype=complex)
    S_all[self.connected] = S
    S = S_all

    s_pu = S/p['S_n']/p['N_par']
    v_g = v_0[self.bus_idx['terminal']]
    v_g = np.where(self.connected, v_g, p['V']*np.exp(1j*np.angle(v_g)))
    I_g = np.conj(s_pu/v_g)

    e_q_tmp = v_g + 1j * p['X_q'] * I_g
    angle = np.angle(e_q_tmp)
    speed = np.zeros_like(angle)


    I_g_dq = I_g * np.exp(1j * (np.pi / 2 - angle))
    I_d = I_g_dq.real
    I_q = I_g_dq.imag  # q-axis leading d-axis

    v_g_dq = v_g * np.exp(1j * (np.pi / 2 - angle))
    v_d = v_g_dq.real
    v_q = v_g_dq.imag

    e_q_t = v_q + p['X_d_t'] * I_d
    e_d_t = v_d - p['X_q_t'] * I_q

    e_q_st = v_q + p['X_d_st'] * I_d
    e_d_st = v_d - p['X_q_st'] * I_q

    e_q = e_q_t + I_d * (p['X_d'] - p['X_d_t'])
    e_q_0 = e_q.copy()

    PF_n = p['PF_n'] if 'PF_n' in p.dtype.names else 1
    self._input_values['P_m'] = s_pu.real/PF_n
    self._input_values['E_f'] = e_q_0

    X_0['speed'][:] = speed
    X_0['angle'][:] = angle
    X_0['e_q_t'][:] = e_q_t
    X_0['e_d_t'][:] = e_d_t
    X_0['e_q_st'][:] = e_q_st
    X_0['e_d_st'][:] = e_d_st

dyn_const_adm

dyn_const_adm()
Source code in src/tops/dyn_models/gen.py
def dyn_const_adm(self):
    idx_bus = self.bus_idx['terminal']
    bus_v_n = self.sys_par['bus_v_n'][idx_bus]
    z_n = bus_v_n ** 2 / self.sys_par['s_n']

    impedance_pu_gen = 1j * self.par['X_d_st']  # self.par['R'] + 1j * (self.par['X_d_st'] + self.par['X_l']?)
    impedance = impedance_pu_gen * self.par['V_n'] ** 2 / self.par['S_n'] / z_n
    self.admittance = self.par['N_par'] / impedance  # Kept for generators out of service, so that connect can stamp it
    return self.admittance*self.connected, (idx_bus,)*2

admittance_change

admittance_change(gen_idx, sign)

Change in the reduced admittance matrix when connecting (sign=1) or disconnecting (sign=-1) a generator.

Source code in src/tops/dyn_models/gen.py
def admittance_change(self, gen_idx, sign):
    """Change in the reduced admittance matrix when connecting (sign=1) or disconnecting (sign=-1) a generator."""
    idx = self.bus_idx_red['terminal'][gen_idx]
    if idx < 0:
        raise ValueError(f'The bus of generator {self.par["name"][gen_idx]} is not in the reduced system.')
    return AdmittanceChange(np.array([sign*self.admittance[gen_idx]]), np.array([idx]), np.array([idx]))

state_list

state_list()
Source code in src/tops/dyn_models/gen.py
def state_list(self):
    return ['speed', 'angle', 'e_q_t', 'e_d_t', 'e_q_st', 'e_d_st']

input_list

input_list()
Source code in src/tops/dyn_models/gen.py
def input_list(self):
    return ['V_t_abs', 'V_t_angle', 'P_m', 'E_f', 'v_aux', 'v_pss']

reduced_system

reduced_system()
Source code in src/tops/dyn_models/gen.py
def reduced_system(self):
    return self.par['bus']

current_injections

current_injections(x, v)
Source code in src/tops/dyn_models/gen.py
def current_injections(self, x, v):
    p = self.par
    X = self.local_view(x)
    i_inj_d = X['e_q_st'] / (1j * p['X_d_st']) * self.q(x, v) * p['N_par']
    i_inj_q = X['e_d_st'] / (1j * p['X_q_st']) * self.d(x, v) * p['N_par']
    i_inj = i_inj_d + i_inj_q

    I_n = p['S_n'] / (np.sqrt(3) * p['V_n'])

    i_n = self.sys_par['s_n']/(np.sqrt(3) * self.sys_par['bus_v_n'])

    # System p.u. base
    I_inj = i_inj*I_n/i_n[self.bus_idx_red['terminal']]*self.connected

    return self.bus_idx_red['terminal'], I_inj

state_derivatives

state_derivatives(dx, x, v)
Source code in src/tops/dyn_models/gen.py
def state_derivatives(self, dx, x, v):
    dX = self.local_view(dx)
    X = self.local_view(x)
    p = self.par

    T_m = self.P_m(x, v)/(1 + X['speed'])
    P_e = self.p_e(x, v)

    PF_n = p['PF_n'] if 'PF_n' in p.dtype.names else 1
    H = p['H']/PF_n

    dX['speed'][:] = 1 / (2 * H) * (T_m - P_e/PF_n - p['D'] * X['speed'])
    dX['angle'][:] = X['speed'] * 2 * np.pi * self.sys_par['f_n']
    dX['e_q_t'][:] = 1 / (p['T_d0_t']) * (self.E_f(x, v) + self.v_aux(x, v) - X['e_q_t'] - self.i_d(x, v) * (p['X_d'] - p['X_d_t']))
    dX['e_d_t'][:] = 1 / (p['T_q0_t']) * (-X['e_d_t'] + self.i_q(x, v) * (p['X_q'] - p['X_q_t']))
    dX['e_q_st'][:] = 1 / (p['T_d0_st']) * (X['e_q_t'] - X['e_q_st'] - self.i_d(x, v) * (p['X_d_t'] - p['X_d_st']))
    dX['e_d_st'][:] = 1 / (p['T_q0_st']) * (X['e_d_t'] - X['e_d_st'] + self.i_q(x, v) * (p['X_q_t'] - p['X_q_st']))

    # Generators out of service: the synchronizer keeps them in step with their bus
    off = ~self.connected
    if off.any():
        w_n = 2*np.pi*self.sys_par['f_n']
        angle_bus = np.angle(v[self.bus_idx_red['terminal']]) - np.angle(X['e_q_st'] - 1j*X['e_d_st'])
        error = np.angle(np.exp(1j*(angle_bus - X['angle'])))[off]
        dX['speed'][off] = self.sync_omega**2/w_n*error
        dX['angle'][off] = w_n*X['speed'][off] + 2*self.sync_omega*error

d

d(x, v)
Source code in src/tops/dyn_models/gen.py
def d(self, x, v):
    return np.exp(1j * (self.local_view(x)['angle'] - np.pi / 2))

q

q(x, v)
Source code in src/tops/dyn_models/gen.py
def q(self, x, v):
    return np.exp(1j * self.local_view(x)['angle'])

v_t

v_t(x, v)
Source code in src/tops/dyn_models/gen.py
def v_t(self, x, v):
    # A generator out of service has its open-circuit voltage at its terminal
    return np.where(self.connected, v[self.bus_idx_red['terminal']], self.e_st(x, v))

v_t_abs

v_t_abs(x, v)
Source code in src/tops/dyn_models/gen.py
def v_t_abs(self, x, v):
    return np.abs(self.v_t(x, v))

v_setp

v_setp(x, v)
Source code in src/tops/dyn_models/gen.py
def v_setp(self, x, v):
    return self.par['V']

e_q_st

e_q_st(x, v)
Source code in src/tops/dyn_models/gen.py
def e_q_st(self, x, v):
    return self.local_view(x)['e_q_st']

e_d_st

e_d_st(x, v)
Source code in src/tops/dyn_models/gen.py
def e_d_st(self, x, v):
    return self.local_view(x)['e_d_st']

e_q_t

e_q_t(x, v)
Source code in src/tops/dyn_models/gen.py
def e_q_t(self, x, v):
    return self.local_view(x)['e_q_t']

e_d_t

e_d_t(x, v)
Source code in src/tops/dyn_models/gen.py
def e_d_t(self, x, v):
    return self.local_view(x)['e_d_t']

angle

angle(x, v)
Source code in src/tops/dyn_models/gen.py
def angle(self, x, v):
    return self.local_view(x)['angle']

speed

speed(x, v)
Source code in src/tops/dyn_models/gen.py
def speed(self, x, v):
    return self.local_view(x)['speed']

e_st

e_st(x, v)
Source code in src/tops/dyn_models/gen.py
def e_st(self, x, v):
    return self.e_q_st(x, v)*self.q(x, v) + self.e_d_st(x, v)*self.d(x, v)

e_t

e_t(x, v)
Source code in src/tops/dyn_models/gen.py
def e_t(self, x, v):
    return self.e_q_t(x, v)*self.q(x, v) + self.e_d_t(x, v)*self.d(x, v)

i

i(x, v)
Source code in src/tops/dyn_models/gen.py
def i(self, x, v):
    return (self.e_st(x, v) - self.v_t(x, v)) / (1j * self.par['X_d_st'])

I

I(x, v)
Source code in src/tops/dyn_models/gen.py
def I(self, x, v):
    # A (or kA, depending on other p.u. base values)
    return self.i(x, v)*self.I_n

i_d

i_d(x, v)
Source code in src/tops/dyn_models/gen.py
def i_d(self, x, v):
    i_dq = self.i(x, v)*np.exp(1j*(np.pi/2 - self.angle(x, v)))
    return i_dq.real

i_q

i_q(x, v)
Source code in src/tops/dyn_models/gen.py
def i_q(self, x, v):
    i_dq = self.i(x, v)*np.exp(1j*(np.pi/2 - self.angle(x, v)))
    return i_dq.imag

s_e

s_e(x, v)
Source code in src/tops/dyn_models/gen.py
def s_e(self, x, v):
    # Apparent power in p.u. (generator base units)
    return self.v_t(x, v)*np.conj(self.i(x, v))

p_e

p_e(x, v)
Source code in src/tops/dyn_models/gen.py
def p_e(self, x, v):
    # Active power in p.u. (generator base units)
    return self.s_e(x, v).real

q_e

q_e(x, v)
Source code in src/tops/dyn_models/gen.py
def q_e(self, x, v):
    # Reactive power in p.u. (generator base units)
    return self.s_e(x, v).imag

S_e

S_e(x, v)
Source code in src/tops/dyn_models/gen.py
def S_e(self, x, v):
    # Apparent power in MVA
    return self.s_e(x, v)*self.par['S_n']

P_e

P_e(x, v)
Source code in src/tops/dyn_models/gen.py
def P_e(self, x, v):
    # Active power in MW
    return self.p_e(x, v)*self.par['S_n']

Q_e

Q_e(x, v)
Source code in src/tops/dyn_models/gen.py
def Q_e(self, x, v):
    # Reactive power in MVAr
    return self.q_e(x, v)*self.par['S_n']

P_nom

P_nom(x, v)
Source code in src/tops/dyn_models/gen.py
def P_nom(self, x, v):
    # Nominal active power (can be used in governor models)
    PF_n = self.par['cosphi_n'] if 'cosphi_n' in self.par.dtype.names else 1
    return self.par['S_n']*PF_n

avr

AVR

output_list

output_list()
Source code in src/tops/dyn_models/avr.py
def output_list(self):
    return ['output']

connections

connections()
Source code in src/tops/dyn_models/avr.py
def connections(self):
    return [
        {
            'input': 'v_t',
            'source': {
                'container': 'gen',
                'mdl': '*',
                'id': self.par['gen'],
            },
            'output': 'v_t_abs',
        },
        {
            'input': 'v_setp',
            'source': {
                'container': 'gen',
                'mdl': '*',
                'id': self.par['gen'],
            },
            'output': 'v_setp',
        },
        {
            'input': 'v_pss',
            'source': {
                'container': 'gen',
                'mdl': '*',
                'id': self.par['gen'],
            },
            'output': 'v_pss',
        },
        {
            'output': 'output',
            'destination': {
                'container': 'gen',
                'mdl': '*',
                'id': self.par['gen'],
            },
            'input': 'E_f',
        }
    ]

SEXS

SEXS(
    par=None,
    sys_par=None,
    first_state_idx=0,
    n_units=None,
    **kwargs,
)

Bases: AVR, DAEModel

Source code in src/tops/dyn_models/utils.py
def __init__(self, par=None, sys_par=None, first_state_idx=0, n_units=None, **kwargs):
    if hasattr(self, 'int_par_list'):
        raise TypeError(
            f'{type(self).__name__} defines int_par_list(), but int_par has been removed. '
            f'Add the parameters to input_list() instead, and set them in _input_values.'
        )

    given = [arg for arg, used in [('par', par is not None), ('n_units', n_units is not None),
                                   ('parameters as keyword arguments', bool(kwargs))] if used]
    if len(given) != 1:
        raise TypeError(
            f'{type(self).__name__}: give exactly one of par, n_units or parameters as keyword '
            f'arguments' + (f' (got {" and ".join(given)})' if given else '') + '.')

    if n_units is not None:
        self.par = dps_uf.structured_array_from_list(names=['name'], entries=[(type(self).__name__,)]*n_units)
    else:
        self.par = par if par is not None else self.parse_input_data(**kwargs)
    self.sys_par = sys_par  # Used by subclasses (e.g. s_n, f_n)

    self.n_units = len(self.par)
    self.n_states = len(self.state_list())
    self.idx = slice(first_state_idx, first_state_idx + self.n_states*self.n_units)  # This will be shifted from outside

    self.state_desc = np.vstack([
        np.repeat(self.par['name'], self.n_states),
        np.tile(self.state_list(), self.n_units)]
    ).T

    # States are ordered by unit, then by state: [unit_0 states, unit_1 states, ...]
    self.dtypes = [(state, float) for state in self.state_list()]
    self.state_idx = np.zeros((self.n_units,), dtype=[(state, int) for state in self.state_list()])
    self.state_idx_global = np.zeros((self.n_units,), dtype=[(state, int) for state in self.state_list()])
    for i, state in enumerate(self.state_list()):
        self.state_idx[state] = np.arange(self.n_units)*self.n_states + i
        self.state_idx_global[state] = self.state_idx[state] + first_state_idx

    self.add_blocks()
    self.update_block_names()

    self._stored_outputs = {}  # See output and store_outputs
    self._outputs_in_progress = set()
    self._input_values = np.zeros(self.n_units, dtype=[(var, float) for var in self.input_list()])
    self._store_output = False
    for input_name in self.input_list():
        self.disconnect_input(input_name)
    # After add_blocks, since outputs are often assigned there (e.g. self.output = lambda x, v: ...)
    for output_name in self.all_outputs():
        _wrap_output(self, output_name)

    self.events = self.events_class(self) if self.events_class is not None else None

input_list

input_list()
Source code in src/tops/dyn_models/avr.py
def input_list(self):
    return ['v_setp', 'v_t', 'v_pss', 'bias']

add_blocks

add_blocks()
Source code in src/tops/dyn_models/avr.py
def add_blocks(self):
    p = self.par
    self.tg_red = LeadLag(T_1=p['T_a'], T_2=p['T_b'])
    self.gain = Gain(K=p['K'])
    self.time_constant_lim = TimeConstantLims(T=p['T_e'], V_min=p['E_min'], V_max=p['E_max'])
    self.tg_red.input = lambda x, v: self.v_setp(x, v) - self.v_t(x, v) + self.v_pss(x, v) + self.bias(x, v)
    self.gain.input = lambda x, v: self.tg_red.output(x, v)
    self.time_constant_lim.input = lambda x, v: self.gain.output(x, v)
    self.output = lambda x, v: self.time_constant_lim.output(x, v)

init_from_connections

init_from_connections(x0, v0, output_0)
Source code in src/tops/dyn_models/avr.py
def init_from_connections(self, x0, v0, output_0):
    self._input_values['bias'] = \
        self.tg_red.initialize(
            x0, v0, self.gain.initialize(
                x0, v0, self.time_constant_lim.initialize(
                    x0, v0, output_0['output'])
        )
    )

SEXS_PI

SEXS_PI(
    par=None,
    sys_par=None,
    first_state_idx=0,
    n_units=None,
    **kwargs,
)

Bases: AVR, DAEModel

Source code in src/tops/dyn_models/utils.py
def __init__(self, par=None, sys_par=None, first_state_idx=0, n_units=None, **kwargs):
    if hasattr(self, 'int_par_list'):
        raise TypeError(
            f'{type(self).__name__} defines int_par_list(), but int_par has been removed. '
            f'Add the parameters to input_list() instead, and set them in _input_values.'
        )

    given = [arg for arg, used in [('par', par is not None), ('n_units', n_units is not None),
                                   ('parameters as keyword arguments', bool(kwargs))] if used]
    if len(given) != 1:
        raise TypeError(
            f'{type(self).__name__}: give exactly one of par, n_units or parameters as keyword '
            f'arguments' + (f' (got {" and ".join(given)})' if given else '') + '.')

    if n_units is not None:
        self.par = dps_uf.structured_array_from_list(names=['name'], entries=[(type(self).__name__,)]*n_units)
    else:
        self.par = par if par is not None else self.parse_input_data(**kwargs)
    self.sys_par = sys_par  # Used by subclasses (e.g. s_n, f_n)

    self.n_units = len(self.par)
    self.n_states = len(self.state_list())
    self.idx = slice(first_state_idx, first_state_idx + self.n_states*self.n_units)  # This will be shifted from outside

    self.state_desc = np.vstack([
        np.repeat(self.par['name'], self.n_states),
        np.tile(self.state_list(), self.n_units)]
    ).T

    # States are ordered by unit, then by state: [unit_0 states, unit_1 states, ...]
    self.dtypes = [(state, float) for state in self.state_list()]
    self.state_idx = np.zeros((self.n_units,), dtype=[(state, int) for state in self.state_list()])
    self.state_idx_global = np.zeros((self.n_units,), dtype=[(state, int) for state in self.state_list()])
    for i, state in enumerate(self.state_list()):
        self.state_idx[state] = np.arange(self.n_units)*self.n_states + i
        self.state_idx_global[state] = self.state_idx[state] + first_state_idx

    self.add_blocks()
    self.update_block_names()

    self._stored_outputs = {}  # See output and store_outputs
    self._outputs_in_progress = set()
    self._input_values = np.zeros(self.n_units, dtype=[(var, float) for var in self.input_list()])
    self._store_output = False
    for input_name in self.input_list():
        self.disconnect_input(input_name)
    # After add_blocks, since outputs are often assigned there (e.g. self.output = lambda x, v: ...)
    for output_name in self.all_outputs():
        _wrap_output(self, output_name)

    self.events = self.events_class(self) if self.events_class is not None else None

input_list

input_list()
Source code in src/tops/dyn_models/avr.py
def input_list(self):
    return ['v_setp', 'v_t', 'v_pss']

add_blocks

add_blocks()
Source code in src/tops/dyn_models/avr.py
def add_blocks(self):
    p = self.par
    self.pi_regulator = PIRegulator(K_p=p['K_p'], K_i=p['K_i'])
    self.tg_red = LeadLag(T_1=p['T_a'], T_2=p['T_b'])
    self.gain = Gain(K=p['K'])
    self.time_constant_lim = TimeConstantLims(T=p['T_e'], V_min=p['E_min'], V_max=p['E_max'])

    self.v_setp_lag = TimeConstant(T=p['T_ext'])
    self.v_setp_lag.input = lambda x, v: self.v_setp(x, v)

    self.pi_regulator.input = lambda x, v: self.v_setp_lag.output(x, v) - self.v_t(x, v) + self.v_pss(x, v)
    self.tg_red.input = lambda x, v: self.pi_regulator.output(x, v)
    self.gain.input = lambda x, v: self.tg_red.output(x, v)
    self.time_constant_lim.input = lambda x, v: self.gain.output(x, v)
    self.output = lambda x, v: self.time_constant_lim.output(x, v)

init_from_connections

init_from_connections(x0, v0, output_0)
Source code in src/tops/dyn_models/avr.py
def init_from_connections(self, x0, v0, output_0):
    # v_0 = np.ones(self.n_units)
    v_0 = self.v_setp(x0, v0)
    self.v_setp_lag.initialize(x0, v0, v_0)
    self.pi_regulator.initialize(
        x0, v0, self.tg_red.initialize(
            x0, v0, self.gain.initialize(
                x0, v0, self.time_constant_lim.initialize(
                    x0, v0, output_0['output']
                )
            )
        )
    )

IEEET1

IEEET1(
    par=None,
    sys_par=None,
    first_state_idx=0,
    n_units=None,
    **kwargs,
)

Bases: AVR, DAEModel

Saturation not yet included!

Source code in src/tops/dyn_models/utils.py
def __init__(self, par=None, sys_par=None, first_state_idx=0, n_units=None, **kwargs):
    if hasattr(self, 'int_par_list'):
        raise TypeError(
            f'{type(self).__name__} defines int_par_list(), but int_par has been removed. '
            f'Add the parameters to input_list() instead, and set them in _input_values.'
        )

    given = [arg for arg, used in [('par', par is not None), ('n_units', n_units is not None),
                                   ('parameters as keyword arguments', bool(kwargs))] if used]
    if len(given) != 1:
        raise TypeError(
            f'{type(self).__name__}: give exactly one of par, n_units or parameters as keyword '
            f'arguments' + (f' (got {" and ".join(given)})' if given else '') + '.')

    if n_units is not None:
        self.par = dps_uf.structured_array_from_list(names=['name'], entries=[(type(self).__name__,)]*n_units)
    else:
        self.par = par if par is not None else self.parse_input_data(**kwargs)
    self.sys_par = sys_par  # Used by subclasses (e.g. s_n, f_n)

    self.n_units = len(self.par)
    self.n_states = len(self.state_list())
    self.idx = slice(first_state_idx, first_state_idx + self.n_states*self.n_units)  # This will be shifted from outside

    self.state_desc = np.vstack([
        np.repeat(self.par['name'], self.n_states),
        np.tile(self.state_list(), self.n_units)]
    ).T

    # States are ordered by unit, then by state: [unit_0 states, unit_1 states, ...]
    self.dtypes = [(state, float) for state in self.state_list()]
    self.state_idx = np.zeros((self.n_units,), dtype=[(state, int) for state in self.state_list()])
    self.state_idx_global = np.zeros((self.n_units,), dtype=[(state, int) for state in self.state_list()])
    for i, state in enumerate(self.state_list()):
        self.state_idx[state] = np.arange(self.n_units)*self.n_states + i
        self.state_idx_global[state] = self.state_idx[state] + first_state_idx

    self.add_blocks()
    self.update_block_names()

    self._stored_outputs = {}  # See output and store_outputs
    self._outputs_in_progress = set()
    self._input_values = np.zeros(self.n_units, dtype=[(var, float) for var in self.input_list()])
    self._store_output = False
    for input_name in self.input_list():
        self.disconnect_input(input_name)
    # After add_blocks, since outputs are often assigned there (e.g. self.output = lambda x, v: ...)
    for output_name in self.all_outputs():
        _wrap_output(self, output_name)

    self.events = self.events_class(self) if self.events_class is not None else None

input_list

input_list()
Source code in src/tops/dyn_models/avr.py
def input_list(self):
    return ['v_setp', 'v_t', 'v_pss', 'bias']

add_blocks

add_blocks()
Source code in src/tops/dyn_models/avr.py
def add_blocks(self):
    p = self.par
    self.time_constant_Tr = TimeConstant(T=p['T_r'])
    self.time_constant_gain_Ka_Ta = TimeConstantGainLims(K=p['K_a'], T=p['T_a'], V_min=p['V_rmin'], V_max=p['V_rmax'])
    self.time_constant_gain_Ke_Te = TimeConstantVar(K=p['K_e'], T=p['T_e'])
    # self.saturation = Saturation(E_1=p['E_1'], S_e1=p['S_e1'], E_2=p['E_2'], S_e2=p['S_e2'])
    self.diff_Kf_Tf = WashoutGain(K=p['K_f'], T_w=p['T_f'])

    self.time_constant_Tr.input = lambda x, v: self.v_t(x, v)
    self.v_error = lambda x, v: self.v_setp(x, v) - self.time_constant_Tr.output(x, v) + self.v_pss(x, v) + self.bias(x, v)
    self.time_constant_gain_Ka_Ta.input = lambda x, v: self.v_error(x, v) - self.diff_Kf_Tf.output(x, v)
    self.time_constant_gain_Ke_Te.input = lambda x, v: self.time_constant_gain_Ka_Ta.output(x, v) # + self.saturation.output(x, v)
    self.diff_Kf_Tf.input = self.time_constant_gain_Ke_Te.output
    # self.saturation.input = lambda x, v: self.time_constant_gain_Ke_Te.output(x, v)*0

    self.output = self.time_constant_gain_Ke_Te.output

init_from_connections

init_from_connections(x0, v0, output_0)
Source code in src/tops/dyn_models/avr.py
def init_from_connections(self, x0, v0, output_0):
    auto_init(self, x0, v0, output_0['output'], free_inputs=['bias'])

SCRX

SCRX(
    par=None,
    sys_par=None,
    first_state_idx=0,
    n_units=None,
    **kwargs,
)

Bases: AVR, DAEModel

Missing negative current logic!

Source code in src/tops/dyn_models/utils.py
def __init__(self, par=None, sys_par=None, first_state_idx=0, n_units=None, **kwargs):
    if hasattr(self, 'int_par_list'):
        raise TypeError(
            f'{type(self).__name__} defines int_par_list(), but int_par has been removed. '
            f'Add the parameters to input_list() instead, and set them in _input_values.'
        )

    given = [arg for arg, used in [('par', par is not None), ('n_units', n_units is not None),
                                   ('parameters as keyword arguments', bool(kwargs))] if used]
    if len(given) != 1:
        raise TypeError(
            f'{type(self).__name__}: give exactly one of par, n_units or parameters as keyword '
            f'arguments' + (f' (got {" and ".join(given)})' if given else '') + '.')

    if n_units is not None:
        self.par = dps_uf.structured_array_from_list(names=['name'], entries=[(type(self).__name__,)]*n_units)
    else:
        self.par = par if par is not None else self.parse_input_data(**kwargs)
    self.sys_par = sys_par  # Used by subclasses (e.g. s_n, f_n)

    self.n_units = len(self.par)
    self.n_states = len(self.state_list())
    self.idx = slice(first_state_idx, first_state_idx + self.n_states*self.n_units)  # This will be shifted from outside

    self.state_desc = np.vstack([
        np.repeat(self.par['name'], self.n_states),
        np.tile(self.state_list(), self.n_units)]
    ).T

    # States are ordered by unit, then by state: [unit_0 states, unit_1 states, ...]
    self.dtypes = [(state, float) for state in self.state_list()]
    self.state_idx = np.zeros((self.n_units,), dtype=[(state, int) for state in self.state_list()])
    self.state_idx_global = np.zeros((self.n_units,), dtype=[(state, int) for state in self.state_list()])
    for i, state in enumerate(self.state_list()):
        self.state_idx[state] = np.arange(self.n_units)*self.n_states + i
        self.state_idx_global[state] = self.state_idx[state] + first_state_idx

    self.add_blocks()
    self.update_block_names()

    self._stored_outputs = {}  # See output and store_outputs
    self._outputs_in_progress = set()
    self._input_values = np.zeros(self.n_units, dtype=[(var, float) for var in self.input_list()])
    self._store_output = False
    for input_name in self.input_list():
        self.disconnect_input(input_name)
    # After add_blocks, since outputs are often assigned there (e.g. self.output = lambda x, v: ...)
    for output_name in self.all_outputs():
        _wrap_output(self, output_name)

    self.events = self.events_class(self) if self.events_class is not None else None

input_list

input_list()
Source code in src/tops/dyn_models/avr.py
def input_list(self):
    return ['v_setp', 'v_t', 'v_pss', 'bias']

add_blocks

add_blocks()
Source code in src/tops/dyn_models/avr.py
def add_blocks(self):
    p = self.par

    self.lead_lag_Tb_Ta = LeadLag(T_1=p['T_a'], T_2=p['T_b'])
    self.time_constant_gain_K_Te = TimeConstantGainLims(K=p['K'], T=p['T_e'], V_min=p['E_min'], V_max=p['E_max'])

    self.v_error = lambda x, v: self.v_setp(x, v) - self.v_t(x, v) + self.v_pss(x, v) + self.bias(x, v)
    self.lead_lag_Tb_Ta.input = self.v_error
    self.time_constant_gain_K_Te.input = self.lead_lag_Tb_Ta.output

    def current_logic_block(x, v):
        bus_fed_idx = p['C_switch'] == 0
        out_signal = self.time_constant_gain_K_Te.output(x, v)
        out_signal[bus_fed_idx] *= self.v_t(x, v)[bus_fed_idx]
        return out_signal            

    self.output = current_logic_block

init_from_connections

init_from_connections(x0, v0, output_0)
Source code in src/tops/dyn_models/avr.py
def init_from_connections(self, x0, v0, output_0):
    auto_init(self, x0, v0, output_0['output'], free_inputs=['bias'])

gov

GovEvents

GovEvents(mdl)

Bases: ModelEvents

Source code in src/tops/events.py
def __init__(self, mdl):
    self.mdl = mdl

actions class-attribute instance-attribute

actions = ('set_reference',)

set_reference

set_reference(gov_name, P_m)

Set the power reference of a governor: the mechanical power that it gives in steady state at rated speed. At other speeds, its droop moves the power away from the reference.

Parameters:

Name Type Description Default
gov_name

Name of the governor.

required
P_m

Mechanical power in p.u. of the generator's rating (machine base).

required

Returns:

Type Description

No effects on the network.

Source code in src/tops/dyn_models/gov.py
def set_reference(self, gov_name, P_m):
    """Set the power reference of a governor: the mechanical power that it gives in steady state at rated speed.
    At other speeds, its droop moves the power away from the reference.

    :param gov_name: Name of the governor.
    :param P_m: Mechanical power in p.u. of the generator's rating (machine base).
    :return: No effects on the network.
    """
    try:
        value = float(P_m)
    except (TypeError, ValueError):
        value = np.nan
    if not np.isfinite(value):
        raise ValueError(f'P_m must be a finite number, got {P_m!r}.')
    self.mdl.set_reference(self._unit_idx(gov_name), value)
    return []

GOV

events_class class-attribute instance-attribute

events_class = GovEvents

input_list

input_list()
Source code in src/tops/dyn_models/gov.py
def input_list(self):
    return ['input', 'P_n_gen', 'bias']

reference_bias

reference_bias(P_m, idx=slice(None))

The bias input that gives a mechanical power in steady state at rated speed.

Parameters:

Name Type Description Default
P_m

Mechanical power in p.u. of the generator's rating (machine base).

required
idx

Indices of the units.

slice(None)
Source code in src/tops/dyn_models/gov.py
def reference_bias(self, P_m, idx=slice(None)):
    """The bias input that gives a mechanical power in steady state at rated speed.

    :param P_m: Mechanical power in p.u. of the generator's rating (machine base).
    :param idx: Indices of the units.
    """
    raise NotImplementedError(f'{type(self).__name__} has no power reference.')

set_reference

set_reference(idx, P_m)

Set the power reference of units (see GovEvents.set_reference).

Parameters:

Name Type Description Default
idx

Indices of the units.

required
P_m

Mechanical power in p.u. of the generator's rating (machine base).

required
Source code in src/tops/dyn_models/gov.py
def set_reference(self, idx, P_m):
    """Set the power reference of units (see ``GovEvents.set_reference``).

    :param idx: Indices of the units.
    :param P_m: Mechanical power in p.u. of the generator's rating (machine base).
    """
    self.set_input('bias', self.reference_bias(P_m, idx), idx)

output_list

output_list()
Source code in src/tops/dyn_models/gov.py
def output_list(self):
    return ['output']

connections

connections()
Source code in src/tops/dyn_models/gov.py
def connections(self):
    return [
        {
            'input': 'input',
            'source': {
                'container': 'gen',
                'mdl': '*',
                'id': self.par['gen'],
            },
            'output': 'speed',
        },
        {
            'input': 'P_n_gen',
            'source': {
                'container': 'gen',
                'mdl': '*',
                'id': self.par['gen'],
            },
            'output': 'P_nom',
        },
        {
            'output': 'output',
            'destination': {
                'container': 'gen',
                'mdl': '*',
                'id': self.par['gen'],
            },
            'input': 'P_m',
        }
    ]

TGOV1

TGOV1(
    par=None,
    sys_par=None,
    first_state_idx=0,
    n_units=None,
    **kwargs,
)

Bases: GOV, DAEModel

Source code in src/tops/dyn_models/utils.py
def __init__(self, par=None, sys_par=None, first_state_idx=0, n_units=None, **kwargs):
    if hasattr(self, 'int_par_list'):
        raise TypeError(
            f'{type(self).__name__} defines int_par_list(), but int_par has been removed. '
            f'Add the parameters to input_list() instead, and set them in _input_values.'
        )

    given = [arg for arg, used in [('par', par is not None), ('n_units', n_units is not None),
                                   ('parameters as keyword arguments', bool(kwargs))] if used]
    if len(given) != 1:
        raise TypeError(
            f'{type(self).__name__}: give exactly one of par, n_units or parameters as keyword '
            f'arguments' + (f' (got {" and ".join(given)})' if given else '') + '.')

    if n_units is not None:
        self.par = dps_uf.structured_array_from_list(names=['name'], entries=[(type(self).__name__,)]*n_units)
    else:
        self.par = par if par is not None else self.parse_input_data(**kwargs)
    self.sys_par = sys_par  # Used by subclasses (e.g. s_n, f_n)

    self.n_units = len(self.par)
    self.n_states = len(self.state_list())
    self.idx = slice(first_state_idx, first_state_idx + self.n_states*self.n_units)  # This will be shifted from outside

    self.state_desc = np.vstack([
        np.repeat(self.par['name'], self.n_states),
        np.tile(self.state_list(), self.n_units)]
    ).T

    # States are ordered by unit, then by state: [unit_0 states, unit_1 states, ...]
    self.dtypes = [(state, float) for state in self.state_list()]
    self.state_idx = np.zeros((self.n_units,), dtype=[(state, int) for state in self.state_list()])
    self.state_idx_global = np.zeros((self.n_units,), dtype=[(state, int) for state in self.state_list()])
    for i, state in enumerate(self.state_list()):
        self.state_idx[state] = np.arange(self.n_units)*self.n_states + i
        self.state_idx_global[state] = self.state_idx[state] + first_state_idx

    self.add_blocks()
    self.update_block_names()

    self._stored_outputs = {}  # See output and store_outputs
    self._outputs_in_progress = set()
    self._input_values = np.zeros(self.n_units, dtype=[(var, float) for var in self.input_list()])
    self._store_output = False
    for input_name in self.input_list():
        self.disconnect_input(input_name)
    # After add_blocks, since outputs are often assigned there (e.g. self.output = lambda x, v: ...)
    for output_name in self.all_outputs():
        _wrap_output(self, output_name)

    self.events = self.events_class(self) if self.events_class is not None else None

add_blocks

add_blocks()
Source code in src/tops/dyn_models/gov.py
def add_blocks(self):
    p = self.par
    self.droop = Gain(K=1/p['R'])
    self.time_constant_lim = TimeConstantLims(T=p['T_1'], V_min=p['V_min'], V_max=p['V_max'])
    self.lead_lag = LeadLag(T_1=p['T_2'], T_2=p['T_3'])
    self.damping_gain = Gain(K=p['D_t'])

    self.droop.input = lambda x, v: -self.input(x, v) + self.bias(x, v)
    self.time_constant_lim.input = lambda x, v: self.droop.output(x, v)
    self.lead_lag.input = lambda x, v: self.time_constant_lim.output(x, v)
    self.damping_gain.input = lambda x, v: self.input(x, v)

    self.output = lambda x, v: self.lead_lag.output(x, v) - self.damping_gain.output(x, v)

reference_bias

reference_bias(P_m, idx=slice(None))
Source code in src/tops/dyn_models/gov.py
def reference_bias(self, P_m, idx=slice(None)):
    return self.par['R'][idx]*P_m

init_from_connections

init_from_connections(x0, v0, output_0)
Source code in src/tops/dyn_models/gov.py
def init_from_connections(self, x0, v0, output_0):
    self._input_values['bias'] = self.droop.initialize(
        x0, v0, self.time_constant_lim.initialize(
            x0, v0, self.lead_lag.initialize(x0, v0, output_0['output'])
        )
    )

HYGOV

HYGOV(
    par=None,
    sys_par=None,
    first_state_idx=0,
    n_units=None,
    **kwargs,
)

Bases: GOV, DAEModel

Implementation of the HYGOV model. Some limiters are missing.

Source code in src/tops/dyn_models/utils.py
def __init__(self, par=None, sys_par=None, first_state_idx=0, n_units=None, **kwargs):
    if hasattr(self, 'int_par_list'):
        raise TypeError(
            f'{type(self).__name__} defines int_par_list(), but int_par has been removed. '
            f'Add the parameters to input_list() instead, and set them in _input_values.'
        )

    given = [arg for arg, used in [('par', par is not None), ('n_units', n_units is not None),
                                   ('parameters as keyword arguments', bool(kwargs))] if used]
    if len(given) != 1:
        raise TypeError(
            f'{type(self).__name__}: give exactly one of par, n_units or parameters as keyword '
            f'arguments' + (f' (got {" and ".join(given)})' if given else '') + '.')

    if n_units is not None:
        self.par = dps_uf.structured_array_from_list(names=['name'], entries=[(type(self).__name__,)]*n_units)
    else:
        self.par = par if par is not None else self.parse_input_data(**kwargs)
    self.sys_par = sys_par  # Used by subclasses (e.g. s_n, f_n)

    self.n_units = len(self.par)
    self.n_states = len(self.state_list())
    self.idx = slice(first_state_idx, first_state_idx + self.n_states*self.n_units)  # This will be shifted from outside

    self.state_desc = np.vstack([
        np.repeat(self.par['name'], self.n_states),
        np.tile(self.state_list(), self.n_units)]
    ).T

    # States are ordered by unit, then by state: [unit_0 states, unit_1 states, ...]
    self.dtypes = [(state, float) for state in self.state_list()]
    self.state_idx = np.zeros((self.n_units,), dtype=[(state, int) for state in self.state_list()])
    self.state_idx_global = np.zeros((self.n_units,), dtype=[(state, int) for state in self.state_list()])
    for i, state in enumerate(self.state_list()):
        self.state_idx[state] = np.arange(self.n_units)*self.n_states + i
        self.state_idx_global[state] = self.state_idx[state] + first_state_idx

    self.add_blocks()
    self.update_block_names()

    self._stored_outputs = {}  # See output and store_outputs
    self._outputs_in_progress = set()
    self._input_values = np.zeros(self.n_units, dtype=[(var, float) for var in self.input_list()])
    self._store_output = False
    for input_name in self.input_list():
        self.disconnect_input(input_name)
    # After add_blocks, since outputs are often assigned there (e.g. self.output = lambda x, v: ...)
    for output_name in self.all_outputs():
        _wrap_output(self, output_name)

    self.events = self.events_class(self) if self.events_class is not None else None

add_blocks

add_blocks()
Source code in src/tops/dyn_models/gov.py
def add_blocks(self):
    p = self.par
    g_min = p['g_min'] if 'g_min' in p.dtype.names else np.zeros(self.n_units)
    g_max = p['g_max'] if 'g_max' in p.dtype.names else 1*np.ones(self.n_units)

    self.time_constant_1 = TimeConstant(T=p['T_f'])
    self.pi_reg = PIRegulator2Lims(T_1=p['T_r'], T_2=p['T_r']*p['r'], x_min=g_min, x_max=g_max)
    self.gain = Gain(K=p['R'])
    self.time_constant_2 = TimeConstant(T=p['T_g'])
    self.gain_A_t = Gain(K=p['A_t'])
    self.integrator = Integrator2(T=p['T_w'])

    self.time_constant_1.input = lambda x, v: -self.input(x, v) + self.bias(x, v) - p['R']*self.c(x, v)
    self.pi_reg.input = self.time_constant_1.output  # This should have a limiter
    self.c = self.pi_reg.output
    self.time_constant_2.input = self.c
    # self.g = self.time_constant_2.output
    if 'backlash' in self.par.dtype.names:
        self.backlash = Backlash(db=p['backlash'])
        self.backlash.input = self.time_constant_2.output
        self.g = self.backlash.output
    else:
        self.g = self.time_constant_2.output

    self.q = self.integrator.output
    self.div = lambda x, v: self.q(x, v)/self.g(x, v)
    self.h = lambda x, v: self.div(x, v)**2
    self.integrator.input = lambda x, v: -self.h(x, v) + 1
    self.gain_A_t.input = lambda x, v: (self.q(x, v) - p['q_nl'])*self.h(x, v)
    self.output = self.gain_A_t.output

reference_bias

reference_bias(P_m, idx=slice(None))
Source code in src/tops/dyn_models/gov.py
def reference_bias(self, P_m, idx=slice(None)):
    p = self.par
    return p['R'][idx]*(P_m/p['A_t'][idx] + p['q_nl'][idx])

init_from_connections

init_from_connections(x0, v0, output_0)
Source code in src/tops/dyn_models/gov.py
def init_from_connections(self, x0, v0, output_0):
    p = self.par
    q_p = self.gain_A_t.initialize(x0, v0, output_0['output'])
    q = q_p + p['q_nl']
    self.integrator.initialize(x0, v0, q)
    c = g = q
    if 'backlash' in self.par.dtype.names:
        self.backlash.initialize(x0, v0, q)
    self.time_constant_2.initialize(x0, v0, q)
    self.pi_reg.initialize(x0, v0, q)
    self.pi_reg.output(x0, v0)
    self.time_constant_1.initialize(x0, v0, q*0)
    self._input_values['bias'] = p['R']*c

IEESGO

IEESGO(
    par=None,
    sys_par=None,
    first_state_idx=0,
    n_units=None,
    **kwargs,
)

Bases: GOV, DAEModel

Source code in src/tops/dyn_models/utils.py
def __init__(self, par=None, sys_par=None, first_state_idx=0, n_units=None, **kwargs):
    if hasattr(self, 'int_par_list'):
        raise TypeError(
            f'{type(self).__name__} defines int_par_list(), but int_par has been removed. '
            f'Add the parameters to input_list() instead, and set them in _input_values.'
        )

    given = [arg for arg, used in [('par', par is not None), ('n_units', n_units is not None),
                                   ('parameters as keyword arguments', bool(kwargs))] if used]
    if len(given) != 1:
        raise TypeError(
            f'{type(self).__name__}: give exactly one of par, n_units or parameters as keyword '
            f'arguments' + (f' (got {" and ".join(given)})' if given else '') + '.')

    if n_units is not None:
        self.par = dps_uf.structured_array_from_list(names=['name'], entries=[(type(self).__name__,)]*n_units)
    else:
        self.par = par if par is not None else self.parse_input_data(**kwargs)
    self.sys_par = sys_par  # Used by subclasses (e.g. s_n, f_n)

    self.n_units = len(self.par)
    self.n_states = len(self.state_list())
    self.idx = slice(first_state_idx, first_state_idx + self.n_states*self.n_units)  # This will be shifted from outside

    self.state_desc = np.vstack([
        np.repeat(self.par['name'], self.n_states),
        np.tile(self.state_list(), self.n_units)]
    ).T

    # States are ordered by unit, then by state: [unit_0 states, unit_1 states, ...]
    self.dtypes = [(state, float) for state in self.state_list()]
    self.state_idx = np.zeros((self.n_units,), dtype=[(state, int) for state in self.state_list()])
    self.state_idx_global = np.zeros((self.n_units,), dtype=[(state, int) for state in self.state_list()])
    for i, state in enumerate(self.state_list()):
        self.state_idx[state] = np.arange(self.n_units)*self.n_states + i
        self.state_idx_global[state] = self.state_idx[state] + first_state_idx

    self.add_blocks()
    self.update_block_names()

    self._stored_outputs = {}  # See output and store_outputs
    self._outputs_in_progress = set()
    self._input_values = np.zeros(self.n_units, dtype=[(var, float) for var in self.input_list()])
    self._store_output = False
    for input_name in self.input_list():
        self.disconnect_input(input_name)
    # After add_blocks, since outputs are often assigned there (e.g. self.output = lambda x, v: ...)
    for output_name in self.all_outputs():
        _wrap_output(self, output_name)

    self.events = self.events_class(self) if self.events_class is not None else None

add_blocks

add_blocks()
Source code in src/tops/dyn_models/gov.py
def add_blocks(self):
    p = self.par
    self.lead_lag = LeadLag(T_1=p['T_2'], T_2=p['T_1'])
    self.time_constant_gain_k1_t3 = TimeConstantGain(K=p['K_1'], T=p['T_3'])
    self.limiter = Limiter(Min=p['P_min'], Max=p['P_max'])
    self.time_constant_2 = TimeConstant(T=p['T_4'])

    self.gain_1_minus_k2 = Gain(K=1-p['K_2'])
    self.time_constant_gain_k2_t5 = TimeConstantGain(K=p['K_2'], T=p['T_5'])
    self.gain_1_minus_k3 = Gain(K=1-p['K_3'])
    self.time_constant_gain_k3_t6 = TimeConstantGain(K=p['K_3'], T=p['T_6'])

    self.lead_lag.input = lambda x, v: self.input(x, v)
    self.time_constant_gain_k1_t3.input = self.lead_lag.output
    self.limiter.input = lambda x, v: -self.time_constant_gain_k1_t3.output(x, v) + self.bias(x, v)

    self.time_constant_2.input = self.limiter.output
    self.gain_1_minus_k2.input = self.time_constant_2.output
    self.time_constant_gain_k2_t5.input = self.time_constant_2.output
    self.gain_1_minus_k3.input = self.time_constant_gain_k2_t5.output
    self.time_constant_gain_k3_t6.input = self.time_constant_gain_k2_t5.output

    def output_sum(x, v):
        return self.gain_1_minus_k2.output(x, v) + self.gain_1_minus_k3.output(x, v) + self.time_constant_gain_k3_t6.output(x, v)

    P_n = p['P_N']
    self.output = lambda x, v: output_sum(x, v)*(P_n/self.P_n_gen(x, v) + 1*(P_n==0))

reference_bias

reference_bias(P_m, idx=slice(None))
Source code in src/tops/dyn_models/gov.py
def reference_bias(self, P_m, idx=slice(None)):
    P_N = self.par['P_N'][idx]
    scale = np.where(P_N == 0, 1.0, self._P_n_gen_0[idx]/np.where(P_N == 0, 1.0, P_N))
    return P_m*scale

init_from_connections

init_from_connections(x0, v0, output_0)
Source code in src/tops/dyn_models/gov.py
def init_from_connections(self, x0, v0, output_0):
    auto_init(self, x0, v0, output_0['output'], free_inputs=['bias'])
    self._P_n_gen_0 = np.array(self.P_n_gen(x0, v0), dtype=float)*np.ones(self.n_units)

pss

PSS

input_list

input_list()
Source code in src/tops/dyn_models/pss.py
def input_list(self):
    return ['input']

output_list

output_list()
Source code in src/tops/dyn_models/pss.py
def output_list(self):
    return ['output']

connections

connections()
Source code in src/tops/dyn_models/pss.py
def connections(self):
    return [
        {
            'input': 'input',
            'source': {
                'container': 'gen',
                'mdl': '*',
                'id': self.par['gen'],
            },
            'output': 'speed',
        },
        {
            'output': 'output',
            'destination': {
                'container': 'gen',
                'mdl': '*',
                'id': self.par['gen'],
            },
            'input': 'v_pss',
        }
    ]

STAB1

STAB1(
    par=None,
    sys_par=None,
    first_state_idx=0,
    n_units=None,
    **kwargs,
)

Bases: PSS, DAEModel

Source code in src/tops/dyn_models/utils.py
def __init__(self, par=None, sys_par=None, first_state_idx=0, n_units=None, **kwargs):
    if hasattr(self, 'int_par_list'):
        raise TypeError(
            f'{type(self).__name__} defines int_par_list(), but int_par has been removed. '
            f'Add the parameters to input_list() instead, and set them in _input_values.'
        )

    given = [arg for arg, used in [('par', par is not None), ('n_units', n_units is not None),
                                   ('parameters as keyword arguments', bool(kwargs))] if used]
    if len(given) != 1:
        raise TypeError(
            f'{type(self).__name__}: give exactly one of par, n_units or parameters as keyword '
            f'arguments' + (f' (got {" and ".join(given)})' if given else '') + '.')

    if n_units is not None:
        self.par = dps_uf.structured_array_from_list(names=['name'], entries=[(type(self).__name__,)]*n_units)
    else:
        self.par = par if par is not None else self.parse_input_data(**kwargs)
    self.sys_par = sys_par  # Used by subclasses (e.g. s_n, f_n)

    self.n_units = len(self.par)
    self.n_states = len(self.state_list())
    self.idx = slice(first_state_idx, first_state_idx + self.n_states*self.n_units)  # This will be shifted from outside

    self.state_desc = np.vstack([
        np.repeat(self.par['name'], self.n_states),
        np.tile(self.state_list(), self.n_units)]
    ).T

    # States are ordered by unit, then by state: [unit_0 states, unit_1 states, ...]
    self.dtypes = [(state, float) for state in self.state_list()]
    self.state_idx = np.zeros((self.n_units,), dtype=[(state, int) for state in self.state_list()])
    self.state_idx_global = np.zeros((self.n_units,), dtype=[(state, int) for state in self.state_list()])
    for i, state in enumerate(self.state_list()):
        self.state_idx[state] = np.arange(self.n_units)*self.n_states + i
        self.state_idx_global[state] = self.state_idx[state] + first_state_idx

    self.add_blocks()
    self.update_block_names()

    self._stored_outputs = {}  # See output and store_outputs
    self._outputs_in_progress = set()
    self._input_values = np.zeros(self.n_units, dtype=[(var, float) for var in self.input_list()])
    self._store_output = False
    for input_name in self.input_list():
        self.disconnect_input(input_name)
    # After add_blocks, since outputs are often assigned there (e.g. self.output = lambda x, v: ...)
    for output_name in self.all_outputs():
        _wrap_output(self, output_name)

    self.events = self.events_class(self) if self.events_class is not None else None

add_blocks

add_blocks()
Source code in src/tops/dyn_models/pss.py
def add_blocks(self):
    p = self.par
    self.gain = Gain(K=p['K'])  # , input=self.input)
    self.washout = Washout(T_w=p['T'])  # , input=self.input)
    self.lead_lag_1 = LeadLag(T_1=p['T_1'], T_2=p['T_3'])  # , input=self.washout.output)
    self.lead_lag_2 = LeadLag(T_1=p['T_2'], T_2=p['T_4'])  # , input=self.lead_lag_1.output)
    self.limiter = Limiter(Min=-p['H_lim'], Max=p['H_lim'])  # , input=self.lead_lag_1.output)

    self.gain.input = lambda x, v: self.input(x, v)
    self.washout.input = lambda x, v: self.gain.output(x, v)
    self.lead_lag_1.input = lambda x, v: self.washout.output(x, v)
    self.lead_lag_2.input = lambda x, v: self.lead_lag_1.output(x, v)
    self.limiter.input = lambda x, v: self.lead_lag_2.output(x, v)

    self.output = lambda x, v: self.limiter.output(x, v)

loads

LoadEvents

LoadEvents(mdl)

Bases: ModelEvents

Source code in src/tops/events.py
def __init__(self, mdl):
    self.mdl = mdl

actions class-attribute instance-attribute

actions = ('set_power',)

set_power

set_power(load_name, P=None, Q=None)
Source code in src/tops/dyn_models/loads.py
def set_power(self, load_name, P=None, Q=None):
    idx = self._unit_idx(load_name)
    change = self.mdl.power_change(idx, P, Q)
    return [] if change is None else [change]

Load

Load(data, sys_par, **kwargs)

Bases: DAEModel

Source code in src/tops/dyn_models/loads.py
def __init__(self, data, sys_par, **kwargs):
    super().__init__(data, sys_par, **kwargs)
    self.data = data
    self.par = data
    self.n_units = len(data)

    self.bus_idx = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.bus_idx_red = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.sys_par = sys_par  # {'s_n': 0, 'f_n': 50, 'bus_v_n': None}

events_class class-attribute instance-attribute

events_class = LoadEvents

data instance-attribute

data = data

par instance-attribute

par = data

n_units instance-attribute

n_units = len(data)

bus_idx instance-attribute

bus_idx = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

bus_idx_red instance-attribute

bus_idx_red = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

sys_par instance-attribute

sys_par = sys_par

bus_ref_spec

bus_ref_spec()
Source code in src/tops/dyn_models/loads.py
def bus_ref_spec(self):
    return {'terminal': self.par['bus']}

reduced_system

reduced_system()
Source code in src/tops/dyn_models/loads.py
def reduced_system(self):
    return self.par['bus']

load_flow_pq

load_flow_pq()
Source code in src/tops/dyn_models/loads.py
def load_flow_pq(self):
    return self.bus_idx['terminal'], self.par['P'], self.par['Q']

init_from_load_flow

init_from_load_flow(x_0, v_0, S)
Source code in src/tops/dyn_models/loads.py
def init_from_load_flow(self, x_0, v_0, S):
    self.v_0 = v_0[self.bus_idx['terminal']]
    s_load = (self.par['P'] + 1j * self.par['Q']) / self.sys_par['s_n']
    self.y_load = np.conj(s_load)/abs(self.v_0)**2  # y = 0 for a load of zero power

    V_n = self.sys_par['bus_v_n'][self.bus_idx['terminal']]
    self.I_n = self.sys_par['s_n']/(np.sqrt(3)*V_n)

dyn_const_adm

dyn_const_adm()
Source code in src/tops/dyn_models/loads.py
def dyn_const_adm(self):
    return self.y_load, (self.bus_idx_red['terminal'],)*2

power_change

power_change(load_idx, P=None, Q=None)

Set the power of a load in MW and Mvar (None keeps it), at the voltage of the load flow.

Returns the change in the reduced admittance matrix, or None if the power is as it was.

Source code in src/tops/dyn_models/loads.py
def power_change(self, load_idx, P=None, Q=None):
    """Set the power of a load in MW and Mvar (None keeps it), at the voltage of the load flow.

    Returns the change in the reduced admittance matrix, or None if the power is as it was.
    """
    if not write_power(self, load_idx, P, Q):
        return None
    bus = self.bus_idx_red['terminal'][load_idx]
    s_load = (self.par['P'][load_idx] + 1j*self.par['Q'][load_idx])/self.sys_par['s_n']
    y_load = np.conj(s_load)/abs(self.v_0[load_idx])**2
    change = y_load - self.y_load[load_idx]
    self.y_load[load_idx] = y_load
    return AdmittanceChange(np.array([change]), np.array([bus]), np.array([bus]))

i

i(x, v)
Source code in src/tops/dyn_models/loads.py
def i(self, x, v):
    return v[self.bus_idx_red['terminal']]*self.y_load

I

I(x, v)
Source code in src/tops/dyn_models/loads.py
def I(self, x, v):
    return self.i(x, v)*self.I_n

s

s(x, v)
Source code in src/tops/dyn_models/loads.py
def s(self, x, v):
    return v[self.bus_idx_red['terminal']]*np.conj(self.i(x, v))

p

p(x, v)
Source code in src/tops/dyn_models/loads.py
def p(self, x, v):
    # p.u. system base
    return self.s(x, v).real

q

q(x, v)
Source code in src/tops/dyn_models/loads.py
def q(self, x, v):
    # p.u. system base
    return self.s(x, v).imag

P

P(x, v)
Source code in src/tops/dyn_models/loads.py
def P(self, x, v):
    # MW
    return self.s(x, v).real*self.sys_par['s_n']

Q

Q(x, v)
Source code in src/tops/dyn_models/loads.py
def Q(self, x, v):
    # MVA
    return self.s(x, v).imag*self.sys_par['s_n']

DynamicLoad

DynamicLoad(data, sys_par, **kwargs)

Bases: DAEModel

Source code in src/tops/dyn_models/loads.py
def __init__(self, data, sys_par, **kwargs):
    super().__init__(data, sys_par, **kwargs)
    self.data = data
    self.par = data
    self.n_units = len(data)

    self.bus_idx = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.bus_idx_red = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.sys_par = sys_par  # {'s_n': 0, 'f_n': 50, 'bus_v_n': None}

data instance-attribute

data = data

par instance-attribute

par = data

n_units instance-attribute

n_units = len(data)

bus_idx instance-attribute

bus_idx = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

bus_idx_red instance-attribute

bus_idx_red = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

sys_par instance-attribute

sys_par = sys_par

input_list

input_list()
Source code in src/tops/dyn_models/loads.py
def input_list(self):
    return ['g_setp', 'b_setp']

bus_ref_spec

bus_ref_spec()
Source code in src/tops/dyn_models/loads.py
def bus_ref_spec(self):
    return {'terminal': self.par['bus']}

reduced_system

reduced_system()
Source code in src/tops/dyn_models/loads.py
def reduced_system(self):
    return self.par['bus']

load_flow_pq

load_flow_pq()
Source code in src/tops/dyn_models/loads.py
def load_flow_pq(self):
    return self.bus_idx['terminal'], self.par['P'], self.par['Q']

init_from_load_flow

init_from_load_flow(x_0, v_0, S)
Source code in src/tops/dyn_models/loads.py
def init_from_load_flow(self, x_0, v_0, S):
    self.v_0 = v_0[self.bus_idx['terminal']]
    s_load = (self.par['P'] + 1j * self.par['Q']) / self.sys_par['s_n']
    y_load = np.conj(s_load)/abs(self.v_0)**2  # y = 0 for a load of zero power
    self._input_values['g_setp'] = y_load.real
    self._input_values['b_setp'] = y_load.imag

    V_n = self.sys_par['bus_v_n'][self.bus_idx['terminal']]
    self.I_n = self.sys_par['s_n']/(np.sqrt(3)*V_n)

g_load

g_load(x, v)
Source code in src/tops/dyn_models/loads.py
def g_load(self, x, v):
    return self.g_setp(x, v)

b_load

b_load(x, v)
Source code in src/tops/dyn_models/loads.py
def b_load(self, x, v):
    return self.b_setp(x, v)

y_load

y_load(x, v)
Source code in src/tops/dyn_models/loads.py
def y_load(self, x, v):
    return self.g_load(x, v) + 1j*self.b_load(x, v)

dyn_var_adm

dyn_var_adm(x, v)
Source code in src/tops/dyn_models/loads.py
def dyn_var_adm(self, x, v):
    return self.y_load(x, v), (self.bus_idx_red['terminal'],)*2

i

i(x, v)
Source code in src/tops/dyn_models/loads.py
def i(self, x, v):
    return v[self.bus_idx_red['terminal']]*self.y_load(x, v)

I

I(x, v)
Source code in src/tops/dyn_models/loads.py
def I(self, x, v):
    return self.i(x, v)*self.I_n

s

s(x, v)
Source code in src/tops/dyn_models/loads.py
def s(self, x, v):
    return v[self.bus_idx_red['terminal']]*np.conj(self.i(x, v))

p

p(x, v)
Source code in src/tops/dyn_models/loads.py
def p(self, x, v):
    # p.u. system base
    return self.s(x, v).real

q

q(x, v)
Source code in src/tops/dyn_models/loads.py
def q(self, x, v):
    # p.u. system base
    return self.s(x, v).imag

P

P(x, v)
Source code in src/tops/dyn_models/loads.py
def P(self, x, v):
    # MW
    return self.s(x, v).real*self.sys_par['s_n']

Q

Q(x, v)
Source code in src/tops/dyn_models/loads.py
def Q(self, x, v):
    # MVA
    return self.s(x, v).imag*self.sys_par['s_n']

DynamicLoadFiltered

DynamicLoadFiltered(data, sys_par, **kwargs)

Bases: DynamicLoad

Dynamic load where the input is filtered using a low pass filter.

The load is an admittance which is determined by the output of two low pass filters, one for G (conductance) and one for B (susceptance).

Source code in src/tops/dyn_models/loads.py
def __init__(self, data, sys_par, **kwargs):
    super().__init__(data, sys_par, **kwargs)
    self.data = data
    self.par = data
    self.n_units = len(data)

    self.bus_idx = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.bus_idx_red = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.sys_par = sys_par  # {'s_n': 0, 'f_n': 50, 'bus_v_n': None}

add_blocks

add_blocks()
Source code in src/tops/dyn_models/loads.py
def add_blocks(self):
    p = self.par
    self.lpf_g = TimeConstant(T=p['T_g'])
    self.lpf_g.input = lambda x, v: self.g_setp(x, v)

    self.lpf_b = TimeConstant(T=p['T_b'])
    self.lpf_b.input = lambda x, v: self.b_setp(x, v)

g_load

g_load(x, v)
Source code in src/tops/dyn_models/loads.py
def g_load(self, x, v):
    return self.lpf_g.output(x, v)

b_load

b_load(x, v)
Source code in src/tops/dyn_models/loads.py
def b_load(self, x, v):
    return self.lpf_b.output(x, v)

init_from_load_flow

init_from_load_flow(x_0, v_0, S)
Source code in src/tops/dyn_models/loads.py
def init_from_load_flow(self, x_0, v_0, S):
    self.v_0 = v_0[self.bus_idx['terminal']]
    s_load = (self.par['P'] + 1j * self.par['Q']) / self.sys_par['s_n']
    y_load = np.conj(s_load)/abs(self.v_0)**2  # y = 0 for a load of zero power
    self._input_values['g_setp'] = y_load.real
    self._input_values['b_setp'] = y_load.imag

    self.lpf_g.initialize(x_0, v_0, y_load.real)
    self.lpf_b.initialize(x_0, v_0, y_load.imag)

    V_n = self.sys_par['bus_v_n'][self.bus_idx['terminal']]
    self.I_n = self.sys_par['s_n']/(np.sqrt(3)*V_n)

ConstPowerLoad

ConstPowerLoad(data, sys_par, **kwargs)

Bases: DAEModel

Source code in src/tops/dyn_models/loads.py
def __init__(self, data, sys_par, **kwargs):
    super().__init__(data, sys_par, **kwargs)
    self.data = data
    self.par = data
    self.n_units = len(data)

    self.bus_idx = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.bus_idx_red = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.sys_par = sys_par  # {'s_n': 0, 'f_n': 50, 'bus_v_n': None}

events_class class-attribute instance-attribute

events_class = LoadEvents

data instance-attribute

data = data

par instance-attribute

par = data

n_units instance-attribute

n_units = len(data)

bus_idx instance-attribute

bus_idx = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

bus_idx_red instance-attribute

bus_idx_red = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

sys_par instance-attribute

sys_par = sys_par

bus_ref_spec

bus_ref_spec()
Source code in src/tops/dyn_models/loads.py
def bus_ref_spec(self):
    return {'terminal': self.par['bus']}

reduced_system

reduced_system()
Source code in src/tops/dyn_models/loads.py
def reduced_system(self):
    return self.par['bus']

load_flow_pq

load_flow_pq()
Source code in src/tops/dyn_models/loads.py
def load_flow_pq(self):
    return self.bus_idx['terminal'], self.par['P'], self.par['Q']

power_change

power_change(load_idx, P=None, Q=None)

Set the power of a load in MW and Mvar (None keeps it). The power is read at every step, so there is no change of the admittance matrix to return.

Source code in src/tops/dyn_models/loads.py
def power_change(self, load_idx, P=None, Q=None):
    """Set the power of a load in MW and Mvar (None keeps it). The power is read at every step, so there is no
    change of the admittance matrix to return."""
    write_power(self, load_idx, P, Q)

apparent_power_injections

apparent_power_injections(x, v)
Source code in src/tops/dyn_models/loads.py
def apparent_power_injections(self, x, v):
    s_inj = -(self.par['P'] + 1j*self.par['Q'])/self.sys_par['s_n']
    return self.bus_idx_red['terminal'], s_inj

read_power

read_power(column, value)

A power in MW or Mvar given to set_power, as a finite float.

Source code in src/tops/dyn_models/loads.py
def read_power(column, value):
    """A power in MW or Mvar given to set_power, as a finite float."""
    try:
        number = float(value)
    except (TypeError, ValueError):
        number = np.nan
    if not np.isfinite(number):
        raise ValueError(f'{column} must be a finite number, got {value!r}.')
    return number

float_power_columns

float_power_columns(par)

The load table with float P and Q, as set_power must not truncate the integer columns a table may have.

Source code in src/tops/dyn_models/loads.py
def float_power_columns(par):
    """The load table with float P and Q, as set_power must not truncate the integer columns a table may have."""
    if par['P'].dtype.kind == 'f' and par['Q'].dtype.kind == 'f':
        return par
    dtype = [(name, float if name in ('P', 'Q') else par.dtype[name]) for name in par.dtype.names]
    return par.astype(dtype)

write_power

write_power(mdl, load_idx, P, Q)

Write the power of a load, in MW and Mvar (None keeps it), to the table of its model.

Nothing is changed if a value is refused, or if the bus of the load is not in the reduced system. Returns False if the power is as it was.

Source code in src/tops/dyn_models/loads.py
def write_power(mdl, load_idx, P, Q):
    """Write the power of a load, in MW and Mvar (None keeps it), to the table of its model.

    Nothing is changed if a value is refused, or if the bus of the load is not in the reduced system.
    Returns False if the power is as it was.
    """
    if mdl.bus_idx_red['terminal'][load_idx] < 0:
        raise ValueError(f'Bus of load {mdl.par["name"][load_idx]} is not in the reduced system.')
    p = mdl.par['P'][load_idx] if P is None else read_power('P', P)
    q = mdl.par['Q'][load_idx] if Q is None else read_power('Q', Q)
    if p == mdl.par['P'][load_idx] and q == mdl.par['Q'][load_idx]:
        return False

    mdl.par = mdl.data = float_power_columns(mdl.par)
    mdl.par['P'][load_idx] = p
    mdl.par['Q'][load_idx] = q
    return True

lines

LineEvents

LineEvents(mdl)

Bases: ModelEvents

Source code in src/tops/events.py
def __init__(self, mdl):
    self.mdl = mdl

actions class-attribute instance-attribute

actions = ('connect', 'disconnect')

connect

connect(line_name)
Source code in src/tops/dyn_models/lines.py
def connect(self, line_name):
    idx = self._unit_idx(line_name)
    if self.mdl.connected[idx]:
        return []
    self.mdl.connected[idx] = True
    return [self.mdl.admittance_change(idx, sign=1)]

disconnect

disconnect(line_name)
Source code in src/tops/dyn_models/lines.py
def disconnect(self, line_name):
    idx = self._unit_idx(line_name)
    if not self.mdl.connected[idx]:
        return []
    self.mdl.connected[idx] = False
    return [self.mdl.admittance_change(idx, sign=-1)]

Line

Line(data, sys_par, **kwargs)

Bases: DAEModel

Source code in src/tops/dyn_models/lines.py
def __init__(self, data, sys_par, **kwargs):
    super().__init__(data, sys_par, **kwargs)
    self.data = data
    self.par = data
    self.n_units = len(data)
    self.connected = read_connected(data)

    self.bus_idx = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.bus_idx_red = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.sys_par = sys_par  # {'s_n': 0, 'f_n': 50, n_bus: None, 'bus_v_n': None}

events_class class-attribute instance-attribute

events_class = LineEvents

data instance-attribute

data = data

par instance-attribute

par = data

n_units instance-attribute

n_units = len(data)

connected instance-attribute

connected = read_connected(data)

bus_idx instance-attribute

bus_idx = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

bus_idx_red instance-attribute

bus_idx_red = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

sys_par instance-attribute

sys_par = sys_par

bus_ref_spec

bus_ref_spec()
Source code in src/tops/dyn_models/lines.py
def bus_ref_spec(self):
    return {'from_bus': self.par['from_bus'], 'to_bus': self.par['to_bus']}

event

event(ps, line_name, event_name)

Apply a line event directly (connect/disconnect). Kept for backwards compatibility, see LineEvents.

Source code in src/tops/dyn_models/lines.py
def event(self, ps, line_name, event_name):
    """Apply a line event directly (connect/disconnect). Kept for backwards compatibility, see LineEvents."""
    for effect in self.events.apply(line_name, event_name):
        ps.apply_effect(effect)

admittance_change

admittance_change(line_idx, sign)

Change in the reduced admittance matrix when connecting (sign=1) or disconnecting (sign=-1) a line.

Source code in src/tops/dyn_models/lines.py
def admittance_change(self, line_idx, sign):
    """Change in the reduced admittance matrix when connecting (sign=1) or disconnecting (sign=-1) a line."""
    idx_from = self.bus_idx_red['from_bus'][line_idx]
    idx_to = self.bus_idx_red['to_bus'][line_idx]
    if idx_from < 0 or idx_to < 0:
        raise ValueError(f'Buses of line {self.par["name"][line_idx]} are not in the reduced system.')

    admittance = self.admittance[line_idx]
    shunt = self.shunt[line_idx]
    data = sign*np.array([admittance + shunt/2, admittance + shunt/2, -admittance, -admittance])
    rows = np.array([idx_from, idx_to, idx_from, idx_to])
    cols = np.array([idx_from, idx_to, idx_to, idx_from])
    return AdmittanceChange(data, rows, cols)

init_extras

init_extras()
Source code in src/tops/dyn_models/lines.py
def init_extras(self):
    self.idx_from = self.bus_idx_red['from_bus']
    self.idx_to = self.bus_idx_red['to_bus']
    n_bus = self.sys_par['n_bus']

    self.v_to_i = np.zeros((self.n_units, n_bus), dtype=complex)
    self.v_to_i_rev = np.zeros((self.n_units, n_bus), dtype=complex)
    for i in range(self.n_units):
        self.v_to_i[i, [self.idx_from[i], self.idx_to[i]]] = [self.admittance[i] + self.shunt[i]/2, -self.admittance[i]]
        self.v_to_i_rev[i, [self.idx_to[i], self.idx_from[i]]] = [self.admittance[i] + self.shunt[i]/2, -self.admittance[i]]

load_flow_adm

load_flow_adm()
Source code in src/tops/dyn_models/lines.py
def load_flow_adm(self):
    z_n = self.sys_par['bus_v_n'] ** 2 / self.sys_par['s_n']

    V_n_from = self.sys_par['bus_v_n'][self.bus_idx['from_bus']]
    self.I_n = self.sys_par['s_n']/(np.sqrt(3)*V_n_from)


    data = self.data
    self.shunt = np.zeros(self.n_units, dtype=complex)
    self.admittance = np.zeros(self.n_units, dtype=complex)
    lengths = data['length'] if 'length' in data.dtype.names else np.ones(self.n_units)
    for i, line in enumerate(data):
        idx_from = self.bus_idx['from_bus'][i]
        idx_to = self.bus_idx['to_bus'][i]
        length = lengths[i]
        if 'unit' not in line.dtype.names or line['unit'] in ['p.u.', 'pu', 'pu/km']:
            if 'S_n' in line.dtype.names and 'V_n' in line.dtype.names and line['S_n'] != 0 and line['V_n'] != 0:
                # If impedance given in p.u./km
                impedance = (line['R'] + 1j * line['X']) * length * line['V_n'] ** 2 / line['S_n'] / \
                            z_n[idx_from]
                shunt = 1j * line['B'] * length * 1 / (
                        line['V_n'] ** 2 / line['S_n'] / z_n[idx_from])
            else:
                # Per unit of system base and bus nominal voltage
                impedance = (line['R'] + 1j * line['X']) * length
                shunt = 1j * line['B'] * length
        elif line['unit'] in ['PF', 'pf', 'PowerFactory', 'powerfactory']:
            # Given in ohm/km, but with capacitance in micro-Siemens
            impedance = (line['R'] + 1j * line['X']) * length / z_n[idx_from]
            shunt = 1j * line['B'] * length * z_n[idx_from] * 1e-6
        elif line['unit'] in ['Ohm', 'ohm']:
            # Given in Ohm/km
            impedance = (line['R'] + 1j * line['X']) * length / z_n[idx_from]
            shunt = 1j * line['B'] * length * z_n[idx_from]
        admittance = 1 / impedance
        self.admittance[i] = admittance
        self.shunt[i] = shunt

    idx_from = self.bus_idx['from_bus']
    idx_to = self.bus_idx['to_bus']

    rows = np.array([idx_from, idx_to, idx_from, idx_to])
    cols = np.array([idx_from, idx_to, idx_to, idx_from])
    data = np.array([
        self.admittance + self.shunt/2,
        self.admittance + self.shunt/2,
        -self.admittance,
        -self.admittance
    ])*self.connected  # admittance and shunt stay set for lines out of service, so that connect can stamp them

    self.init_extras()

    return data, (rows, cols)

dyn_const_adm

dyn_const_adm()
Source code in src/tops/dyn_models/lines.py
def dyn_const_adm(self):
    return self.load_flow_adm()

i_from

i_from(x, v)
Source code in src/tops/dyn_models/lines.py
def i_from(self, x, v):
    # Current in p.u.
    v_full = v
    return self.v_to_i.dot(v_full)*self.connected

i_to

i_to(x, v)
Source code in src/tops/dyn_models/lines.py
def i_to(self, x, v):
    # Current in p.u.
    v_full = v
    return self.v_to_i_rev.dot(v_full)*self.connected

I_from

I_from(x, v)
Source code in src/tops/dyn_models/lines.py
def I_from(self, x, v):
    # Current in kA
    return self.i_from(x, v)*self.I_n

I_to

I_to(x, v)
Source code in src/tops/dyn_models/lines.py
def I_to(self, x, v):
    # Current in kA
    return self.i_to(x, v)*self.I_n

s_from

s_from(x, v)
Source code in src/tops/dyn_models/lines.py
def s_from(self, x, v):
    v_full = v
    return v_full[self.idx_from]*np.conj(self.i_from(x, v))

s_to

s_to(x, v)
Source code in src/tops/dyn_models/lines.py
def s_to(self, x, v):
    v_full = v
    return v_full[self.idx_to]*np.conj(self.i_to(x, v))

p_from

p_from(x, v)
Source code in src/tops/dyn_models/lines.py
def p_from(self, x, v):
    return self.s_from(x, v).real

p_to

p_to(x, v)
Source code in src/tops/dyn_models/lines.py
def p_to(self, x, v):
    return self.s_to(x, v).real

q_from

q_from(x, v)
Source code in src/tops/dyn_models/lines.py
def q_from(self, x, v):
    return self.s_from(x, v).imag

q_to

q_to(x, v)
Source code in src/tops/dyn_models/lines.py
def q_to(self, x, v):
    return self.s_to(x, v).imag

s_line

s_line(x, v)
Source code in src/tops/dyn_models/lines.py
def s_line(self, x, v):
    return self.s_from(x, v) + self.s_to(x, v)

p_line

p_line(x, v)
Source code in src/tops/dyn_models/lines.py
def p_line(self, x, v):
    return self.s_line(x, v).real

q_line

q_line(x, v)
Source code in src/tops/dyn_models/lines.py
def q_line(self, x, v):
    return self.s_line(x, v).imag

p_loss_tot

p_loss_tot(x, v)
Source code in src/tops/dyn_models/lines.py
def p_loss_tot(self, x, v):
    return np.sum(np.abs(self.p_line(x, v)))

switches

Switches (breakers, disconnectors): ideal connections between two buses, modelled as a very high admittance.

SwitchEvents

SwitchEvents(mdl)

Bases: ModelEvents

Source code in src/tops/events.py
def __init__(self, mdl):
    self.mdl = mdl

actions class-attribute instance-attribute

actions = ('open', 'close')

close

close(switch_name)
Source code in src/tops/dyn_models/switches.py
def close(self, switch_name):
    idx = self._unit_idx(switch_name)
    if self.mdl.connected[idx]:
        return []
    self.mdl.connected[idx] = True
    return [self.mdl.admittance_change(idx, sign=1)]

open

open(switch_name)
Source code in src/tops/dyn_models/switches.py
def open(self, switch_name):
    idx = self._unit_idx(switch_name)
    if not self.mdl.connected[idx]:
        return []
    self.mdl.connected[idx] = False
    return [self.mdl.admittance_change(idx, sign=-1)]

Switch

Switch(data, sys_par, **kwargs)

Bases: DAEModel

Switch between two buses.

A closed switch is a series admittance y (pu on system base, default :attr:y_closed), large enough that the voltage across it is negligible. An open switch is removed from the network.

Parameters (table columns): name, from_bus, to_bus, and optionally closed (initial state, boolean or 1/0, default closed) and y (admittance when closed, pu on system base). The state is kept in connected, like for lines and transformers.

Source code in src/tops/dyn_models/switches.py
def __init__(self, data, sys_par, **kwargs):
    super().__init__(data, sys_par, **kwargs)
    self.par = data
    self.n_units = len(data)
    names = data.dtype.names
    self.connected = read_connected(data, column="closed")  # True when the switch is closed
    self.admittance = data["y"].astype(complex) if "y" in names else np.full(self.n_units, self.y_closed, complex)

    self.bus_idx = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.bus_idx_red = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.sys_par = sys_par

events_class class-attribute instance-attribute

events_class = SwitchEvents

y_closed class-attribute instance-attribute

y_closed = 100000.0

par instance-attribute

par = data

n_units instance-attribute

n_units = len(data)

connected instance-attribute

connected = read_connected(data, column='closed')

admittance instance-attribute

admittance = (
    data["y"].astype(complex)
    if "y" in names
    else np.full(self.n_units, self.y_closed, complex)
)

bus_idx instance-attribute

bus_idx = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

bus_idx_red instance-attribute

bus_idx_red = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

sys_par instance-attribute

sys_par = sys_par

bus_ref_spec

bus_ref_spec()
Source code in src/tops/dyn_models/switches.py
def bus_ref_spec(self):
    return {"from_bus": self.par["from_bus"], "to_bus": self.par["to_bus"]}

admittance_change

admittance_change(idx, sign)

Change in the reduced admittance matrix when closing (sign=1) or opening (sign=-1) a switch.

Source code in src/tops/dyn_models/switches.py
def admittance_change(self, idx, sign):
    """Change in the reduced admittance matrix when closing (sign=1) or opening (sign=-1) a switch."""
    idx_from = self.bus_idx_red["from_bus"][idx]
    idx_to = self.bus_idx_red["to_bus"][idx]
    if idx_from < 0 or idx_to < 0:
        raise ValueError(f"Buses of switch {self.par['name'][idx]} are not in the reduced system.")

    y = self.admittance[idx]
    data = sign * np.array([y, y, -y, -y])
    rows = np.array([idx_from, idx_to, idx_from, idx_to])
    cols = np.array([idx_from, idx_to, idx_to, idx_from])
    return AdmittanceChange(data, rows, cols)

load_flow_adm

load_flow_adm()
Source code in src/tops/dyn_models/switches.py
def load_flow_adm(self):
    V_n_from = self.sys_par["bus_v_n"][self.bus_idx["from_bus"]]
    self.I_n = self.sys_par["s_n"] / (np.sqrt(3) * V_n_from)

    idx_from = self.bus_idx["from_bus"]
    idx_to = self.bus_idx["to_bus"]
    y = self.admittance * self.connected
    rows = np.array([idx_from, idx_to, idx_from, idx_to])
    cols = np.array([idx_from, idx_to, idx_to, idx_from])
    data = np.array([y, y, -y, -y])
    return data, (rows, cols)

dyn_const_adm

dyn_const_adm()
Source code in src/tops/dyn_models/switches.py
def dyn_const_adm(self):
    return self.load_flow_adm()

i_from

i_from(x, v)
Source code in src/tops/dyn_models/switches.py
def i_from(self, x, v):
    # Current in p.u., flowing from from_bus into the switch
    idx_from = self.bus_idx_red["from_bus"]
    idx_to = self.bus_idx_red["to_bus"]
    return self.admittance * (v[idx_from] - v[idx_to]) * self.connected

i_to

i_to(x, v)
Source code in src/tops/dyn_models/switches.py
def i_to(self, x, v):
    return -self.i_from(x, v)

I_from

I_from(x, v)
Source code in src/tops/dyn_models/switches.py
def I_from(self, x, v):
    # Current in kA
    return self.i_from(x, v) * self.I_n

s_from

s_from(x, v)
Source code in src/tops/dyn_models/switches.py
def s_from(self, x, v):
    return v[self.bus_idx_red["from_bus"]] * np.conj(self.i_from(x, v))

s_to

s_to(x, v)
Source code in src/tops/dyn_models/switches.py
def s_to(self, x, v):
    return v[self.bus_idx_red["to_bus"]] * np.conj(self.i_to(x, v))

p_from

p_from(x, v)
Source code in src/tops/dyn_models/switches.py
def p_from(self, x, v):
    return self.s_from(x, v).real

q_from

q_from(x, v)
Source code in src/tops/dyn_models/switches.py
def q_from(self, x, v):
    return self.s_from(x, v).imag

p_to

p_to(x, v)
Source code in src/tops/dyn_models/switches.py
def p_to(self, x, v):
    return self.s_to(x, v).real

q_to

q_to(x, v)
Source code in src/tops/dyn_models/switches.py
def q_to(self, x, v):
    return self.s_to(x, v).imag

trafos

TrafoEvents

TrafoEvents(mdl)

Bases: ModelEvents

Source code in src/tops/events.py
def __init__(self, mdl):
    self.mdl = mdl

actions class-attribute instance-attribute

actions = ('connect', 'disconnect')

connect

connect(trafo_name)
Source code in src/tops/dyn_models/trafos.py
def connect(self, trafo_name):
    idx = self._unit_idx(trafo_name)
    if self.mdl.connected[idx]:
        return []
    change = self.mdl.admittance_change(idx, sign=1)
    self.mdl.connected[idx] = True
    return [] if change is None else [change]

disconnect

disconnect(trafo_name)
Source code in src/tops/dyn_models/trafos.py
def disconnect(self, trafo_name):
    idx = self._unit_idx(trafo_name)
    if not self.mdl.connected[idx]:
        return []
    change = self.mdl.admittance_change(idx, sign=-1)
    self.mdl.connected[idx] = False
    return [] if change is None else [change]

Trafo

Trafo(data, sys_par, **kwargs)

Bases: DAEModel

Source code in src/tops/dyn_models/trafos.py
def __init__(self, data, sys_par, **kwargs):
    super().__init__(data, sys_par, **kwargs)
    self.data = data
    self.par = data
    self.n_units = len(data)
    self.connected = read_connected(data)

    self.bus_idx = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.bus_idx_red = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.sys_par = sys_par  # {'s_n': 0, 'f_n': 50, 'bus_v_n': None}

events_class class-attribute instance-attribute

events_class = TrafoEvents

data instance-attribute

data = data

par instance-attribute

par = data

n_units instance-attribute

n_units = len(data)

connected instance-attribute

connected = read_connected(data)

bus_idx instance-attribute

bus_idx = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

bus_idx_red instance-attribute

bus_idx_red = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

sys_par instance-attribute

sys_par = sys_par

bus_ref_spec

bus_ref_spec()
Source code in src/tops/dyn_models/trafos.py
def bus_ref_spec(self):
    return {'from_bus': self.par['from_bus'], 'to_bus': self.par['to_bus']}

admittance_change

admittance_change(trafo_idx, sign)

Change in the reduced admittance matrix when connecting (sign=1) or disconnecting (sign=-1) a transformer.

Source code in src/tops/dyn_models/trafos.py
def admittance_change(self, trafo_idx, sign):
    """Change in the reduced admittance matrix when connecting (sign=1) or disconnecting (sign=-1) a transformer."""
    idx_from = self.bus_idx_red['from_bus'][trafo_idx]
    idx_to = self.bus_idx_red['to_bus'][trafo_idx]
    if idx_from < 0 or idx_to < 0:
        raise ValueError(f'Buses of transformer {self.par["name"][trafo_idx]} are not in the reduced system.')

    admittance = self.admittance[trafo_idx]
    ratio_from = self.ratio_from_0[trafo_idx]
    ratio_to = self.ratio_to_0[trafo_idx]
    data = sign*np.array([
        ratio_from*np.conj(ratio_from)*admittance,
        ratio_to*np.conj(ratio_to)*admittance,
        -ratio_from*np.conj(ratio_to)*admittance,
        -np.conj(ratio_from)*ratio_to*admittance
    ])
    rows = np.array([idx_from, idx_to, idx_from, idx_to])
    cols = np.array([idx_from, idx_to, idx_to, idx_from])
    return AdmittanceChange(data, rows, cols)

init_extras

init_extras()
Source code in src/tops/dyn_models/trafos.py
def init_extras(self):
    self.idx_from = self.bus_idx_red['from_bus']
    self.idx_to = self.bus_idx_red['to_bus']
    n_bus = self.sys_par['n_bus']

    # Trafos:
    n_elements = len(self.par)
    self.v_to_i = np.zeros((n_elements, n_bus), dtype=complex)
    self.v_to_i_rev = np.zeros((n_elements, n_bus), dtype=complex)

    for i in range(self.n_units):
        # This might not be correct for phase shifting transformers (conj in the right place?)
        shunt_from = self.ratio_from_0[i] * np.conj(self.ratio_from_0[i]) * self.admittance[i]
        shunt_to = self.ratio_to_0[i] * np.conj(self.ratio_to_0[i]) * self.admittance[i]
        adm_from_to = self.ratio_from_0[i] * np.conj(self.ratio_to_0[i]) * self.admittance[i]
        adm_to_from = np.conj(self.ratio_from_0[i]) * self.ratio_to_0[i] * self.admittance[i]

        self.v_to_i[i, [self.idx_from[i], self.idx_to[i]]] = [shunt_from, -adm_from_to]
        self.v_to_i_rev[i, [self.idx_to[i], self.idx_from[i]]] = [shunt_to, -adm_to_from]

load_flow_adm

load_flow_adm()
Source code in src/tops/dyn_models/trafos.py
def load_flow_adm(self):
    z_n = self.sys_par['bus_v_n'] ** 2 / self.sys_par['s_n']

    self.V_n_from = self.sys_par['bus_v_n'][self.bus_idx['from_bus']]
    self.I_n_from = self.sys_par['s_n']/(np.sqrt(3)*self.V_n_from)
    self.V_n_to = self.sys_par['bus_v_n'][self.bus_idx['to_bus']]
    self.I_n_to = self.sys_par['s_n']/(np.sqrt(3)*self.V_n_to)

    data = self.data
    self.admittance = np.zeros(self.n_units, dtype=complex)
    self.ratio_from_0 = np.zeros(self.n_units, dtype=complex)
    self.ratio_to_0 = np.zeros(self.n_units, dtype=complex)

    self.idx_from = idx_from = self.bus_idx['from_bus']  # dps_uf.lookup_strings(trafo['from_bus'], buses['name'])
    self.idx_to = idx_to = self.bus_idx['to_bus']  # dps_uf.lookup_strings(trafo['to_bus'], buses['name'])

    for i, trafo in enumerate(self.par):

        ratio_from = (trafo['ratio_from'] if not np.isnan(trafo['ratio_from']) else 1) if 'ratio_from' in trafo.dtype.names else 1
        ratio_to = (trafo['ratio_to'] if not np.isnan(trafo['ratio_to']) else 1) if 'ratio_to' in trafo.dtype.names else 1

        V_n_from = trafo['V_n_from'] if 'V_n_from' in trafo.dtype.names and trafo['V_n_from'] > 0 else self.sys_par['bus_v_n'][idx_from[i]]
        Z_base_trafo = V_n_from ** 2/(trafo['S_n'] if 'S_n' in trafo.dtype.names else self.sys_par['s_n'])  # <= Could also have used _to instead of _from
        impedance = (trafo['R']+1j*trafo['X'])*Z_base_trafo/z_n[idx_from[i]]
        n_par = trafo['N_par'] if 'N_par' in trafo.dtype.names else 1
        admittance = n_par/impedance

        self.admittance[i] = admittance
        self.ratio_from_0[i] = ratio_from
        self.ratio_to_0[i] = ratio_to

    rows = np.array([idx_from, idx_to, idx_from, idx_to])
    cols = np.array([idx_from, idx_to, idx_to, idx_from])
    data = np.array([
        self.ratio_from_0*np.conj(self.ratio_from_0)*self.admittance,
        self.ratio_to_0*np.conj(self.ratio_to_0)*self.admittance,
        -self.ratio_from_0*np.conj(self.ratio_to_0)*self.admittance,
        -np.conj(self.ratio_from_0)*self.ratio_to_0*self.admittance
    ])*self.connected  # admittance and ratios stay set for transformers out of service, so that connect can stamp them

    # self.init_extras()
    self.rows = rows
    self.cols = cols

    self.init_extras()

    return data, (self.rows, self.cols)

dyn_const_adm

dyn_const_adm()
Source code in src/tops/dyn_models/trafos.py
def dyn_const_adm(self):
    return self.load_flow_adm()

i_from

i_from(x, v)
Source code in src/tops/dyn_models/trafos.py
def i_from(self, x, v):
    # Current in p.u.
    v_full = v
    return self.v_to_i.dot(v_full)*self.connected

i_to

i_to(x, v)
Source code in src/tops/dyn_models/trafos.py
def i_to(self, x, v):
    # Current in p.u.
    v_full = v
    return self.v_to_i_rev.dot(v_full)*self.connected

I_from

I_from(x, v)
Source code in src/tops/dyn_models/trafos.py
def I_from(self, x, v):
    # Current in kA
    return self.i_from(x, v)*self.I_n_from

I_to

I_to(x, v)
Source code in src/tops/dyn_models/trafos.py
def I_to(self, x, v):
    # Current in kA
    return self.i_to(x, v)*self.I_n_to

s_from

s_from(x, v)
Source code in src/tops/dyn_models/trafos.py
def s_from(self, x, v):
    v_full = v
    return v_full[self.idx_from]*np.conj(self.i_from(x, v))

s_to

s_to(x, v)
Source code in src/tops/dyn_models/trafos.py
def s_to(self, x, v):
    v_full = v
    return v_full[self.idx_to]*np.conj(self.i_to(x, v))

p_from

p_from(x, v)
Source code in src/tops/dyn_models/trafos.py
def p_from(self, x, v):
    return self.s_from(x, v).real

p_to

p_to(x, v)
Source code in src/tops/dyn_models/trafos.py
def p_to(self, x, v):
    return self.s_to(x, v).real

q_from

q_from(x, v)
Source code in src/tops/dyn_models/trafos.py
def q_from(self, x, v):
    return self.s_from(x, v).imag

q_to

q_to(x, v)
Source code in src/tops/dyn_models/trafos.py
def q_to(self, x, v):
    return self.s_to(x, v).imag

s_line

s_line(x, v)
Source code in src/tops/dyn_models/trafos.py
def s_line(self, x, v):
    return self.s_from(x, v) + self.s_to(x, v)

p_line

p_line(x, v)
Source code in src/tops/dyn_models/trafos.py
def p_line(self, x, v):
    return self.s_line(x, v).real

q_line

q_line(x, v)
Source code in src/tops/dyn_models/trafos.py
def q_line(self, x, v):
    return self.s_line(x, v).imag

p_loss_tot

p_loss_tot(x, v)
Source code in src/tops/dyn_models/trafos.py
def p_loss_tot(self, x, v):
    return np.sum(np.abs(self.p_line(x, v)))

DynTrafo

DynTrafo(data, sys_par, **kwargs)

Bases: Trafo

Source code in src/tops/dyn_models/trafos.py
def __init__(self, data, sys_par, **kwargs):
    super().__init__(data, sys_par, **kwargs)
    self.data = data
    self.par = data
    self.n_units = len(data)
    self.connected = read_connected(data)

    self.bus_idx = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.bus_idx_red = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.sys_par = sys_par  # {'s_n': 0, 'f_n': 50, 'bus_v_n': None}

input_list

input_list()
Source code in src/tops/dyn_models/trafos.py
def input_list(self):
    return ['ratio_from', 'ratio_to']

load_flow_adm

load_flow_adm()
Source code in src/tops/dyn_models/trafos.py
def load_flow_adm(self):
    z_n = self.sys_par['bus_v_n'] ** 2 / self.sys_par['s_n']

    self.V_n_from = self.sys_par['bus_v_n'][self.bus_idx['from_bus']]
    self.I_n_from = self.sys_par['s_n']/(np.sqrt(3)*self.V_n_from)
    self.V_n_to = self.sys_par['bus_v_n'][self.bus_idx['to_bus']]
    self.I_n_to = self.sys_par['s_n']/(np.sqrt(3)*self.V_n_to)

    data = self.data
    self.admittance = np.zeros(self.n_units, dtype=complex)
    self.ratio_from_0 = self.par['ratio_from']
    self.ratio_to_0 = self.par['ratio_to']

    self.idx_from = idx_from = self.bus_idx['from_bus']
    self.idx_to = idx_to = self.bus_idx['to_bus']

    for i, trafo in enumerate(self.par):

        V_n_from = trafo['V_n_from'] if 'V_n_from' in trafo.dtype.names and trafo['V_n_from'] > 0 else self.sys_par['bus_v_n'][idx_from[i]]
        Z_base_trafo = V_n_from ** 2/(trafo['S_n'] if 'S_n' in trafo.dtype.names else self.sys_par['s_n'])  # <= Could also have used _to instead of _from
        impedance = (trafo['R']+1j*trafo['X'])*Z_base_trafo/z_n[idx_from[i]]
        n_par = trafo['N_par'] if 'N_par' in trafo.dtype.names else 1
        admittance = n_par/impedance
        self.admittance[i] = admittance

    rows = np.array([idx_from, idx_to, idx_from, idx_to])
    cols = np.array([idx_from, idx_to, idx_to, idx_from])
    data = np.array([
        self.ratio_from_0*np.conj(self.ratio_from_0)*self.admittance,
        self.ratio_to_0*np.conj(self.ratio_to_0)*self.admittance,
        -self.ratio_from_0*np.conj(self.ratio_to_0)*self.admittance,
        -np.conj(self.ratio_from_0)*self.ratio_to_0*self.admittance
    ])*self.connected

    self.rows = rows
    self.cols = cols

    return data, (self.rows, self.cols)

admittance_change

admittance_change(trafo_idx, sign)
Source code in src/tops/dyn_models/trafos.py
def admittance_change(self, trafo_idx, sign):
    # The stamp is rebuilt at every step from the ratios, in dyn_var_adm, which leaves out transformers out of service
    return None

init_from_load_flow

init_from_load_flow(x_0, v_0, S)
Source code in src/tops/dyn_models/trafos.py
def init_from_load_flow(self, x_0, v_0, S):
    self._input_values['ratio_from'] = self.ratio_from_0
    self._input_values['ratio_to'] = self.ratio_to_0

dyn_const_adm

dyn_const_adm()
Source code in src/tops/dyn_models/trafos.py
def dyn_const_adm(self):
    return np.zeros(0, dtype=complex), (np.zeros(0, dtype=int),)*2

dyn_var_adm

dyn_var_adm(x, v)
Source code in src/tops/dyn_models/trafos.py
def dyn_var_adm(self, x, v):
    ratio_from = self.ratio_from(x, v)
    ratio_to = self.ratio_to(x, v)
    data = np.array([
        ratio_from              *   np.conj(ratio_from) *   self.admittance,
        ratio_to                *   np.conj(ratio_to)   *   self.admittance,
        -ratio_from             *   np.conj(ratio_to)   *   self.admittance,
        -np.conj(ratio_from)    *   ratio_to            *   self.admittance
    ])*self.connected

    return data, (self.rows, self.cols)

i_from

i_from(x, v)
Source code in src/tops/dyn_models/trafos.py
def i_from(self, x, v):
    v_full = v
    v_from = v_full[self.idx_from]
    v_to = v_full[self.idx_to]

    shunt_from = self.ratio_from(x, v)*np.conj(self.ratio_from(x, v))*self.admittance
    adm_from_to = self.ratio_from(x, v)*np.conj(self.ratio_to(x, v))*self.admittance

    return (v_from*shunt_from - v_to*adm_from_to)*self.connected

i_to

i_to(x, v)
Source code in src/tops/dyn_models/trafos.py
def i_to(self, x, v):
    v_full = v
    v_from = v_full[self.idx_from]
    v_to = v_full[self.idx_to]

    shunt_to = self.ratio_to(x, v) * np.conj(self.ratio_to(x, v)) * self.admittance
    adm_to_from = np.conj(self.ratio_from(x, v)) * self.ratio_to(x, v) * self.admittance

    return (v_to*shunt_to - v_from*adm_to_from)*self.connected

shunts

Shunt

Shunt(data, sys_par, **kwargs)

Bases: DAEModel

Source code in src/tops/dyn_models/shunts.py
def __init__(self, data, sys_par, **kwargs):
    super().__init__(data, sys_par, **kwargs)
    self.data = data
    self.par = data
    self.n_units = len(data)

    self.bus_idx = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.bus_idx_red = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.sys_par = sys_par  # {'s_n': 0, 'f_n': 50, 'bus_v_n': None}

data instance-attribute

data = data

par instance-attribute

par = data

n_units instance-attribute

n_units = len(data)

bus_idx instance-attribute

bus_idx = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

bus_idx_red instance-attribute

bus_idx_red = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

sys_par instance-attribute

sys_par = sys_par

bus_ref_spec

bus_ref_spec()
Source code in src/tops/dyn_models/shunts.py
def bus_ref_spec(self):
    return {'terminal': self.par['bus']}

reduced_system

reduced_system()
Source code in src/tops/dyn_models/shunts.py
def reduced_system(self):
    return self.par['bus']

load_flow_adm

load_flow_adm()
Source code in src/tops/dyn_models/shunts.py
def load_flow_adm(self):
    s_shunt = -1j * self.par['Q'] / self.sys_par['s_n']
    z = np.conj(abs(1) ** 2 / s_shunt)
    y_shunt = 1 / z
    return y_shunt, (self.bus_idx['terminal'],) * 2

dyn_const_adm

dyn_const_adm()
Source code in src/tops/dyn_models/shunts.py
def dyn_const_adm(self):
    return self.load_flow_adm()

vsc

VSC

VSC(*args, **kwargs)

Bases: DAEModel

Grid-following voltage source converter, modelled as a controlled current source.

The active and reactive power injected at the terminal bus are measured and controlled by PI regulators. The outputs of the regulators, filtered by the time constant T_i, give the d- and q-axis currents, which are aligned with the voltage angle estimated by a PLL (PLL1).

Quantities are in physical units, not per unit: power in MW and Mvar, current in kA and voltage in kV. The gains of the regulators are thus in kA/MW (kA/Mvar).

Parameters (columns in the model dict):

  • bus: Terminal bus.
  • T_pll: Time constant of the PLL angle filter [s].
  • T_i: Time constant of the current response [s].
  • P_K_p, P_K_i: Proportional and integral gain of the active power regulator.
  • Q_K_p, Q_K_i: Proportional and integral gain of the reactive power regulator.
  • P_setp, Q_setp: Initial active [MW] and reactive [Mvar] power setpoints. Positive values are injected into the grid. The setpoints are inputs, which can be changed during the simulation with set_input.
Source code in src/tops/dyn_models/vsc.py
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

    self.bus_idx = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.bus_idx_red = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])

bus_idx instance-attribute

bus_idx = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

bus_idx_red instance-attribute

bus_idx_red = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

bus_ref_spec

bus_ref_spec()
Source code in src/tops/dyn_models/vsc.py
def bus_ref_spec(self):
    return {"terminal": self.par["bus"]}

add_blocks

add_blocks()
Source code in src/tops/dyn_models/vsc.py
def add_blocks(self):
    p = self.par
    self.pll = PLL1(T_filter=self.par["T_pll"], bus=p["bus"])

    self.pi_p = PIRegulator(K_p=p["P_K_p"], K_i=p["P_K_i"])
    self.pi_p.input = lambda x, v: self.P_setp(x, v) - self.P(x, v)

    self.pi_q = PIRegulator(K_p=p["Q_K_p"], K_i=p["Q_K_i"])
    self.pi_q.input = lambda x, v: self.Q_setp(x, v) - self.Q(x, v)

    self.lag_p = TimeConstant(T=p["T_i"])
    self.lag_p.input = self.pi_p.output
    self.lag_q = TimeConstant(T=p["T_i"])
    self.lag_q.input = self.pi_q.output

    self.I_d = self.lag_p.output
    self.I_q = self.lag_q.output

I_inj

I_inj(x, v)
Source code in src/tops/dyn_models/vsc.py
def I_inj(self, x, v):
    return (self.I_d(x, v) - 1j * self.I_q(x, v)) * np.exp(1j * self.pll.output(x, v))

input_list

input_list()
Source code in src/tops/dyn_models/vsc.py
def input_list(self):
    return ["P_setp", "Q_setp"]

S

S(x, v)

Complex power [MVA] injected into the terminal bus.

Source code in src/tops/dyn_models/vsc.py
def S(self, x, v):
    """Complex power [MVA] injected into the terminal bus."""
    v_n = self.sys_par["bus_v_n"][self.bus_idx_red["terminal"]]
    V = v[self.bus_idx_red["terminal"]] * v_n
    return np.sqrt(3) * V * np.conj(self.I_inj(x, v))

P

P(x, v)

Active power [MW] injected into the terminal bus.

Source code in src/tops/dyn_models/vsc.py
def P(self, x, v):
    """Active power [MW] injected into the terminal bus."""
    return self.S(x, v).real

Q

Q(x, v)

Reactive power [Mvar] injected into the terminal bus.

Source code in src/tops/dyn_models/vsc.py
def Q(self, x, v):
    """Reactive power [Mvar] injected into the terminal bus."""
    return self.S(x, v).imag

load_flow_pq

load_flow_pq()
Source code in src/tops/dyn_models/vsc.py
def load_flow_pq(self):
    return self.bus_idx["terminal"], -self.par["P_setp"], -self.par["Q_setp"]

init_from_load_flow

init_from_load_flow(x_0, v_0, S)
Source code in src/tops/dyn_models/vsc.py
def init_from_load_flow(self, x_0, v_0, S):
    self._input_values["P_setp"] = self.par["P_setp"]
    self._input_values["Q_setp"] = self.par["Q_setp"]

    v_n = self.sys_par["bus_v_n"][self.bus_idx_red["terminal"]]

    V_0 = v_0[self.bus_idx_red["terminal"]] * v_n

    I_d_0 = self.par["P_setp"] / (abs(V_0) * np.sqrt(3))
    I_q_0 = self.par["Q_setp"] / (abs(V_0) * np.sqrt(3))

    self.pi_p.initialize(x_0, v_0, self.lag_p.initialize(x_0, v_0, I_d_0))

    self.pi_q.initialize(x_0, v_0, self.lag_q.initialize(x_0, v_0, I_q_0))

current_injections

current_injections(x, v)
Source code in src/tops/dyn_models/vsc.py
def current_injections(self, x, v):
    i_n = self.sys_par["s_n"] / (np.sqrt(3) * self.sys_par["bus_v_n"])
    return self.bus_idx_red["terminal"], self.I_inj(x, v) / i_n[self.bus_idx_red["terminal"]]

pll

PLL1

PLL1(*args, **kwargs)

Bases: DAEModel

Source code in src/tops/dyn_models/pll.py
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

    self.bus_idx = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.bus_idx_red = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])

bus_idx instance-attribute

bus_idx = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

bus_idx_red instance-attribute

bus_idx_red = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

bus_ref_spec

bus_ref_spec()
Source code in src/tops/dyn_models/pll.py
def bus_ref_spec(self):
    return {'terminal': self.par['bus']}

add_blocks

add_blocks()
Source code in src/tops/dyn_models/pll.py
def add_blocks(self):
    p = self.par
    self.filter = TimeConstant(T=p['T_filter'])

    def angle_measurement(x, v):
        v_terminal = v[self.bus_idx_red['terminal']]
        # A bus without voltage (dead bus) has no angle: the filter holds the value it has
        v_angle = np.where(abs(v_terminal) < 1e-9, self.output(x, v), np.angle(v_terminal))

        # np.unwrap(np.vstack([np.array([0, 3 * np.pi, 0]), np.array([0, np.pi + 1e-10 + 2 * np.pi, 0])]), axis=0)[1, :]
        return np.unwrap(np.vstack([self.output(x, v), v_angle]), axis=0)[1, :]

    # self.filter.input = lambda x, v: np.angle(v[self.bus_idx_red['terminal']])
    self.filter.input = angle_measurement
    self.output = lambda x, v: self.filter.output(x, v)

freq_est

freq_est(x, v)
Source code in src/tops/dyn_models/pll.py
def freq_est(self, x, v):
    X = self.filter.local_view(x)
    dX = 1/self.filter.par['T']*(self.filter.input(x, v) - X['x'])
    return dX/(2 * np.pi * self.sys_par['f_n'])

init_from_load_flow

init_from_load_flow(x_0, v_0, S)
Source code in src/tops/dyn_models/pll.py
def init_from_load_flow(self, x_0, v_0, S):
    output_value = np.angle(v_0[self.bus_idx_red['terminal']])
    self.filter.initialize(x_0, v_0, output_value)

PLL2

PLL2(*args, **kwargs)

Bases: PLL1

Source code in src/tops/dyn_models/pll.py
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

    self.bus_idx = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])
    self.bus_idx_red = np.array(np.zeros(self.n_units), dtype=[(key, int) for key in self.bus_ref_spec().keys()])

bus_idx instance-attribute

bus_idx = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

bus_idx_red instance-attribute

bus_idx_red = np.array(
    np.zeros(self.n_units),
    dtype=[
        (key, int) for key in self.bus_ref_spec().keys()
    ],
)

bus_ref_spec

bus_ref_spec()
Source code in src/tops/dyn_models/pll.py
def bus_ref_spec(self):
    return {'terminal': self.par['bus']}

add_blocks

add_blocks()
Source code in src/tops/dyn_models/pll.py
def add_blocks(self):
    p = self.par
    self.pi = PIRegulator(K_p=p['K_p'], K_i=p['K_i'])
    self.integrator = Integrator(n_units=self.n_units)

    self.v_measured = lambda x, v: v[self.bus_idx_red['terminal']]
    self.phi = self.integrator.output
    self.pi.input = lambda x, v: -self.v_measured(x, v).real*np.sin(self.phi(x, v)) + self.v_measured(x, v).imag*np.cos(self.phi(x, v))
    self.integrator.input = self.pi.output

    self.freq_est = lambda x, v: self.integrator.input(x, v)/(2 * np.pi * self.sys_par['f_n'])

    self.output = self.phi

init_from_load_flow

init_from_load_flow(x_0, v_0, S)
Source code in src/tops/dyn_models/pll.py
def init_from_load_flow(self, x_0, v_0, S):
    output_value = np.angle(v_0[self.bus_idx_red['terminal']])
    # self.pi.initialize(
    x_0, v_0, self.integrator.initialize(x_0, v_0, output_value)

utils

AlgebraicLoopError

Bases: RuntimeError

Raised when an output depends on itself without passing through a state.

DAEModel

DAEModel(
    par=None,
    sys_par=None,
    first_state_idx=0,
    n_units=None,
    **kwargs,
)

Base class for dynamic models.

Parameters are given in one of three ways: as a structured array (par), as keyword arguments with one array per parameter (e.g. Gain(K=k)), or as the number of units (n_units) for models without parameters.

Source code in src/tops/dyn_models/utils.py
def __init__(self, par=None, sys_par=None, first_state_idx=0, n_units=None, **kwargs):
    if hasattr(self, 'int_par_list'):
        raise TypeError(
            f'{type(self).__name__} defines int_par_list(), but int_par has been removed. '
            f'Add the parameters to input_list() instead, and set them in _input_values.'
        )

    given = [arg for arg, used in [('par', par is not None), ('n_units', n_units is not None),
                                   ('parameters as keyword arguments', bool(kwargs))] if used]
    if len(given) != 1:
        raise TypeError(
            f'{type(self).__name__}: give exactly one of par, n_units or parameters as keyword '
            f'arguments' + (f' (got {" and ".join(given)})' if given else '') + '.')

    if n_units is not None:
        self.par = dps_uf.structured_array_from_list(names=['name'], entries=[(type(self).__name__,)]*n_units)
    else:
        self.par = par if par is not None else self.parse_input_data(**kwargs)
    self.sys_par = sys_par  # Used by subclasses (e.g. s_n, f_n)

    self.n_units = len(self.par)
    self.n_states = len(self.state_list())
    self.idx = slice(first_state_idx, first_state_idx + self.n_states*self.n_units)  # This will be shifted from outside

    self.state_desc = np.vstack([
        np.repeat(self.par['name'], self.n_states),
        np.tile(self.state_list(), self.n_units)]
    ).T

    # States are ordered by unit, then by state: [unit_0 states, unit_1 states, ...]
    self.dtypes = [(state, float) for state in self.state_list()]
    self.state_idx = np.zeros((self.n_units,), dtype=[(state, int) for state in self.state_list()])
    self.state_idx_global = np.zeros((self.n_units,), dtype=[(state, int) for state in self.state_list()])
    for i, state in enumerate(self.state_list()):
        self.state_idx[state] = np.arange(self.n_units)*self.n_states + i
        self.state_idx_global[state] = self.state_idx[state] + first_state_idx

    self.add_blocks()
    self.update_block_names()

    self._stored_outputs = {}  # See output and store_outputs
    self._outputs_in_progress = set()
    self._input_values = np.zeros(self.n_units, dtype=[(var, float) for var in self.input_list()])
    self._store_output = False
    for input_name in self.input_list():
        self.disconnect_input(input_name)
    # After add_blocks, since outputs are often assigned there (e.g. self.output = lambda x, v: ...)
    for output_name in self.all_outputs():
        _wrap_output(self, output_name)

    self.events = self.events_class(self) if self.events_class is not None else None

events_class class-attribute instance-attribute

events_class = None

par instance-attribute

par = dps_uf.structured_array_from_list(
    names=["name"],
    entries=[(type(self).__name__,)] * n_units,
)

sys_par instance-attribute

sys_par = sys_par

n_units instance-attribute

n_units = len(self.par)

n_states instance-attribute

n_states = len(self.state_list())

idx instance-attribute

idx = slice(
    first_state_idx,
    first_state_idx + self.n_states * self.n_units,
)

state_desc instance-attribute

state_desc = np.vstack(
    [
        np.repeat(self.par["name"], self.n_states),
        np.tile(self.state_list(), self.n_units),
    ]
).T

dtypes instance-attribute

dtypes = [(state, float) for state in self.state_list()]

state_idx instance-attribute

state_idx = np.zeros(
    (self.n_units,),
    dtype=[(state, int) for state in self.state_list()],
)

state_idx_global instance-attribute

state_idx_global = np.zeros(
    (self.n_units,),
    dtype=[(state, int) for state in self.state_list()],
)

events instance-attribute

events = (
    self.events_class(self)
    if self.events_class is not None
    else None
)

int_par property

int_par

blocks property

blocks

Blocks (sub-models) of the model, by attribute name, in the order they were created.

state_list

state_list()

Returns list of states for dynamic model. Should be overwritten (if model has one or more states)

Source code in src/tops/dyn_models/utils.py
def state_list(self):
    """
    Returns list of states for dynamic model.
    Should be overwritten (if model has one or more states)
    """
    return []

input_list

input_list()

Returns list of inputs for dynamic model. Should be overwritten (if model has one or more inputs)

Source code in src/tops/dyn_models/utils.py
def input_list(self):
    """
    Returns list of inputs for dynamic model.
    Should be overwritten (if model has one or more inputs)
    """
    return []

output_list

output_list()

Returns list of outputs for dynamic model, i.e. names of functions f(x, v) of the model that other models connect to. Should be overwritten (if model has one or more outputs).

Within store_outputs, each listed output is computed once per evaluation and the stored value is returned on later calls. A listed output that depends on itself without passing through a state (an algebraic loop) raises AlgebraicLoopError. Outputs may be methods or functions assigned in add_blocks (e.g. self.output = lambda x, v: ...), but should not be reassigned after the model is created.

Source code in src/tops/dyn_models/utils.py
def output_list(self):
    """
    Returns list of outputs for dynamic model, i.e. names of functions f(x, v) of the model that
    other models connect to.
    Should be overwritten (if model has one or more outputs).

    Within ``store_outputs``, each listed output is computed once per evaluation and the stored
    value is returned on later calls. A listed output that depends on itself without passing
    through a state (an algebraic loop) raises AlgebraicLoopError. Outputs may be methods or
    functions assigned in ``add_blocks`` (e.g. ``self.output = lambda x, v: ...``), but should
    not be reassigned after the model is created.
    """
    return []

all_outputs

all_outputs()

Outputs listed by output_list() of the model's class and all its base classes. A mixin's list is thereby not hidden by another, e.g. for class MyAVR(DAEModel, AVR), where DAEModel.output_list() comes before AVR.output_list().

Source code in src/tops/dyn_models/utils.py
def all_outputs(self):
    """Outputs listed by ``output_list()`` of the model's class and all its base classes. A
    mixin's list is thereby not hidden by another, e.g. for ``class MyAVR(DAEModel, AVR)``,
    where ``DAEModel.output_list()`` comes before ``AVR.output_list()``."""
    names = {}
    for cls in type(self).__mro__:
        if 'output_list' in vars(cls):
            names.update(dict.fromkeys(cls.output_list(self)))
    return list(names)

reset_outputs

reset_outputs()
Source code in src/tops/dyn_models/utils.py
def reset_outputs(self):
    self._stored_outputs.clear()

set_input

set_input(input_name, value, idx=None)

Set the value of an input. Units where the input is connected to another model's output are not affected, since their value is given by the connection.

Source code in src/tops/dyn_models/utils.py
def set_input(self, input_name, value, idx=None):
    """Set the value of an input. Units where the input is connected to another model's output
    are not affected, since their value is given by the connection."""
    if idx is not None:
        self._input_values[input_name][idx] = value
    else:
        self._input_values[input_name] = value

disconnect_input

disconnect_input(input_name)

Make the input read its value from _input_values (set with set_input), replacing any connection. Set on the instance, so that other instances and the class are not affected.

Source code in src/tops/dyn_models/utils.py
def disconnect_input(self, input_name):
    """Make the input read its value from _input_values (set with set_input), replacing any
    connection. Set on the instance, so that other instances and the class are not affected."""
    setattr(self, input_name, functools.partial(self._read_input, input_name))

add_blocks

add_blocks()

Create blocks (sub-models) by assigning them to attributes, e.g. self.gain = Gain(...). Should be overwritten (if model has blocks).

Source code in src/tops/dyn_models/utils.py
def add_blocks(self):
    """Create blocks (sub-models) by assigning them to attributes, e.g. self.gain = Gain(...).
    Should be overwritten (if model has blocks)."""
    pass

update_block_names

update_block_names()

Name the blocks (recursively) after their attribute, e.g. 'AVR1/gain' or 'VSC1/pll/filter'.

Source code in src/tops/dyn_models/utils.py
def update_block_names(self):
    """Name the blocks (recursively) after their attribute, e.g. 'AVR1/gain' or 'VSC1/pll/filter'."""
    for attr, block in self.blocks.items():
        names = np.char.add(self.par['name'].astype(str), f'/{attr}')
        other_par = dps_uf.remove_recarray_field(block.par, 'name')
        block.par = dps_uf.combine_recarrays(np.array(names, dtype=[('name', names.dtype)]), other_par)
        if block.n_states > 0:
            block.state_desc = np.vstack([
                np.repeat(block.par['name'], block.n_states),
                np.tile(block.state_list(), block.n_units)]
            ).T
        block.update_block_names()

parse_input_data

parse_input_data(**kwargs)

Read parameters from kwargs, with one array (with one value per unit) per parameter.

Source code in src/tops/dyn_models/utils.py
def parse_input_data(self, **kwargs):
    """Read parameters from kwargs, with one array (with one value per unit) per parameter."""
    names = list(kwargs.keys())
    data = [np.asarray(val) for val in kwargs.values()]

    lengths = {name: len(col) if col.ndim == 1 else None for name, col in zip(names, data)}
    if None in lengths.values() or len(set(lengths.values())) != 1:
        raise ValueError(
            f'{type(self).__name__}: parameters must be 1D arrays of equal length (one value per '
            f'unit), got lengths ' + ', '.join(f'{k}={v if v is not None else "scalar/nD"}'
                                               for k, v in lengths.items()) + '.')

    if 'name' not in names:
        names.append('name')
        data.append(np.array([type(self).__name__]*len(data[0])))

    entries = [entry for entry in zip(*data)]
    col_dtypes = [np.array(col).dtype for col in data]
    dtypes = [(name_, dtype_) for name_, dtype_ in zip(names, col_dtypes)]

    return np.array(entries, dtype=dtypes)

local_view

local_view(x)
Source code in src/tops/dyn_models/utils.py
def local_view(self, x):
    return x[self.idx].view(dtype=self.dtypes)

output

output(x, v)
Source code in src/tops/dyn_models/utils.py
def output(self, x, v):
    raise NotImplementedError(f'{type(self).__name__} has no output.')

read_connected

read_connected(par, column='connected')

In-service flags of the branches of a model table; all connected if it has no such column.

Source code in src/tops/dyn_models/utils.py
def read_connected(par, column='connected'):
    """In-service flags of the branches of a model table; all connected if it has no such column."""
    name = column
    if name not in par.dtype.names:
        return np.ones(len(par), dtype=bool)
    column = par[name]
    if column.dtype.kind == 'b':
        return column.copy()
    if column.dtype.kind in 'iuf' and np.isin(column, (0, 1)).all():
        return column.astype(bool)
    raise ValueError(f"Column '{name}' must hold booleans (or 0 and 1), got {column.tolist()}.")

determine_connections

determine_connections(dyn_mdls, order_by='input')

Resolve the connections declared by each model's connections() method.

A connection is declared on one model (the local side) and points to models in another container (the remote side), either as a 'source' (remote output -> local input) or as a 'destination' (local output -> remote input). The 'id' list of the connection is aligned with the local model's units and is looked up among the remote models' names.

With order_by='input' the result is {dest_mdl: {input: [entry, ...]}} where each entry names the source model and output. With order_by='output' it is {source_mdl: {output: [entry, ...]}} where each entry names the destination model and input.

Source code in src/tops/dyn_models/utils.py
def determine_connections(dyn_mdls, order_by='input'):
    """Resolve the connections declared by each model's ``connections()`` method.

    A connection is declared on one model (the local side) and points to models in another
    container (the remote side), either as a ``'source'`` (remote output -> local input) or as a
    ``'destination'`` (local output -> remote input). The ``'id'`` list of the connection is aligned
    with the local model's units and is looked up among the remote models' names.

    With ``order_by='input'`` the result is ``{dest_mdl: {input: [entry, ...]}}`` where each entry
    names the source model and output. With ``order_by='output'`` it is
    ``{source_mdl: {output: [entry, ...]}}`` where each entry names the destination model and input.
    """
    if order_by not in ('input', 'output'):
        raise ValueError(f"order_by must be 'input' or 'output', got {order_by!r}")

    mdl_connections = {}
    for container_key, mdls in dyn_mdls.items():
        for mdl_key, mdl in mdls.items():
            if not hasattr(mdl, 'connections'):
                continue
            for conn in mdl.connections():
                for source, dest in _resolve_connection(dyn_mdls, container_key, mdl_key, mdl, conn):
                    if order_by == 'input':
                        key_mdl, key_var = dest.mdl, conn['input']
                        entry = {'container': source.container, 'mdl': source.key, 'output': conn['output']}
                    else:
                        key_mdl, key_var = source.mdl, conn['output']
                        entry = {'container': dest.container, 'mdl': dest.key, 'input': conn['input']}
                    entry.update(source_idx=source.idx, dest_idx=dest.idx)
                    mdl_connections.setdefault(key_mdl, {}).setdefault(key_var, []).append(entry)

    return mdl_connections

get_submodules

get_submodules(mdl)

Return mdl followed by all its blocks (recursively), in the order they were created.

Source code in src/tops/dyn_models/utils.py
def get_submodules(mdl):
    """Return ``mdl`` followed by all its blocks (recursively), in the order they were created."""
    output = [mdl]
    for block in mdl.blocks.values():
        output.extend(get_submodules(block))
    return output

output

output(f)

Deprecated: list the output in the model's output_list() instead.

Outputs in output_list() are stored and checked for algebraic loops by DAEModel (see DAEModel.output_list). The decorator returns f unchanged.

Source code in src/tops/dyn_models/utils.py
def output(f):
    """Deprecated: list the output in the model's ``output_list()`` instead.

    Outputs in ``output_list()`` are stored and checked for algebraic loops by ``DAEModel`` (see
    ``DAEModel.output_list``). The decorator returns ``f`` unchanged.
    """
    warnings.warn(
        f'The @output decorator (on {f.__qualname__}) is deprecated and has no effect. List the '
        f'output in output_list() instead.', DeprecationWarning, stacklevel=2)
    return f

store_outputs

store_outputs(mdls)

Within the context, each output (in output_list) of the models is computed once and then stored. Should be entered for each evaluation, since stored outputs do not depend on (x, v).

Source code in src/tops/dyn_models/utils.py
@contextlib.contextmanager
def store_outputs(mdls):
    """Within the context, each output (in output_list) of the models is computed once and then
    stored. Should be entered for each evaluation, since stored outputs do not depend on (x, v)."""
    for mdl in mdls:
        mdl._stored_outputs.clear()
        mdl._store_output = True
    try:
        yield
    finally:
        for mdl in mdls:
            mdl._store_output = False
            mdl._stored_outputs.clear()

summation

summation(*funcs)

Creates a new function which sums the output of functions and constants/ constant arrays specified as arguments

Source code in src/tops/dyn_models/utils.py
def summation(*funcs):
    '''Creates a new function which sums the output of functions and constants/
    constant arrays specified as arguments
    '''
    callables = [func for func in funcs if callable(func)]
    constants = [func for func in funcs if not callable(func)]
    def summation(*args):
        return sum([func(*args) for func in callables] + constants)

    return summation

auto_init

auto_init(mdl, x0, v0, output_0, free_inputs=(), tol=1e-06)

Numerically initialize mdl (including its submodules) to a steady state.

Solves for the states and the given free_inputs such that all state derivatives are zero and mdl.output equals output_0. Each unit is solved separately, since the units of a model are independent (all model equations are elementwise over units). This keeps the number of free variables per solve at n_states_per_unit + len(free_inputs), regardless of n_units. The residual is still evaluated for all units (the models are vectorized), but only the entries of the unit being solved are used.

free_inputs are inputs of mdl that are not connected to other models (typically a 'bias' input). Their solved values are stored in mdl._input_values.

Source code in src/tops/dyn_models/utils.py
def auto_init(mdl, x0, v0, output_0, free_inputs=(), tol=1e-6):
    """Numerically initialize ``mdl`` (including its submodules) to a steady state.

    Solves for the states and the given ``free_inputs`` such that all state derivatives are zero
    and ``mdl.output`` equals ``output_0``. Each unit is solved separately, since the units of a
    model are independent (all model equations are elementwise over units). This keeps the number
    of free variables per solve at ``n_states_per_unit + len(free_inputs)``, regardless of
    ``n_units``. The residual is still evaluated for all units (the models are vectorized), but only
    the entries of the unit being solved are used.

    ``free_inputs`` are inputs of ``mdl`` that are not connected to other models (typically a
    'bias' input). Their solved values are stored in ``mdl._input_values``.
    """
    submodules = get_submodules(mdl)
    state_submodules = [sm for sm in submodules if sm.n_states > 0]

    # Global state indices of each unit, shape (n_units, n_states_per_unit)
    unit_state_idx = np.hstack([
        np.column_stack([sm.state_idx_global[state] for state in sm.state_list()])
        for sm in state_submodules
    ]) if state_submodules else np.zeros((mdl.n_units, 0), dtype=int)
    n_states_unit = unit_state_idx.shape[1]
    n_free = n_states_unit + len(free_inputs)

    x_all = x0.copy()

    def residual(z, i):
        x_all[unit_state_idx[i]] = z[:n_states_unit]
        for input_name, val in zip(free_inputs, z[n_states_unit:]):
            mdl._input_values[input_name][i] = val

        dx_all = np.zeros_like(x0)
        # Other units may be evaluated at meaningless points, hence errstate
        with store_outputs(submodules), np.errstate(all='ignore'):
            for submodule in state_submodules:
                submodule.state_derivatives(dx_all, x_all, v0)
            output_err = mdl.output(x_all, v0)[i] - output_0[i]

        return np.append(dx_all[unit_state_idx[i]], output_err)

    rng = np.random.default_rng(0)
    for i in range(mdl.n_units):
        z_best, err_best = None, np.inf
        for z_init in [np.ones(n_free), np.zeros(n_free), rng.standard_normal(n_free)]:
            try:
                sol = least_squares(residual, z_init, args=(i,))
            except ValueError:
                continue
            err = np.linalg.norm(residual(sol.x, i))
            if err < err_best:
                z_best, err_best = sol.x, err
            if err_best < tol:
                break

        if z_best is None:
            warnings.warn(f'Initialization of {mdl.par["name"][i]} ({mdl.__class__.__name__}) failed.')
            continue

        residual(z_best, i)  # Leave x_all and inputs at the best solution
        if err_best > tol:
            warnings.warn(
                f'{mdl.par["name"][i]} ({mdl.__class__.__name__}) was potentially not initialized '
                f'properly (error: {err_best:.2e}).'
            )

    x0[:] = x_all