Skip to content

Simulator

The simulation loop, event scheduling and result recording.

Simulator

Simulator(
    ps,
    dt=0.005,
    solver=dps_sol.ModifiedEulerDAE,
    t_end=np.inf,
    log_fun=None,
    ode_fun=None,
    events=None,
)

Parameters:

Name Type Description Default
ps

Initialized PowerSystemModel.

required
events

Events to apply during the simulation, as a table (list with header row, or DataFrame) with columns t, category, model, unit, action, or t, event, unit. See EventSchedule.

None
Source code in src/tops/simulator.py
def __init__(self, ps, dt=5e-3, solver=dps_sol.ModifiedEulerDAE, t_end=np.inf, log_fun=None, ode_fun=None,
             events=None):
    """
    :param ps: Initialized PowerSystemModel.
    :param events: Events to apply during the simulation, as a table (list with header row, or DataFrame)
        with columns t, category, model, unit, action, or t, event, unit. See EventSchedule.
    """

    self._stopped = False
    self.n_markers = 20
    self.t_end = t_end
    self.dt = dt
    self.log_fun = log_fun
    self.log = callable(self.log_fun)
    self.ps = ps
    self.events = EventSchedule(events)
    self.events.check(self.ps)

    if callable(ode_fun):
        self.ode_fun = ode_fun
    else:
        self.ode_fun = self.ps.ode_fun

    self.sol = solver(self.ps.state_derivatives, self.ps.solve_algebraic, 0, self.ps.x0, v0=self.ps.v0, max_step=self.dt, first_step=self.dt)

    self.new_data_cv = threading.Condition()
    self.new_data_ready = False
    self.x = self.sol.y
    self.t = self.sol.t

    self.interface_functions = dict()
    self.interface_functions_lock = threading.Lock()
    self.interface_timers = dict()

n_markers instance-attribute

n_markers = 20

t_end instance-attribute

t_end = t_end

dt instance-attribute

dt = dt

log_fun instance-attribute

log_fun = log_fun

log instance-attribute

log = callable(self.log_fun)

ps instance-attribute

ps = ps

events instance-attribute

events = EventSchedule(events)

ode_fun instance-attribute

ode_fun = ode_fun

sol instance-attribute

sol = solver(
    self.ps.state_derivatives,
    self.ps.solve_algebraic,
    0,
    self.ps.x0,
    v0=self.ps.v0,
    max_step=self.dt,
    first_step=self.dt,
)

new_data_cv instance-attribute

new_data_cv = threading.Condition()

new_data_ready instance-attribute

new_data_ready = False

x instance-attribute

x = self.sol.y

t instance-attribute

t = self.sol.t

interface_functions instance-attribute

interface_functions = dict()

interface_functions_lock instance-attribute

interface_functions_lock = threading.Lock()

interface_timers instance-attribute

interface_timers = dict()

stopped

stopped()
Source code in src/tops/simulator.py
def stopped(self):
    return self._stopped

make_simulation_step

make_simulation_step()
Source code in src/tops/simulator.py
def make_simulation_step(self):
    # Simulate next step
        with self.new_data_cv:
            self.events.apply_due(self.ps, self.sol.t)
            self.sol.step()

            with self.interface_functions_lock:
                for key, fun in self.interface_functions.items():
                    fun(self)

            self.new_data_ready = True
            self.new_data_cv.notify()

main_loop

main_loop()
Source code in src/tops/simulator.py
def main_loop(self):
    t = self.sol.t
    while not self.stopped() and t < self.t_end:
        self.make_simulation_step()
        t = self.sol.t

EventSchedule

EventSchedule(events=None)

Events to be applied at given times.

Events are given as a table (list with header row, or DataFrame) with columns t, category, model, unit, action, e.g. [0.1, 'lines', 'Line', 'L1-2', 'disconnect'] or [0.1, 'buses', '', 'B1', 'short_circuit']. The model column is ignored for category 'buses'. An optional column kwargs holds a dict of arguments for the action, or None, e.g. [0.1, 'buses', '', 'B1', 'short_circuit', {'y': 100}]; they are kept in the list kwargs, one per event.

Alternatively, the table has columns t, event, unit (and optionally kwargs), where event is an event function of the power system model, e.g. [0.1, ps.lines.Line.events.disconnect, 'L1-2'] or [0.1, ps.bus_events.short_circuit, 'B1']. Such events are kept as (t, event, unit).

Used by the Simulator, or directly in a custom simulation loop:

schedule = EventSchedule(events)
schedule.check(ps)
while t < t_end:
    schedule.apply_due(ps, t)
    ...
Source code in src/tops/simulator.py
def __init__(self, events=None):
    table = read_table(events) if events is not None else None
    if table is None or len(table) == 0:
        self.events = []
        self.kwargs = []
    else:
        fields = self.function_fields if 'event' in table.dtype.names else self.fields
        missing = [field for field in fields if field not in table.dtype.names]
        if missing:
            raise ValueError(f'Event table is missing fields: {missing}. The columns are '
                             f'{list(self.fields)} or {list(self.function_fields)}, and optionally kwargs.')
        order = np.argsort(table['t'], kind='stable')
        self.events = [tuple(self._read_value(table[field][i]) for field in fields) for i in order]
        kwargs = table['kwargs'] if 'kwargs' in table.dtype.names else [None]*len(table)
        self.kwargs = [self._read_kwargs(kwargs[i]) for i in order]
    self.reset()

fields class-attribute instance-attribute

fields = ('t', 'category', 'model', 'unit', 'action')

function_fields class-attribute instance-attribute

function_fields = ('t', 'event', 'unit')

events instance-attribute

events = []

kwargs instance-attribute

kwargs = []

reset

reset()
Source code in src/tops/simulator.py
def reset(self):
    self._next = 0

check

check(ps)

Check that all events exist in the (initialized) power system model.

Source code in src/tops/simulator.py
def check(self, ps):
    """Check that all events exist in the (initialized) power system model."""
    for _, *event in self.events:
        ps.check_event(*event)

pop_due

pop_due(t)

Return events with time <= t that have not been returned before.

Source code in src/tops/simulator.py
def pop_due(self, t):
    """Return events with time <= t that have not been returned before."""
    due = []
    while self._next < len(self.events) and self.events[self._next][0] <= t:
        due.append(self.events[self._next])
        self._next += 1
    return due

apply_due

apply_due(ps, t)

Apply events with time <= t that have not been applied before.

Source code in src/tops/simulator.py
def apply_due(self, ps, t):
    """Apply events with time <= t that have not been applied before."""
    first = self._next
    for (_, *event), kwargs in zip(self.pop_due(t), self.kwargs[first:self._next]):
        ps.apply_event(*event, **kwargs)

Events

Events(sim, data)

Events given as a list of (t, ('line', line_name, action)).

Kept for backwards compatibility. Events can instead be given to the Simulator (Simulator(ps, ..., events=...)).

Source code in src/tops/simulator.py
def __init__(self, sim, data):
    self.data = sorted(data, key=lambda event: event[0])
    self._next = 0

data instance-attribute

data = sorted(data, key=lambda event: event[0])

update

update(sim)
Source code in src/tops/simulator.py
def update(self, sim):
    while self._next < len(self.data) and self.data[self._next][0] <= sim.sol.t:
        _, (category, name, action) = self.data[self._next]
        if category != 'line':
            raise ValueError(f'Events only supports line events, not "{category}". Use Simulator(ps, ..., events=...) instead.')
        sim.ps.apply_event('lines', 'Line', name, action)
        self._next += 1

InterfacerDirect

InterfacerDirect(
    rts=None, name="InterfacerDirect", fs=None
)

Parameters:

Name Type Description Default
fs

Updates per second of simulated time, or None to update at every step.

None
Source code in src/tops/simulator.py
def __init__(self, rts=None, name='InterfacerDirect', fs=None):
    """:param fs: Updates per second of simulated time, or None to update at every step."""
    self.interface_name = name
    self.fs = fs
    self._timer = 0

    if rts:
        self.connect(rts)

interface_name instance-attribute

interface_name = name

fs instance-attribute

fs = fs

connect

connect(rts)
Source code in src/tops/simulator.py
def connect(self, rts):
    rts.interface_functions[self.interface_name] = self.interface_fun

interface_fun

interface_fun(rts)
Source code in src/tops/simulator.py
def interface_fun(self, rts):
    if self.fs:
        if rts.sol.t < self._timer:
            return
        else:
            self._timer += 1 / self.fs

    self.update(self.read_input_signal(rts))
    self.apply_ctrl_signal(rts, self.generate_ctrl_signal())

read_input_signal

read_input_signal(rts)
Source code in src/tops/simulator.py
def read_input_signal(self, rts):
    # Read input from RealTimeSimulator
    pass

apply_ctrl_signal

apply_ctrl_signal(rts, ctrl_signal)
Source code in src/tops/simulator.py
def apply_ctrl_signal(self, rts, ctrl_signal):
    # Apply control in RealTimeSimulator, generated by "generate_ctrl_signal"
    pass

generate_ctrl_signal

generate_ctrl_signal()
Source code in src/tops/simulator.py
def generate_ctrl_signal(self):
    # Generate control signal from internal states
    pass

update

update(input)
Source code in src/tops/simulator.py
def update(self, input):
    # Update internal states from whatever is returned by "read_input_signal"
    pass

ResultKeeper

ResultKeeper(sim, **kwargs)

Stores the states and algebraic variables at every step, and the outputs given as keyword arguments.

Add it as an interface function of the Simulator:

res = ResultKeeper(sim, speed=ps.gen.GEN.speed)
sim.interface_functions['results'] = res.update

Parameters:

Name Type Description Default
sim

The Simulator. Create the ResultKeeper before the simulation starts.

required
kwargs

Functions f(x, v) to store at every step, e.g. ps.gen.GEN.speed. Kept in store[name].

{}
Source code in src/tops/simulator.py
def __init__(self, sim, **kwargs):
    self.t = []
    self.x = []
    self.v = []
    self.sim = sim
    self.store = defaultdict(list)
    self.spec = dict(**kwargs)

    # The events, and what they change in the model as it is now, so that calculate can replay them
    # Not a deep copy, which would copy the models behind event functions (e.g. ps.lines.Line.events.disconnect)
    self.events = copy.copy(sim.events)
    self.events.events = list(sim.events.events)
    self.events.kwargs = [dict(kwargs) for kwargs in sim.events.kwargs]
    self._event_state = sim.ps._save_event_state()
    self._n_events = []  # Number of events applied at each step

t instance-attribute

t = []

x instance-attribute

x = []

v instance-attribute

v = []

sim instance-attribute

sim = sim

store instance-attribute

store = defaultdict(list)

spec instance-attribute

spec = dict(**kwargs)

events instance-attribute

events = copy.copy(sim.events)

update

update(sim)
Source code in src/tops/simulator.py
def update(self, sim):
    self.t.append(sim.sol.t)
    self.x.append(sim.sol.x.copy())
    self.v.append(sim.sol.v.copy())
    self._n_events.append(sim.events._next)
    for key, val in self.spec.items():
        self.store[key].append(val(sim.sol.x, sim.sol.v).copy())

calculate

calculate(fun)

Calculate a function of the states and algebraic variables at every stored step, after the simulation.

The events of the Simulator are replayed, so that e.g. the current of a line is zero while it is disconnected. Changes made in other ways during the simulation (set_input, or ps.apply_event in an interface function) are not replayed. The model is left as it was before the call.

Parameters:

Name Type Description Default
fun

Function f(x, v), e.g. ps.gen.GEN.speed or ps.lines.Line.p_from.

required

Returns:

Type Description

Array with one row per stored step and one column per unit.

Source code in src/tops/simulator.py
def calculate(self, fun):
    """Calculate a function of the states and algebraic variables at every stored step, after the simulation.

    The events of the Simulator are replayed, so that e.g. the current of a line is zero while it is disconnected.
    Changes made in other ways during the simulation (set_input, or ps.apply_event in an interface function) are
    not replayed. The model is left as it was before the call.

    :param fun: Function f(x, v), e.g. ps.gen.GEN.speed or ps.lines.Line.p_from.
    :return: Array with one row per stored step and one column per unit.
    """
    ps = self.sim.ps
    state_now = ps._save_event_state()
    applied = self.events._next
    result = []
    try:
        ps._restore_event_state(self._event_state)
        for x, v, n_events in zip(self.x, self.v, self._n_events):
            for i in range(applied, n_events):
                _, *event = self.events.events[i]
                ps.apply_event(*event, **self.events.kwargs[i])
            applied = n_events
            result.append(fun(x, v))
    finally:
        ps._restore_event_state(state_now)
    return np.array(result)

get_dataframe

get_dataframe()
Source code in src/tops/simulator.py
def get_dataframe(self):
    df = pd.DataFrame(columns=self.sim.ps.state_desc, data=self.x, index=self.t)
    return df