pycity_scheduling.util package

Submodules

pycity_scheduling.util.approximation module

The pycity_scheduling framework

Copyright (C) 2025, Institute for Automation of Complex Power Systems (ACS), E.ON Energy Research Center (E.ON ERC), RWTH Aachen University

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

pycity_scheduling.util.approximation.piecewise_linear_approx(f, inf_bound, sup_bound, nb_samples=1000, nb_segments=10)

Perform piece-wise linear approximation for convex or concave 1D functions.

Find a partition of the bound interval using KMeans-clustering with x_sample and function slope as features, for a given number of clusters. Then perform a linear regression on each segment of the partition. The approximation is given by the maximum (resp. minimum) of all linear functions if the function to approximate is convex (resp. concave). The convexity of the function is given through the argument “convexity” that takes the value “convex” if the function is convex and anything else if the function is concave.

Parameters:
  • f (callable) – Function to be approximated.

  • inf_bound (list of float) – List of lower bounds for the variables in var.

  • sup_bound (list of float) – List of upper bounds for the variables in var.

  • nb_samples (int, default 100) – Number of sampling points.

  • nb_segments (int, default 10) – Number of segments used in the partitioning of the bound interval.

Returns:

  • slopes (List[float])

  • intercepts (List[float])

pycity_scheduling.util.debug module

The pycity_scheduling framework

Copyright (C) 2025, Institute for Automation of Complex Power Systems (ACS), E.ON Energy Research Center (E.ON ERC), RWTH Aachen University

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

pycity_scheduling.util.debug.analyze_model(model, optimizer, result, options={})

Analyze a model which is not optimal.

Parameters:
  • model (pyomo.ConcreteModel) – Model with status != OPTIMAL

  • optimizer (OptSolver) – The solver that was used for optimization and is used for analyzes

  • result (SolverResults) – The not optimal result that was returned by the solver

  • options (str, optional) – Options which should be passed to the solver when analyzing

pycity_scheduling.util.debug.print_district(cd, lvl=1)

Hierarchically print a city district.

Parameters:

pycity_scheduling.util.district_analyzer module

Python class to analyze the generated city district in terms of the total generated and consumed power

class pycity_scheduling.util.district_analyzer.DistrictAnalyzer(city_district)

Bases: object

Python class to analyze the generated city district in terms of the total generated and consumed power

Methods

add_vectors(numpy_vector, pyomo_vector)

Function to add an indexed pyomo variable with a numpy array elementwise

compare_aggregated_entities(...[, save_plots])

Function to compare the aggregated schedules of each entity type, if different algorithms were used for the optimization of the same city district.

compare_city_ditrict_schedules(...[, save_plots])

Function that compares the final city district schedules if two different optimization algorithms were used.

complete_pre_analyze()

Function to plot an estimation of the city districts schedules if no optimization was done.

convert_pyomo_to_numpy(pyomo_vector)

Function that converts an indexed pyomo variable to a numpy array

plot_city_district_schedule()

Function that plots the city districts' final schedule

plot_electrical_demand_profile([plot_now])

Pre analyze

plot_electrical_generation_profile([plot_now])

Pre analyze

plot_electrical_power_imbalance([plot_now])

Pre analyze

plot_entity_schedules(entity_class)

Function that plots all schedules of one type of entity, e.g. Batteries.

plot_heat_demand_profile([plot_now])

Pre analyze

check_start_vars_DL

compare_entity_schedules

complete_post_analyze

count_violated_constraints

plot_demand_profile

plot_flexible_device_schedules

plot_generation_profile

print_schedules

save_schedules

add_vectors(numpy_vector, pyomo_vector)

Function to add an indexed pyomo variable with a numpy array elementwise

check_start_vars_DL()
compare_aggregated_entities(first_optimization, first_algorithm_name, second_algorithm_name, save_plots=False)

Function to compare the aggregated schedules of each entity type, if different algorithms were used for the optimization of the same city district. It is mandatory that both optimizations are started in the same script and that an own DistrictAnalyzer object is created for each optimization. After the first executed optimization, the DistrictAnalyzer class method save_aggregated_schedules() has to be called to save the schedules for the later comparing.

compare_city_ditrict_schedules(first_optimization, first_algorithm_name, second_algorithm_name, save_plots=False)

Function that compares the final city district schedules if two different optimization algorithms were used.

compare_entity_schedules(entity_class, first_optimization, first_algorithm_name, second_algorithm_name)
complete_post_analyze()
complete_pre_analyze()

Function to plot an estimation of the city districts schedules if no optimization was done.

convert_pyomo_to_numpy(pyomo_vector)

Function that converts an indexed pyomo variable to a numpy array

count_violated_constraints()
figure_number = 5
plot_city_district_schedule()

Function that plots the city districts’ final schedule

plot_demand_profile(plot_now=False)
plot_electrical_demand_profile(plot_now=False)

Pre analyze

plot_electrical_generation_profile(plot_now=False)

Pre analyze

plot_electrical_power_imbalance(plot_now=False)

Pre analyze

plot_entity_schedules(entity_class)

Function that plots all schedules of one type of entity, e.g. Batteries

plot_flexible_device_schedules(plot_now=False)
plot_generation_profile(plot_now=False)
plot_heat_demand_profile(plot_now=False)

Pre analyze

print_schedules()
save_schedules()

pycity_scheduling.util.factory module

The pycity_scheduling framework

Copyright (C) 2025, Institute for Automation of Complex Power Systems (ACS), E.ON Energy Research Center (E.ON ERC), RWTH Aachen University

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

pycity_scheduling.util.factory.generate_simple_building(env, fl=0, sh=0, eh=0, ths=0, bat=0)

Generate a simple building with load and storage units.

Parameters:
  • env (pycity_scheduling.classes.Environment)

  • fl (float, optional) – Demand of the FixedLoad in [kW].

  • sh (float, optional) – Demand of the SpaceHeating in [kW].

  • eh (float, optional) – Power of the ElectricHeater in [kW].

  • ths (float, optional) – Capacity of the ThermalHeatingStorage in [kWh].

  • bat (float, optional) – Capacity of the Battery in [kWh].

Returns:

pycity_scheduling.classes.Building – Simple building with load and storage units.

Return type:

Building

pycity_scheduling.util.factory.generate_standard_environment(**timer_args)

Generate a standard environment object.

Return type:

pycity_scheduling.classes.Environment

pycity_scheduling.util.factory.generate_tabula_buildings(environment, number, building_distribution=None, heating_distribution=None, device_probabilities=None, objective='price', seed=None, mpi_interface=None)

Generate buildings based on the TABULA data.

Generate buildings based on the TABULA data from: http://www.episcope.eu/ (accessed on 2020/09/28) Heating units are automatically dimensioned and added to each building. A THS always covers the thermal energy demand of a building for at least two hours.

Parameters:
  • environment (pycity_scheduling.classes.Environment)

  • number (int) – Number of houses to be generated.

  • building_distribution (dict, optional) –

    The distribution of the houses among the tabula standard buildings. If omitted an equal distribution will be used. Keys : str

    ’DE.N.<SFH|MFH>.<n>.Gen’ or ‘<SFH|MFH>.<year>’

    Valuesfloat

    Number between 0 and 1. The sum over all values must be one.

  • heating_distribution (dict, optional) –

    The distribution of heating devices among the houses. If omitted an equal distribution will be used. Keys : str

    {‘HP’, ‘EH’, ‘CHP’, ‘BL’}

    Valuesfloat

    Number between 0 and 1. The sum over all values must be one.

  • device_probabilities (dict, optional) –

    The probabilities of the houses / apartments to have the given device. Keys : str

    {‘FL’, ‘DL’, ‘EV’, ‘PV’, ‘BAT’}

    Valuesfloat

    Number between 0 and 1.

  • objective (str, optional) – The objective for all buildings.

  • seed (int, optional) – Specify a seed for the randomization. If omitted, a non-deterministic city district will be generated.

  • mpi_interface (MPIInterface, optional) – In the case of MPI, create a more “lightweight” city district per MPI process only containing the particular buildings and assets that are required for the computations using MPI. Rank zero always has a list with all buildings.

Returns:

list of pycity_scheduling.classes.Building – List of generated buildings.

Return type:

list

pycity_scheduling.util.factory.generate_tabula_district(environment, number_sfh, number_mfh, sfh_building_distribution=None, sfh_heating_distribution=None, sfh_device_probabilities=None, mfh_building_distribution=None, mfh_heating_distribution=None, mfh_device_probabilities=None, district_objective='price', building_objective='price', seed=1, mpi_interface=None)

Generate a TABULA-based city district.

Parameters:
  • environment (pycity_scheduling.classes.Environment)

  • number_sfh (int) – Number of SFH buildings.

  • number_mfh (int) – Number of MFH buildings.

  • sfh_building_distribution (dict, optional) –

    The distribution of the houses among the tabula standard buildings. If omitted an equal distribution will be used. Keys : str

    ’DE.N.<SFH|MFH>.<n>.Gen’ or ‘<SFH|MFH>.<year>’

    Valuesfloat

    Number between 0 and 1. The sum over all values must be one.

  • sfh_heating_distribution (dict, optional) –

    The distribution of heating devices among the houses. If omitted an equal distribution will be used. Keys : str

    {‘HP’, ‘EH’, ‘CHP’, ‘BL’}

    Valuesfloat

    Number between 0 and 1. The sum over all values must be one.

  • sfh_device_probabilities (dict, optional) –

    The probabilities of the houses / apartments to have the given device. Keys : str

    {‘FL’, ‘DL’, ‘EV’, ‘PV’, ‘BAT’}

    Valuesfloat

    Number between 0 and 1.

  • mfh_building_distribution (dict, optional) –

    The distribution of the houses among the tabula standard buildings. If omitted an equal distribution will be used. Keys : str

    ’DE.N.<SFH|MFH>.<n>.Gen’ or ‘<SFH|MFH>.<year>’

    Valuesfloat

    Number between 0 and 1. The sum over all values must be one.

  • mfh_heating_distribution (dict, optional) –

    The distribution of heating devices among the houses. If omitted an equal distribution will be used. Keys : str

    {‘HP’, ‘EH’, ‘CHP’, ‘BL’}

    Valuesfloat

    Number between 0 and 1. The sum over all values must be one.

  • mfh_device_probabilities (dict, optional) –

    The probabilities of the houses / apartments to have the given device. Keys : str

    {‘FL’, ‘DL’, ‘EV’, ‘PV’, ‘BAT’}

    Valuesfloat

    Number between 0 and 1.

  • district_objective (str, optional) – Objective function for the city district (district operator). Default is ‘price’.

  • building_objective (str, optional) – Objective function for the buildings. Default is ‘price’.

  • seed (int, optional) – Specify a seed for the randomization. If omitted, a non-deterministic city district will be generated.

  • mpi_interface (MPIInterface, optional) – In the case of MPI, create a more “lightweight” city district per MPI process only containing the particular buildings and assets that are required for the computations using MPI. Rank zero always has the city district with all buildings.

Returns:

list of pycity_scheduling.classes.CityDistrict – CityDistrict object containing the generated buildings.

Return type:

CityDistrict

pycity_scheduling.util.generic_constraints module

The pycity_scheduling framework

Copyright (C) 2025, Institute for Automation of Complex Power Systems (ACS), E.ON Energy Research Center (E.ON ERC), RWTH Aachen University

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class pycity_scheduling.util.generic_constraints.Constraint

Bases: object

Base class for all generic constraints.

This class provides functionality common to all generic constraints. Generic constraints can be easily added to an entity block.

Methods

apply(model[, mode])

Apply constraint to block during populate_model method call.

apply(model, mode='')

Apply constraint to block during populate_model method call.

Parameters:
  • model (pyomo.Block) – The block corresponding to the entity the constraint should be applied to.

  • mode (str, optional) –

    Specifies which set of constraints to use.

    • convex : Use linear constraints

    • integer : May use integer variables

class pycity_scheduling.util.generic_constraints.LowerActivationLimit(o, var_name, lower_activation_limit, var_nom, min_off_time=1, min_on_time=1)

Bases: Constraint

Constraint Class for adding lower activation limits

This class provides functionality to add lower activation limits to entities. Adds no new constraints and variables if not in integer mode or if not required. A new state schedule is also created for the entity.

Notes

  • In integer mode the following constraints are added:

\[State \geq \frac{var}{var\_nom} \geq State * lower\_activation\_limit\]

Methods

apply(m[, mode])

Apply constraint to block during populate_model method call.

apply(m, mode='')

Apply constraint to block during populate_model method call.

Parameters:
  • model (pyomo.Block) – The block corresponding to the entity the constraint should be applied to.

  • mode (str, optional) –

    Specifies which set of constraints to use.

    • convex : Use linear constraints

    • integer : May use integer variables

pycity_scheduling.util.metric module

The pycity_scheduling framework

Copyright (C) 2025, Institute for Automation of Complex Power Systems (ACS), E.ON Energy Research Center (E.ON ERC), RWTH Aachen University

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

pycity_scheduling.util.metric.absolute_flexibility_gain(entity, schedule, timestep=None)

Calculates the absolute flexibility gain for the entity with the current schedule. This corresponds to the amount of electrical energy shifted due to the selected objective function.

Parameters:
  • entity (ElectricalEntity) – The entity to calculate the absolute flexibility gain for.

  • schedule (str) –

    Name of Schedule to compare to.

    • ’default’ : Default schedule

    • ’ref’ : Reference schedule

  • timestep (int, optional) – If specified, calculate metric only to this timestep.

Returns:

Absolute flexibility gain in [kWh].

Return type:

float

pycity_scheduling.util.metric.autarky(entity, timestep=None)

Calculate the autarky rate for the current schedule.

Parameters:
  • entity (ElectricalEntity) – The entity to calculate the autarky rate for.

  • timestep (int, optional) – If specified, calculate metric only to this timestep.

Returns:

Autarky rate.

Return type:

float

pycity_scheduling.util.metric.calculate_adj_costs(entity, schedule, timestep=None, prices=None, total_adjustments=True)

Calculate costs for power schedule adjustments.

Parameters:
  • entity (ElectricalEntity) – The entity to calculate adjustment costs for.

  • schedule (str, optional) –

    Schedule to adjust to.

    • ’default’ : Default schedule

    • ’ref’ : Reference schedule

  • timestep (int, optional) – If specified, calculate metric only to this timestep.

  • prices (array_like, optional) – Adjustment prices for all timesteps in simulation horizon.

  • total_adjustments (bool, optional) – True if positive and negative deviations shall be considered. False if only positive deviations shall be considered.

Returns:

Adjustment costs in [ct].

Return type:

float

pycity_scheduling.util.metric.calculate_adj_energy(entity, schedule, timestep=None, total_adjustments=True)

Compute the cumulative absolute energy of all adjustments.

Parameters:
  • entity (ElectricalEntity) – The entity to calculate the energy adjustment for.

  • schedule (str, optional) –

    Schedule to adjust to.

    • ’default’ : Default schedule

    • ’ref’ : Reference schedule

  • timestep (int, optional) – If specified, calculate metric only to this timestep.

  • total_adjustments (bool, optional) – True if positive and negative deviations shall be considered. False if only positive deviations shall be considered.

Returns:

Adjustments in [kWh].

Return type:

float

pycity_scheduling.util.metric.calculate_adj_power(entity, schedule, timestep=None, total_adjustments=True)

Compute the power schedule adjustments.

Parameters:
  • entity (ElectricalEntity) – The entity to calculate the power adjustment for.

  • schedule (str, optional) –

    Schedule to adjust to.

    • ’default’ : Default schedule

    • ’ref’ : Reference schedule

  • timestep (int, optional) – If specified, calculate metric only to this timestep.

  • total_adjustments (bool, optional) – True if positive and negative deviations shall be considered. False if only positive deviations shall be considered.

Returns:

Adjustment power in [kW].

Return type:

array of float

pycity_scheduling.util.metric.calculate_co2(entity, timestep=None, co2_emissions=None)

Calculate CO2 emissions for the entity with the current schedule.

Parameters:
  • entity (OptimizationEntity) – The entity to calculate co2 emission for.

  • timestep (int, optional) – If specified, calculate metric only to this timestep.

  • co2_emissions (array_like, optional) – Specific CO2 emissions for all timesteps in the simulation horizon in [g/kWh].

Returns:

CO2 emissions in [g].

Return type:

float

pycity_scheduling.util.metric.calculate_costs(entity, timestep=None, prices=None, feedin_factor=None)

Calculate electricity costs for the entity with the current schedule.

Parameters:
  • entity (ElectricalEntity) – The entity to calculate costs for.

  • timestep (int, optional) – If specified, calculate metric only to this timestep.

  • prices (array_like, optional) – Energy prices for simulation horizon.

  • feedin_factor (float, optional) – Factor which is multiplied to the prices for feed-in revenue.

Returns:

Electricity costs in [ct].

Return type:

float

pycity_scheduling.util.metric.metric_delta_g(entity, schedule)

Compute the factor ∆g for the current schedule and the reference schedule.

Parameters:
  • entity (ElectricalEntity) – The Entity to calculate the delta g metric for.

  • schedule (str) –

    Referenced Schedule

    • ’default’ : Normal schedule

    • ’ref’ : Reference schedule

Returns:

Factor ∆g.

Return type:

float

Notes

  • Implementation as given in the lecture “Elektrizitaetswirtschaft” by Prof. Dr.-Ing. Christian Rehtanz from TU Dortmund, Germany.

pycity_scheduling.util.metric.peak_reduction_ratio(entity, schedule, timestep=None)

Compute the ratio of the peak reduction.

The reduction of the absolute peak demand of the current schedule is compared to the peak demand in the reference schedule. If r < 1, the specified schedule has smaller peaks, otherwise the reference schedule has smaller peaks. Usually a small r value is the desired outcome.

Parameters:
  • entity (ElectricalEntity) – The entity to calculate the peak reduction ratio for.

  • schedule (str) –

    Name of Schedule to compare to.

    • ’default’ : Default schedule

    • ’ref’ : Reference schedule

  • timestep (int, optional) – If specified, calculate metric only to this timestep.

Returns:

Peak reduction ratio.

Return type:

float

pycity_scheduling.util.metric.peak_to_average_ratio(entity, timestep=None)

Compute the ratio of peak demand to the average demand.

The ratio of the absolute peak demand of the specified schedule is compared to the absolute mean of the schedule. It holds r >= 1, where a lower value is better, 1.0 would be optimal (i.e. no peaks at all).

Parameters:
  • entity (ElectricalEntity) – The entity to calculate the peak to avereage ratio for.

  • timestep (int, optional) – If specified, calculate metric only to this timestep.

Returns:

Peak to average ratio.

Return type:

float

pycity_scheduling.util.metric.self_consumption(entity, timestep=None)

Calculate the self-consumption rate for the current schedule.

Parameters:
  • entity (ElectricalEntity) – The entity to calculate the self-consumption rate for.

  • timestep (int, optional) – If specified, calculate metric only to this timestep.

Returns:

Self-consumption rate.

Return type:

float

pycity_scheduling.util.mpi_interface module

The pycity_scheduling framework

Copyright (C) 2025, Institute for Automation of Complex Power Systems (ACS), E.ON Energy Research Center (E.ON ERC), RWTH Aachen University

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class pycity_scheduling.util.mpi_interface.MPIInterface

Bases: object

Supporting class that handles interactions with the Message Passing Interface (MPI) using module mpi4py. MPI is used to perform parallel computations on loosely coupled machines.

Methods

disable_multiple_printing([stdout, stderr])

Turn off printing for all MPI processes with MPI rank other than 0 and always flush prints for rank 0.

get_comm()

Return the MPI COMM interface.

get_mpi_process_range(n)

Determine which MPI processes are responsible for which elements in an array.

get_rank()

Return the rank of the current MPI process.

get_size()

Return the size, i.e., number, of MPI processes.

disable_multiple_printing(stdout=True, stderr=True)

Turn off printing for all MPI processes with MPI rank other than 0 and always flush prints for rank 0.

Parameters:
  • stdout (bool) – Turn off printing for stdout.

  • stderr (bool) – Turn off printing for stderr.

get_comm()

Return the MPI COMM interface.

get_mpi_process_range(n)

Determine which MPI processes are responsible for which elements in an array.

Parameters:

n (int) – Size of the array.

Returns:

mpi_process_range – Array, in which the number inside an entry corresponds to the responsible MPI rank.

Return type:

np.array

get_rank()

Return the rank of the current MPI process.

get_size()

Return the size, i.e., number, of MPI processes.

class pycity_scheduling.util.mpi_interface.UnbufferedPrint(stream)

Bases: object

Methods

write

writelines

write(data)
writelines(data)

pycity_scheduling.util.plot_schedules module

The pycity_scheduling framework

Copyright (C) 2025, Institute for Automation of Complex Power Systems (ACS), E.ON Energy Research Center (E.ON ERC), RWTH Aachen University

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

pycity_scheduling.util.plot_schedules.plot_entity(entity, schedule=None, ax=None, title=None)

Plot a single entity into axis.

Parameters:
  • entity (OptimizationEntity) – Entity that should be plotted.

  • schedule (str or list, optional) –

    Schedule or list of schedules to save. Defaults to the current schedule. At most two schedules can be plotted.

    • None : Current schedule of entity

    • ’default’ : Normal schedule

    • ’ref’ : Reference schedule

  • ax (matplotlib.Axes, optional) – Axes the Entity should be plotted into. Shows the plot in a new figure if not specified.

  • title (str, optional) – Title of the plot. Uses the name of the entity if not specified.

pycity_scheduling.util.plot_schedules.plot_entity_directory(entity, schedule=None, directory_path=None, levels=None, extension='png')

Plot the entity and its sub-entities into a directory.

Creates the directories and places the plots in them. :param entity: Entity that should be plotted. :type entity: OptimizationEntity :param schedule: Schedule or list of schedules to save. Defaults to the current schedule.

At most two schedules can be plotted. None : Current schedule of entity ‘default’ : Normal schedule ‘ref’ : Reference schedule

Parameters:
  • directory_path (str, optional) – Directory path in which plots are stored. Defaults to the name of the entity in the current directory.

  • levels (int, optional) –

    The level of sub-entities to plot. Defaults to all sub-entities.

    • 0 : Only print city district.

    • 1 : Only print city district and buildings.

    • 2 : Print city district, buildings and their lower entities.

    • : …

  • extension (str, optional) – File extension (i.e., the file format) of the figures to be stored in the given directory.

pycity_scheduling.util.plot_schedules.plot_imbalance(entity, schedule=None, var_name='p_el', ax=None, title=None)

Plot the imbalance of a schedule to its sub-entities.

For entity containers and other similar entities with sub-entities the schedule of some variables should be the equal to the sum of the schedule of these variables of the sub-entities. This function plots this imbalance.

Parameters:
  • entity (OptimizationEntity) – Entity that should be plotted.

  • schedule (str or list, optional) –

    Schedule or list of schedules to save. Defaults to the current schedule. At most two schedules can be plotted.

    • None : Current schedule of entity

    • ’default’ : Normal schedule

    • ’ref’ : Reference schedule

  • var_name (str, optional) – The name of the variable to plot the imbalance for. Defaults to “p_el”.

  • ax (matplotlib.Axes, optional) – Axes the Entity should be plotted into. Shows the plot in a new figure if not specified.

  • title (str, optional) – Title of the plot. Uses the name of the entity if not specified.

pycity_scheduling.util.write_schedules module

The pycity_scheduling framework

Copyright (C) 2025, Institute for Automation of Complex Power Systems (ACS), E.ON Energy Research Center (E.ON ERC), RWTH Aachen University

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

pycity_scheduling.util.write_schedules.schedule_to_csv(input_list, file_name, delimiter=';', schedule=None)

Write the optimized schedule of all entities to a CSV file.

Parameters:
  • input_list (list) – List of entities.

  • file_name (str or file-like object) – Specify the file name or an open file where the csv should be saved in. If file_name is a string and it does not have the .csv extension it will be appended.

  • delimiter (str) – CSV file delimiter character.

  • schedule (str or list, optional) –

    Schedule or list of schedules to save.

    • None : Current schedule of entity

    • ’default’ : Normal schedule

    • ’ref’ : Reference schedule

pycity_scheduling.util.write_schedules.schedule_to_dict(input_list, schedule=None)

Create a dictionary containing a reference to the optimized schedules.

Parameters:
  • input_list (list) – List of entities.

  • schedule (str or list, optional) –

    Schedule or list of schedules to save.

    • None : Current schedule of entity

    • ’default’ : Normal schedule

    • ’ref’ : Reference schedule

pycity_scheduling.util.write_schedules.schedule_to_json(input_list, file_name, schedule=None)

Write the optimized schedule of all entities to a json file.

Parameters:
  • input_list (list) – List of entities.

  • file_name (str or file-like object) – Specify the file name or an open file where the json should be saved in. If file_name is a string and it does not have the .json extension it will be appended.

  • schedule (str or list, optional) –

    Schedule or list of schedules to save.

    • None : Current schedule of entity

    • ’default’ : Normal schedule

    • ’ref’ : Reference schedule

Module contents

The pycity_scheduling framework

Copyright (C) 2025, Institute for Automation of Complex Power Systems (ACS), E.ON Energy Research Center (E.ON ERC), RWTH Aachen University

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

pycity_scheduling.util.calculate_flexibility_potential(city_district, algorithm='central', reference_algorithm='stand-alone')

Calculate and quantify the operational flexibility potential for a certain city district.

Parameters:
  • city_district (pycity_scheduling.classes.CityDistrict) – District for which the flexibility potential should be quantified.

  • algorithm (str) – Define which algorithm should be used for the flexibility potential quantification purposes. Must be one of ‘exchange-admm’, ‘dual-decomposition’, ‘stand-alone’, ‘local’ or ‘central’. Default: ‘central’.

  • reference_algorithm (str) – Define which algorithm should be used as the reference for the flexibility potential quantification purposes. Must be one of ‘exchange-admm’, ‘dual-decomposition’, ‘stand-alone’, ‘local’ or ‘central’. Default: ‘stand-alone’.

Returns:

City district operational flexibility potential in kWh.

Return type:

float

pycity_scheduling.util.compute_profile(timer, profile, pattern=None)

Compute a load series profile for an electrical vehicle.

Parameters:
  • timer (pycity_scheduling.classes.Timer)

  • profile (array of binaries) –

    Indicator when electrical vehicle can be charged.

    • profile[t] == 0: EV cannot be charged in t

    • profile[t] == 1: EV can be charged in t

    It must contain at least one 0 otherwise the model will become infeasible. Its length has to be consistent with pattern.

  • pattern (str, optional) –

    Define how the profile is to be used.

    • None : Profile matches simulation horizon.

    • ’daily’ : Profile matches one day.

    • ’weekly’ : Profile matches one week.

Return type:

numpy.ndarray

pycity_scheduling.util.extract_pyomo_value(variable, var_type=None, verbose=False)

Extract a single values out of the pyomo Variable after optimization.

Parameters:
  • variable (pyomo.Var) – Variable to extract value from.

  • var_type (type, optional) –

    Type with which variable should be stored. Defaults to Domain of pyomo Variable Container or float.

    • float : Store values as floating point numbers.

    • int : Store values as integers (rounding down if necessary).

    • bool : Store values as binary values.

  • verbose (bool, optional) – Verbose mode and output.

Returns:

Extracted value from the pyomo Variable or the closest value to zero if stale.

Return type:

float or int or bool

Raises:

SchedulingError – If value to extract is not feasible.

pycity_scheduling.util.extract_pyomo_values(variable, var_type=None, verbose=False)

Extract values out of the pyomo Variable container after optimization.

Parameters:
  • variable (pyomo.Var) – Variable container to extract values from.

  • var_type (type, optional) –

    Type with which variable should be stored. Defaults to Domain of pyomo Variable Container or float.

    • float : Store values as floating point numbers.

    • int : Store values as integers (rounding down if necessary).

    • bool : Store values as binary values.

  • verbose (bool, optional) – Verbose mode and output.

Returns:

If the Variable container is indexed an array containing the extracted values is returned. If the Variable container is not indexed returns the single extracted value.

Return type:

numpy.ndarray or float or int or bool

Raises:

SchedulingError – If values to extract are not feasible.