Skip to content

Model data

Loading and normalising model dictionaries and JSON files, and the power flow.

model_data

Loading and normalization of power system model data.

PS_MODELS_DIR module-attribute

PS_MODELS_DIR = os.path.join(
    os.path.dirname(os.path.abspath(__file__)), "ps_models"
)

CATEGORY_ALIASES module-attribute

CATEGORY_ALIASES = {
    "transformers": "trafos",
    "generators": "gen",
}

DEFAULT_MODELS module-attribute

DEFAULT_MODELS = {
    "lines": "Line",
    "switches": "Switch",
    "trafos": "Trafo",
    "loads": "Load",
    "shunts": "Shunt",
}

read_json

read_json(path)

Read model data from a JSON file, looking in the bundled ps_models folder if the path does not exist.

Source code in src/tops/model_data.py
def read_json(path):
    """Read model data from a JSON file, looking in the bundled ps_models folder if the path does not exist."""
    for candidate in [path, os.path.join(PS_MODELS_DIR, path)]:
        try:
            with open(candidate) as f:
                return json.load(f)
        except IOError:
            continue
    raise FileNotFoundError(f'Power system model data file not found: {path}')

load_model_data

load_model_data(model)

Return a normalized (shallow) copy of model data.

Parameters:

Name Type Description Default
model

Dict with model data, or path to a .json file (which can also be the name of a bundled model, e.g. 'k2a.json').

required
Source code in src/tops/model_data.py
def load_model_data(model):
    """Return a normalized (shallow) copy of model data.

    :param model: Dict with model data, or path to a .json file (which can also be the name of a bundled model,
        e.g. 'k2a.json').
    """
    if isinstance(model, str) and model.endswith('.json'):
        model_data = read_json(model)
    elif isinstance(model, dict):
        model_data = model
    else:
        raise TypeError(f'model must be a dict or a path to a .json file, not {type(model).__name__}')

    if 'events' in model_data:
        raise ValueError('Events are not part of the model data. Give them to the Simulator instead: '
                         'Simulator(ps, ..., events=events).')

    model_data = model_data.copy()

    for alias, key in CATEGORY_ALIASES.items():
        if alias in model_data:
            model_data[key] = model_data.pop(alias)

    for key, default_mdl in DEFAULT_MODELS.items():
        if key in model_data and is_table(model_data[key]):
            model_data[key] = {default_mdl: model_data[key]}

    return model_data

find_model_class

find_model_class(category_key, mdl_key, user_mdl_lib=None)

Look up a model class, first in the user model library and then in the standard one.

Returns None (with a warning) if the model is not found.

Source code in src/tops/model_data.py
def find_model_class(category_key, mdl_key, user_mdl_lib=None):
    """Look up a model class, first in the user model library and then in the standard one.

    Returns None (with a warning) if the model is not found.
    """
    for lib in [user_mdl_lib, mdl_lib]:
        category = getattr(lib, category_key, None)
        if category is not None and hasattr(category, mdl_key):
            return getattr(category, mdl_key)

    warnings.warn(f'Model {category_key}:{mdl_key} not found in model library.')
    return None

is_table

is_table(data)

Check if data is a single table (list with header row and at least one entry, or a DataFrame).

Source code in src/tops/model_data.py
def is_table(data):
    """Check if data is a single table (list with header row and at least one entry, or a DataFrame)."""
    return isinstance(data, pd.DataFrame) or (isinstance(data, list) and len(data) > 1)

read_table

read_table(data)

Convert a table given as a list (header row followed by entries) or a DataFrame to a structured array.

Source code in src/tops/model_data.py
def read_table(data):
    """Convert a table given as a list (header row followed by entries) or a DataFrame to a structured array."""
    if isinstance(data, list):
        return dps_uf.structured_array_from_list(data[0], data[1:])
    elif isinstance(data, pd.DataFrame):
        return dps_uf.structured_array_from_dataframe(data)
    raise TypeError(f'Table data must be a list or a pandas DataFrame, not {type(data).__name__}')

power_flow

Power flow: collects injections from models, solves, and distributes the solution back to the units.

PowerFlowResult dataclass

PowerFlowResult(
    v, s, converged, slack_unit=None, unit_injections=dict()
)

v instance-attribute

v

s instance-attribute

s

converged instance-attribute

converged

slack_unit class-attribute instance-attribute

slack_unit = None

unit_injections class-attribute instance-attribute

unit_injections = field(default_factory=dict)

default_slack_bus_idx

default_slack_bus_idx(pv_mdls)

Index of the bus of the PV unit with the largest P setpoint, used as slack bus if none is specified.

Ties are resolved in favour of the first unit found.

Source code in src/tops/power_flow.py
def default_slack_bus_idx(pv_mdls):
    """Index of the bus of the PV unit with the largest P setpoint, used as slack bus if none is specified.

    Ties are resolved in favour of the first unit found.
    """
    bus_idx, p_load = zip(*(mdl.load_flow_pv()[:2] for mdl in pv_mdls))
    bus_idx = np.concatenate(bus_idx)
    p_gen = -np.concatenate(p_load)  # load_flow_pv() uses load convention
    return bus_idx[np.argmax(p_gen)]

load_flow_q_share

load_flow_q_share(mdl)

Weights of the PV units of a model in the sharing of the reactive power at their buses.

Parameters:

Name Type Description Default
mdl

A model with load_flow_pv().

required

Returns:

Type Description

One weight per unit, in the order of load_flow_pv(): mdl.load_flow_q_share() if the model has it, else 1 for every unit (equal shares).

Source code in src/tops/power_flow.py
def load_flow_q_share(mdl):
    """Weights of the PV units of a model in the sharing of the reactive power at their buses.

    :param mdl: A model with ``load_flow_pv()``.
    :return: One weight per unit, in the order of ``load_flow_pv()``: ``mdl.load_flow_q_share()`` if the model has
        it, else 1 for every unit (equal shares).
    """
    if hasattr(mdl, 'load_flow_q_share'):
        return np.asarray(mdl.load_flow_q_share(), dtype=float)
    return np.ones(len(mdl.load_flow_pv()[0]))

solve_power_flow

solve_power_flow(
    y_bus, pq_mdls, pv_mdls, s_n, sl_idx, tol, max_it
)

Solve the power flow.

Parameters:

Name Type Description Default
y_bus

Bus admittance matrix for the power flow.

required
pq_mdls

Models with load_flow_pq(), returning (bus_idx, P, Q) in MW/MVAr.

required
pv_mdls

Models with load_flow_pv(), returning (bus_idx, P setpoint, V setpoint). P is in MW with load convention, i.e. a generator producing 100 MW returns -100.

required
s_n

System base power (MVA).

required
sl_idx

Index of the slack bus.

required
Source code in src/tops/power_flow.py
def solve_power_flow(y_bus, pq_mdls, pv_mdls, s_n, sl_idx, tol, max_it):
    """Solve the power flow.

    :param y_bus: Bus admittance matrix for the power flow.
    :param pq_mdls: Models with load_flow_pq(), returning (bus_idx, P, Q) in MW/MVAr.
    :param pv_mdls: Models with load_flow_pv(), returning (bus_idx, P setpoint, V setpoint). P is in MW with load
        convention, i.e. a generator producing 100 MW returns -100.
    :param s_n: System base power (MVA).
    :param sl_idx: Index of the slack bus.
    """
    n_bus = y_bus.shape[0]
    bus_type = np.array(['PQ'] * n_bus, dtype='<U2')

    p_pq = np.zeros(n_bus)
    q_pq = np.zeros(n_bus)
    for mdl in pq_mdls:
        bus_idx, p, q = mdl.load_flow_pq()
        np.add.at(p_pq, bus_idx, p / s_n)
        np.add.at(q_pq, bus_idx, q / s_n)

    p_pv = np.zeros(n_bus)
    v_pv = np.ones(n_bus)
    # The slack unit is the unit at the slack bus with the largest P setpoint (first one found on ties)
    slack_unit = None
    p_gen_slack_unit = -np.inf
    for mdl in pv_mdls:
        bus_idx, p, v = mdl.load_flow_pv()
        at_slack = np.flatnonzero(bus_idx == sl_idx)
        if len(at_slack) > 0:
            p_gen = -p  # load_flow_pv() uses load convention
            unit_idx = at_slack[np.argmax(p_gen[at_slack])]
            if p_gen[unit_idx] > p_gen_slack_unit:
                slack_unit = (mdl, unit_idx)
                p_gen_slack_unit = p_gen[unit_idx]
        bus_type[bus_idx] = 'PV'
        np.add.at(p_pv, bus_idx, p / s_n)
        v_pv[bus_idx] = v

    bus_type[sl_idx] = 'SL'

    v_sol, s_sol, converged = newton_rhapson_power_flow(y_bus, v_pv, p_pv + p_pq, q_pq, bus_type, tol, max_it)

    # Reactive power at each PV bus is shared between the units at that bus in proportion to their weights
    # (load_flow_q_share(), e.g. their ratings; equal shares for models without one)
    weight_per_bus = np.zeros(n_bus)
    for mdl in pv_mdls:
        np.add.at(weight_per_bus, mdl.load_flow_pv()[0], load_flow_q_share(mdl))

    q_bus = s_sol.imag + q_pq
    q_per_weight = np.divide(q_bus, weight_per_bus, out=np.zeros_like(q_bus), where=weight_per_bus != 0)

    unit_injections = {}
    for mdl in pv_mdls:
        bus_idx, p_setp, v = mdl.load_flow_pv()
        q = q_per_weight[bus_idx] * load_flow_q_share(mdl)
        p = -p_setp / s_n
        if slack_unit is not None and slack_unit[0] is mdl:
            # The slack unit takes the power balance at the slack bus
            unit_idx = slack_unit[1]
            p[unit_idx] = s_sol[sl_idx].real - p_setp[unit_idx] / s_n + p_pv[sl_idx] + p_pq[sl_idx]

        unit_injections[mdl] = (p + 1j * q) * s_n

    return PowerFlowResult(v_sol, s_sol, converged, slack_unit, unit_injections)