code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
priv_key = None
# If `key_id` is already a private key path, then easy.
if not FINGERPRINT_RE.match(key_id):
if not skip_priv_key:
f = io.open(key_id, 'rb')
try:
priv_key = f.read()
finally:
f.close()
pub_key_path = ke... | def load_ssh_key(key_id, skip_priv_key=False) | Load a local ssh private key (in PEM format). PEM format is the OpenSSH
default format for private keys.
See similar code in imgapi.js#loadSSHKey.
@param key_id {str} An ssh public key fingerprint or ssh private key path.
@param skip_priv_key {boolean} Optional. Default false. If true, then this
... | 2.569869 | 2.473264 | 1.03906 |
if FINGERPRINT_RE.match(key_id) and priv_key:
key_info = {"fingerprint": key_id, "priv_key": priv_key}
else:
# Otherwise, we attempt to load necessary details from ~/.ssh.
key_info = load_ssh_key(key_id)
# Load a key signer.
key = None
try:
key = serialization.l... | def ssh_key_info_from_key_data(key_id, priv_key=None) | Get/load SSH key info necessary for signing.
@param key_id {str} Either a private ssh key fingerprint, e.g.
'b3:f0:a1:6c:18:3b:42:63:fd:6e:57:42:74:17:d4:bc', or the path to
an ssh private key file (like ssh's IdentityFile config option).
@param priv_key {str} Optional. SSH private key file dat... | 2.902929 | 2.784087 | 1.042686 |
# Need the fingerprint of the key we're using for signing. If it
# is a path to a priv key, then we need to load it.
if not FINGERPRINT_RE.match(key_id):
ssh_key = load_ssh_key(key_id, True)
fingerprint = ssh_key["fingerprint"]
else:
fingerprint = key_id
# Look for a ma... | def agent_key_info_from_key_id(key_id) | Find a matching key in the ssh-agent.
@param key_id {str} Either a private ssh key fingerprint, e.g.
'b3:f0:a1:6c:18:3b:42:63:fd:6e:57:42:74:17:d4:bc', or the path to
an ssh private key file (like ssh's IdentityFile config option).
@return {dict} with these keys:
- type: "agent"
... | 4.762218 | 4.347774 | 1.095323 |
if self._key_info_cache is None:
self._key_info_cache = ssh_key_info_from_key_data(self.key_id,
self.priv_key)
return self._key_info_cache | def _get_key_info(self) | Get key info appropriate for signing. | 3.942545 | 3.369508 | 1.170065 |
if self._key_info_cache is None:
self._key_info_cache = agent_key_info_from_key_id(self.key_id)
return self._key_info_cache | def _get_key_info(self) | Get key info appropriate for signing. | 3.557746 | 3.147337 | 1.130399 |
if self._key_info_cache is not None:
return self._key_info_cache
errors = []
# First try the agent.
try:
key_info = agent_key_info_from_key_id(self.key_id)
except MantaError:
_, ex, _ = sys.exc_info()
errors.append(ex)
... | def _get_key_info(self) | Get key info appropriate for signing: either from the ssh agent
or from a private key. | 2.681638 | 2.387652 | 1.123127 |
# The list of possible options is available here:
# https://grpc.io/grpc/core/group__grpc__arg__keys.html
options = (options or []) + [
("grpc.max_send_message_length", grpc_max_msg_size),
("grpc.max_receive_message_length", grpc_max_msg_size),
]
interceptors = interceptors or [... | def create_channel(
target: str,
options: Optional[List[Tuple[str, Any]]] = None,
interceptors: Optional[List[ClientInterceptor]] = None,
) -> grpc.Channel | Creates a gRPC channel
The gRPC channel is created with the provided options and intercepts each
invocation via the provided interceptors.
The created channel is configured with the following default options:
- "grpc.max_send_message_length": 100MB,
- "grpc.max_receive_message_length": 100... | 2.314498 | 2.585298 | 0.895254 |
# The list of possible options is available here:
# https://grpc.io/grpc/core/group__grpc__arg__keys.html
options = (options or []) + [
("grpc.max_send_message_length", grpc_max_msg_size),
("grpc.max_receive_message_length", grpc_max_msg_size),
]
interceptors = [base.ServerInter... | def create_server(
max_workers: int,
options: Optional[List[Tuple[str, Any]]] = None,
interceptors: Optional[List[grpc.ServerInterceptor]] = None,
) -> grpc.Server | Creates a gRPC server
The gRPC server is created with the provided options and intercepts each
incoming RPCs via the provided interceptors.
The created server is configured with the following default options:
- "grpc.max_send_message_length": 100MB,
- "grpc.max_receive_message_length": 100... | 2.540827 | 2.910249 | 0.873062 |
u = urlparse(target)
if u.scheme == "dns":
raise ValueError("dns:// not supported")
if u.scheme == "unix":
return "unix:"+u.path
return u.netloc | def to_grpc_address(target: str) -> str | Converts a standard gRPC target to one that is supported by grpcio
:param target: the server address.
:returns: the converted address. | 4.282508 | 4.172369 | 1.026397 |
# Get disconnecting point's location
line = mv_grid.graph.edge[node1][node2]['line']
length_sd_line = .75e-3 # in km
x_sd = node1.geom.x + (length_sd_line / line.length) * (
node1.geom.x - node2.geom.x)
y_sd = node1.geom.y + (length_sd_line / line.length) * (
node1.geom.y - no... | def implement_switch_disconnector(mv_grid, node1, node2) | Install switch disconnector in grid topology
The graph that represents the grid's topology is altered in such way that
it explicitly includes a switch disconnector.
The switch disconnector is always located at ``node1``. Technically, it
does not make any difference. This is just an convention ensuring
... | 2.769445 | 2.877277 | 0.962523 |
cable_count = 1
if level == 'mv':
available_cables = network.equipment_data['mv_cables'][
network.equipment_data['mv_cables']['U_n'] ==
network.mv_grid.voltage_nom]
suitable_cables = available_cables[
available_cables['I_max_th'] *
network... | def select_cable(network, level, apparent_power) | Selects an appropriate cable type and quantity using given apparent
power.
Considers load factor.
Parameters
----------
network : :class:`~.grid.network.Network`
The eDisGo container object
level : :obj:`str`
Grid level ('mv' or 'lv')
apparent_power : :obj:`float`
A... | 1.979642 | 1.888042 | 1.048516 |
gens_w_id = []
if 'mv' in level:
gens = network.mv_grid.generators
gens_voltage_level = ['mv']*len(gens)
gens_type = [gen.type for gen in gens]
gens_rating = [gen.nominal_capacity for gen in gens]
for gen in gens:
try:
gens_w_id.append(gen... | def get_gen_info(network, level='mvlv', fluctuating=False) | Gets all the installed generators with some additional information.
Parameters
----------
network : :class:`~.grid.network.Network`
Network object holding the grid data.
level : :obj:`str`
Defines which generators are returned. Possible options are:
* 'mv'
Only genera... | 1.983554 | 1.743461 | 1.137711 |
mv_station_neighbors = mv_grid.graph.neighbors(mv_grid.station)
# get all nodes in MV grid and remove MV station to get separate subgraphs
mv_graph_nodes = mv_grid.graph.nodes()
mv_graph_nodes.remove(mv_grid.station)
subgraph = mv_grid.graph.subgraph(mv_graph_nodes)
for neighbor in mv_stat... | def assign_mv_feeder_to_nodes(mv_grid) | Assigns an MV feeder to every generator, LV station, load, and branch tee
Parameters
-----------
mv_grid : :class:`~.grid.grids.MVGrid` | 4.116412 | 4.21915 | 0.97565 |
try:
# get nodes of line
nodes = line.grid.graph.nodes_from_line(line)
# get feeders
feeders = {}
for node in nodes:
# if one of the nodes is an MV station the line is an MV feeder
# itself
if isinstance(node, MVStation):
... | def get_mv_feeder_from_line(line) | Determines MV feeder the given line is in.
MV feeders are identified by the first line segment of the half-ring.
Parameters
----------
line : :class:`~.grid.components.Line`
Line to find the MV feeder for.
Returns
-------
:class:`~.grid.components.Line`
MV feeder identifie... | 2.908866 | 2.798865 | 1.039302 |
# does only remove from network.pypsa, not from network.pypsa_lopf
# remove from pypsa (buses, storage_units, storage_units_t, lines)
neighbor = storage.grid.graph.neighbors(storage)[0]
if network.pypsa is not None:
line = storage.grid.graph.line_from_nodes(storage, neighbor)
networ... | def disconnect_storage(network, storage) | Removes storage from network graph and pypsa representation.
Parameters
-----------
network : :class:`~.grid.network.Network`
storage : :class:`~.grid.components.Storage`
Storage instance to be removed. | 2.942007 | 2.686654 | 1.095045 |
if not self._weather_cells:
# get all the weather cell ids
self._weather_cells = []
for gen in self.generators:
if hasattr(gen, 'weather_cell_id'):
self._weather_cells.append(gen.weather_cell_id)
# drop duplicates
... | def weather_cells(self) | Weather cells contained in grid
Returns
-------
list
list of weather cell ids contained in grid | 3.990873 | 4.146036 | 0.962575 |
if self._peak_generation is None:
self._peak_generation = sum(
[gen.nominal_capacity
for gen in self.generators])
return self._peak_generation | def peak_generation(self) | Cumulative peak generation capacity of generators of this grid
Returns
-------
float
Ad-hoc calculated or cached peak generation capacity | 5.986543 | 4.449685 | 1.345386 |
peak_generation = defaultdict(float)
for gen in self.generators:
peak_generation[gen.type] += gen.nominal_capacity
return pd.Series(peak_generation) | def peak_generation_per_technology(self) | Peak generation of each technology in the grid
Returns
-------
:pandas:`pandas.Series<series>`
Peak generation index by technology | 4.760877 | 5.831803 | 0.816365 |
peak_generation = defaultdict(float)
for gen in self.generators:
if hasattr(gen, 'weather_cell_id'):
if (gen.type, gen.weather_cell_id) in peak_generation.keys():
peak_generation[gen.type, gen.weather_cell_id] += gen.nominal_capacity
... | def peak_generation_per_technology_and_weather_cell(self) | Peak generation of each technology and the
corresponding weather cell in the grid
Returns
-------
:pandas:`pandas.Series<series>`
Peak generation index by technology | 2.507535 | 2.576836 | 0.973106 |
if self._peak_load is None:
self._peak_load = sum(
[_.peak_load.sum()
for _ in self.graph.nodes_by_attribute('load')])
return self._peak_load | def peak_load(self) | Cumulative peak load capacity of generators of this grid
Returns
-------
float
Ad-hoc calculated or cached peak load capacity | 5.393308 | 6.115977 | 0.881839 |
consumption = defaultdict(float)
for load in self.graph.nodes_by_attribute('load'):
for sector, val in load.consumption.items():
consumption[sector] += val
return pd.Series(consumption) | def consumption(self) | Consumption in kWh per sector for whole grid
Returns
-------
:pandas:`pandas.Series<series>`
Indexed by demand sector | 6.205328 | 7.424374 | 0.835805 |
if not self._generators:
generators = list(self.graph.nodes_by_attribute('generator'))
generators.extend(list(self.graph.nodes_by_attribute(
'generator_aggr')))
return generators
else:
return self._generators | def generators(self) | Connected Generators within the grid
Returns
-------
list
List of Generator Objects | 4.281355 | 5.560457 | 0.769965 |
# get nodes' positions
nodes_pos = {}
for node in self.graph.nodes():
nodes_pos[node] = (node.geom.x, node.geom.y)
plt.figure()
nx.draw_networkx(self.graph, nodes_pos, node_size=16, font_size=8)
plt.show() | def draw(self) | Draw MV grid's graph using the geo data of nodes
Notes
-----
This method uses the coordinates stored in the nodes' geoms which
are usually conformal, not equidistant. Therefore, the plot might
be distorted and does not (fully) reflect the real positions or
distances betw... | 3.145452 | 2.797543 | 1.124362 |
return dict([(v, k) for k, v in
nx.get_edge_attributes(self, 'line').items()])[line] | def nodes_from_line(self, line) | Get nodes adjacent to line
Here, line refers to the object behind the key 'line' of the attribute
dict attached to each edge.
Parameters
----------
line: edisgo.grid.components.Line
A eDisGo line object
Returns
-------
tuple
Node... | 8.334763 | 9.875373 | 0.843995 |
try:
line = nx.get_edge_attributes(self, 'line')[(u, v)]
except:
try:
line = nx.get_edge_attributes(self, 'line')[(v, u)]
except:
raise nx.NetworkXError('Line between ``u`` and ``v`` not '
... | def line_from_nodes(self, u, v) | Get line between two nodes ``u`` and ``v``.
Parameters
----------
u : :class:`~.grid.components.Component`
One adjacent node
v : :class:`~.grid.components.Component`
The other adjacent node
Returns
-------
Line
Line segment co... | 3.031286 | 2.97863 | 1.017678 |
temp_nodes = getattr(self, 'node')
nodes = list(filter(None, map(lambda x: x if temp_nodes[x][attr] == attr_val else None,
temp_nodes.keys())))
return nodes | def nodes_by_attribute(self, attr_val, attr='type') | Select Graph's nodes by attribute value
Get all nodes that share the same attribute. By default, the attr 'type'
is used to specify the nodes type (generator, load, etc.).
Examples
--------
>>> import edisgo
>>> G = edisgo.grids.Graph()
>>> G.add_node(1, type='g... | 4.65651 | 5.475824 | 0.850376 |
# get all lines that have the attribute 'type' set
lines_attributes = nx.get_edge_attributes(self, attr).items()
# attribute value provided?
if attr_val:
# extract lines where 'type' == attr_val
lines_attributes = [(k, self[k[0]][k[1]]['line'])
... | def lines_by_attribute(self, attr_val=None, attr='type') | Returns a generator for iterating over Graph's lines by attribute value.
Get all lines that share the same attribute. By default, the attr 'type'
is used to specify the lines' type (line, agg_line, etc.).
The edge of a graph is described by the two adjacent nodes and the line
object it... | 3.729326 | 3.207931 | 1.162533 |
rpc_method_handler = self._get_rpc_handler(handler_call_details)
if rpc_method_handler.response_streaming:
if self._wrapped.is_streaming:
# `self._wrapped` is a `StreamServerInterceptor`
return self._wrapped.intercept_service(
cont... | def intercept_service(self, continuation, handler_call_details) | Intercepts incoming RPCs before handing them over to a handler
See `grpc.ServerInterceptor.intercept_service`. | 2.924176 | 2.864063 | 1.020989 |
combined = {
c: pd.concat([mv[c], lv[c]], axis=0) for c in list(lv.keys())
}
combined['Transformer'] = mv['Transformer']
return combined | def combine_mv_and_lv(mv, lv) | Combine MV and LV grid topology in PyPSA format | 6.107374 | 5.470185 | 1.116484 |
generators = {}
loads = {}
# collect aggregated generation capacity by type and subtype
# collect aggregated load grouped by sector
for lv_grid in network.mv_grid.lv_grids:
generators.setdefault(lv_grid, {})
for gen in lv_grid.generators:
generators[lv_grid].setdef... | def add_aggregated_lv_components(network, components) | Aggregates LV load and generation at LV stations
Use this function if you aim for MV calculation only. The according
DataFrames of `components` are extended by load and generators representing
these aggregated respecting the technology type.
Parameters
----------
network : Network
The ... | 2.738718 | 2.684883 | 1.020051 |
mv_load_timeseries_p = []
mv_load_timeseries_q = []
lv_load_timeseries_p = []
lv_load_timeseries_q = []
# add MV grid loads
if mode is 'mv' or mode is None:
for load in network.mv_grid.graph.nodes_by_attribute('load'):
mv_load_timeseries_q.append(load.pypsa_timeseries('... | def _pypsa_load_timeseries(network, timesteps, mode=None) | Time series in PyPSA compatible format for load instances
Parameters
----------
network : Network
The eDisGo grid topology model overall container
timesteps : array_like
Timesteps is an array-like object with entries of type
:pandas:`pandas.Timestamp<timestamp>` specifying which... | 2.142813 | 2.121603 | 1.009997 |
mv_gen_timeseries_q = []
mv_gen_timeseries_p = []
lv_gen_timeseries_q = []
lv_gen_timeseries_p = []
# MV generator timeseries
if mode is 'mv' or mode is None:
for gen in network.mv_grid.generators:
mv_gen_timeseries_q.append(gen.pypsa_timeseries('q').rename(
... | def _pypsa_generator_timeseries(network, timesteps, mode=None) | Timeseries in PyPSA compatible format for generator instances
Parameters
----------
network : Network
The eDisGo grid topology model overall container
timesteps : array_like
Timesteps is an array-like object with entries of type
:pandas:`pandas.Timestamp<timestamp>` specifying w... | 1.961675 | 1.928968 | 1.016955 |
mv_storage_timeseries_q = []
mv_storage_timeseries_p = []
lv_storage_timeseries_q = []
lv_storage_timeseries_p = []
# MV storage time series
if mode is 'mv' or mode is None:
for storage in network.mv_grid.graph.nodes_by_attribute('storage'):
mv_storage_timeseries_q.app... | def _pypsa_storage_timeseries(network, timesteps, mode=None) | Timeseries in PyPSA compatible format for storage instances
Parameters
----------
network : Network
The eDisGo grid topology model overall container
timesteps : array_like
Timesteps is an array-like object with entries of type
:pandas:`pandas.Timestamp<timestamp>` specifying whi... | 1.942324 | 1.884464 | 1.030703 |
# get slack bus label
slack_bus = '_'.join(
['Bus', network.mv_grid.station.__repr__(side='mv')])
# set all buses (except slack bus) to nominal voltage
v_set_dict = {bus: 1 for bus in buses if bus != slack_bus}
# Set slack bus to operational voltage (includes offset and control
#... | def _pypsa_bus_timeseries(network, buses, timesteps) | Time series in PyPSA compatible format for bus instances
Set all buses except for the slack bus to voltage of 1 pu (it is assumed
this setting is entirely ignored during solving the power flow problem).
This slack bus is set to an operational voltage which is typically greater
than nominal voltage plus... | 5.801767 | 4.786799 | 1.212035 |
generation_p = []
generation_q = []
for lv_grid in network.mv_grid.lv_grids:
# Determine aggregated generation at LV stations
generation = {}
for gen in lv_grid.generators:
# for type in gen.type:
# for subtype in gen.subtype:
gen_name =... | def _pypsa_generator_timeseries_aggregated_at_lv_station(network, timesteps) | Aggregates generator time series per generator subtype and LV grid.
Parameters
----------
network : Network
The eDisGo grid topology model overall container
timesteps : array_like
Timesteps is an array-like object with entries of type
:pandas:`pandas.Timestamp<timestamp>` specif... | 2.285106 | 2.166692 | 1.054652 |
# ToDo: Load.pypsa_timeseries is not differentiated by sector so this
# function will not work (either change here and in
# add_aggregated_lv_components or in Load class)
load_p = []
load_q = []
for lv_grid in network.mv_grid.lv_grids:
# Determine aggregated load at LV station... | def _pypsa_load_timeseries_aggregated_at_lv_station(network, timesteps) | Aggregates load time series per sector and LV grid.
Parameters
----------
network : Network
The eDisGo grid topology model overall container
timesteps : array_like
Timesteps is an array-like object with entries of type
:pandas:`pandas.Timestamp<timestamp>` specifying which time ... | 3.636643 | 3.498119 | 1.039599 |
update_pypsa_load_timeseries(
network, loads_to_update=loads_to_update, timesteps=timesteps)
update_pypsa_generator_timeseries(
network, generators_to_update=generators_to_update,
timesteps=timesteps)
update_pypsa_storage_timeseries(
network, storages_to_update=storages_... | def update_pypsa_timeseries(network, loads_to_update=None,
generators_to_update=None, storages_to_update=None,
timesteps=None) | Updates load, generator, storage and bus time series in pypsa network.
See functions :func:`update_pypsa_load_timeseries`,
:func:`update_pypsa_generator_timeseries`,
:func:`update_pypsa_storage_timeseries`, and
:func:`update_pypsa_bus_timeseries` for more information.
Parameters
----------
... | 2.005987 | 2.265786 | 0.885338 |
_update_pypsa_timeseries_by_type(
network, type='load', components_to_update=loads_to_update,
timesteps=timesteps) | def update_pypsa_load_timeseries(network, loads_to_update=None,
timesteps=None) | Updates load time series in pypsa representation.
This function overwrites p_set and q_set of loads_t attribute of
pypsa network.
Be aware that if you call this function with `timesteps` and thus overwrite
current time steps it may lead to inconsistencies in the pypsa network
since only load time s... | 3.860733 | 5.94468 | 0.649443 |
_update_pypsa_timeseries_by_type(
network, type='generator', components_to_update=generators_to_update,
timesteps=timesteps) | def update_pypsa_generator_timeseries(network, generators_to_update=None,
timesteps=None) | Updates generator time series in pypsa representation.
This function overwrites p_set and q_set of generators_t attribute of
pypsa network.
Be aware that if you call this function with `timesteps` and thus overwrite
current time steps it may lead to inconsistencies in the pypsa network
since only g... | 3.864973 | 5.794806 | 0.666972 |
_update_pypsa_timeseries_by_type(
network, type='storage', components_to_update=storages_to_update,
timesteps=timesteps) | def update_pypsa_storage_timeseries(network, storages_to_update=None,
timesteps=None) | Updates storage time series in pypsa representation.
This function overwrites p_set and q_set of storage_unit_t attribute of
pypsa network.
Be aware that if you call this function with `timesteps` and thus overwrite
current time steps it may lead to inconsistencies in the pypsa network
since only s... | 3.907329 | 5.562675 | 0.702419 |
if timesteps is None:
timesteps = network.pypsa.buses_t.v_mag_pu_set.index
# check if timesteps is array-like, otherwise convert to list
if not hasattr(timesteps, "__len__"):
timesteps = [timesteps]
buses = network.pypsa.buses.index
v_mag_pu_set = _pypsa_bus_timeseries(network, ... | def update_pypsa_bus_timeseries(network, timesteps=None) | Updates buses voltage time series in pypsa representation.
This function overwrites v_mag_pu_set of buses_t attribute of
pypsa network.
Be aware that if you call this function with `timesteps` and thus overwrite
current time steps it may lead to inconsistencies in the pypsa network
since only bus t... | 2.809155 | 2.648819 | 1.060531 |
# pypsa dataframe to update
if type == 'load':
pypsa_ts = network.pypsa.loads_t
components_in_pypsa = network.pypsa.loads.index
elif type == 'generator':
pypsa_ts = network.pypsa.generators_t
components_in_pypsa = network.pypsa.generators.index
elif type == 'storage... | def _update_pypsa_timeseries_by_type(network, type, components_to_update=None,
timesteps=None) | Updates time series of specified component in pypsa representation.
Be aware that if you call this function with `timesteps` and thus overwrite
current time steps it may lead to inconsistencies in the pypsa network
since only time series of the specified component are updated but none of
the other time... | 3.085883 | 2.846752 | 1.084001 |
# determine generators cumulative apparent power output
generators = network.mv_grid.generators + \
[generators for lv_grid in
network.mv_grid.lv_grids for generators in
lv_grid.generators]
generators_p = pd.concat([_.timeseries['p'] for _ in generat... | def fifty_fifty(network, storage, feedin_threshold=0.5) | Operational mode where the storage operation depends on actual power by
generators. If cumulative generation exceeds 50% of nominal power, the
storage is charged. Otherwise, the storage is discharged.
The time series for active power is written into the storage.
Parameters
-----------
network :... | 3.78299 | 3.531799 | 1.071123 |
# get params from config
buffer_radius = int(network.config[
'grid_connection']['conn_buffer_radius'])
buffer_radius_inc = int(network.config[
'grid_connection']['conn_buffer_radius_inc'])
# get standard equipment
std_line_type = net... | def connect_mv_generators(network) | Connect MV generators to existing grids.
This function searches for unconnected generators in MV grids and connects them.
It connects
* generators of voltage level 4
* to HV-MV station
* generators of voltage level 5
* with a nom. capacity of <=30 kW to LV loads of ty... | 5.455114 | 5.227942 | 1.043453 |
network.results.equipment_changes = \
network.results.equipment_changes.append(
pd.DataFrame(
{'iteration_step': [0],
'change': ['added'],
'equipment': [line.type.name],
'quantity': [1]
},
in... | def _add_cable_to_equipment_changes(network, line) | Add cable to the equipment changes
All changes of equipment are stored in network.results.equipment_changes
which is used later to determine grid expansion costs.
Parameters
----------
network : :class:`~.grid.network.Network`
The eDisGo container object
line : class:`~.grid.components... | 5.286845 | 5.398735 | 0.979275 |
if line in network.results.equipment_changes.index:
network.results.equipment_changes = \
network.results.equipment_changes.drop(line) | def _del_cable_from_equipment_changes(network, line) | Delete cable from the equipment changes if existing
This is needed if a cable was already added to network.results.equipment_changes
but another node is connected later to this cable. Therefore, the cable needs to
be split which changes the id (one cable id -> 2 new cable ids).
Parameters
--------... | 3.497159 | 3.503106 | 0.998302 |
# threshold which is used to determine if 2 objects are on the same position (see below for details on usage)
conn_diff_tolerance = network.config['grid_connection'][
'conn_diff_tolerance']
conn_objects_min_stack = []
node_shp = transform(proj2equidistant(network), node.geom)
for br... | def _find_nearest_conn_objects(network, node, branches) | Searches all branches for the nearest possible connection object per branch
It picks out 1 object out of 3 possible objects: 2 branch-adjacent stations
and 1 potentially created branch tee on the line (using perpendicular projection).
The resulting stack (list) is sorted ascending by distance from node.
... | 3.93776 | 3.505663 | 1.123257 |
grid_district = os.path.basename(ding0_filepath)
grid_district_search = re.search('[_]+\d+', grid_district)
if grid_district_search:
grid_district = int(grid_district_search.group(0)[2:])
return grid_district
else:
raise (KeyError('Grid District not found in '.format(grid_di... | def _get_griddistrict(ding0_filepath) | Just get the grid district number from ding0 data file path
Parameters
----------
ding0_filepath : str
Path to ding0 data ending typically
`/path/to/ding0_data/"ding0_grids__" + str(``grid_district``) + ".xxx"`
Returns
-------
int
grid_district number | 3.149765 | 3.483948 | 0.904079 |
grid_district = _get_griddistrict(ding0_filepath)
grid_issues = {}
logging.info('Grid expansion for MV grid district {}'.format(grid_district))
if edisgo_grid: # if an edisgo_grid is passed in arg then ignore everything else
edisgo_grid = edisgo_grid[0]
else:
try:
... | def run_edisgo_basic(ding0_filepath,
generator_scenario=None,
analysis='worst-case',
*edisgo_grid) | Analyze edisgo grid extension cost as reference scenario
Parameters
----------
ding0_filepath : str
Path to ding0 data ending typically
`/path/to/ding0_data/"ding0_grids__" + str(``grid_district``) + ".xxx"`
analysis : str
Either 'worst-case' or 'timeseries'
generator_scen... | 4.200492 | 3.549656 | 1.183352 |
# base case with no generator import
edisgo_grid, \
costs_before_geno_import, \
grid_issues_before_geno_import = run_edisgo_basic(*run_args)
if edisgo_grid:
# clear the pypsa object and results from edisgo_grid
edisgo_grid.network.results = Results(edisgo_grid.network)
... | def run_edisgo_twice(run_args) | Run grid analysis twice on same grid: once w/ and once w/o new generators
First run without connection of new generators approves sufficient grid
hosting capacity. Otherwise, grid is reinforced.
Second run assessment grid extension needs in terms of RES integration
Parameters
----------
run_ar... | 4.414261 | 3.346959 | 1.318887 |
def collect_pool_results(result):
results.append(result)
results = []
pool = mp.Pool(workers,
maxtasksperchild=worker_lifetime)
for file in ding0_file_list:
edisgo_args = [file] + run_args_opt
pool.apply_async(func=run_edisgo_twice,
... | def run_edisgo_pool(ding0_file_list, run_args_opt,
workers=mp.cpu_count(), worker_lifetime=1) | Use python multiprocessing toolbox for parallelization
Several grids are analyzed in parallel.
Parameters
----------
ding0_file_list : list
Ding0 grid data file names
run_args_opt : list
eDisGo options, see :func:`run_edisgo_basic` and
:func:`run_edisgo_twice`
workers: ... | 2.524279 | 1.809054 | 1.395359 |
def collect_pool_results(result):
results.update({result.network.id: result})
results = {}
pool = mp2.Pool(workers,
maxtasksperchild=worker_lifetime)
def error_callback(key):
return lambda o: results.update({key: o})
for ding0_id in ding0_id_l... | def run_edisgo_pool_flexible(ding0_id_list, func, func_arguments,
workers=mp2.cpu_count(), worker_lifetime=1) | Use python multiprocessing toolbox for parallelization
Several grids are analyzed in parallel based on your custom function that
defines the specific application of eDisGo.
Parameters
----------
ding0_id_list : list of int
List of ding0 grid data IDs (also known as HV/MV substation IDs)
... | 3.120863 | 3.309153 | 0.9431 |
# when `file` is a string, it will be read by the help of pickle
if isinstance(file, str):
ding0_nd = load_nd_from_pickle(filename=file)
# otherwise it is assumed the object is passed directly
else:
ding0_nd = file
ding0_mv_grid = ding0_nd._mv_grid_districts[0].mv_grid
# M... | def import_from_ding0(file, network) | Import an eDisGo grid topology from
`Ding0 data <https://github.com/openego/ding0>`_.
This import method is specifically designed to load grid topology data in
the format as `Ding0 <https://github.com/openego/ding0>`_ provides it via
pickles.
The import of the grid topology includes
* the... | 5.91456 | 5.488823 | 1.077564 |
aggr_line_type = ding0_grid.network._static_data['MV_cables'].iloc[
ding0_grid.network._static_data['MV_cables']['I_max_th'].idxmax()]
for la_id, la in aggregated.items():
# add aggregated generators
for v_level, val in la['generation'].items():
for type, val2 in val.i... | def _attach_aggregated(network, grid, aggregated, ding0_grid) | Add Generators and Loads to MV station representing aggregated generation
capacity and load
Parameters
----------
grid: MVGrid
MV grid object
aggregated: dict
Information about aggregated load and generation capacity. For
information about the structure of the dict see ... .... | 3.92834 | 3.82531 | 1.026934 |
# Check number of components in MV grid
_validate_ding0_mv_grid_import(mv_grid, ding0_mv_grid)
# Check number of components in LV grid
_validate_ding0_lv_grid_import(mv_grid.lv_grids, ding0_mv_grid,
lv_grid_mapping)
# Check cumulative load and generation in... | def _validate_ding0_grid_import(mv_grid, ding0_mv_grid, lv_grid_mapping) | Cross-check imported data with original data source
Parameters
----------
mv_grid: MVGrid
eDisGo MV grid instance
ding0_mv_grid: MVGridDing0
Ding0 MV grid instance
lv_grid_mapping: dict
Translates Ding0 LV grids to associated, newly created eDisGo LV grids | 3.452701 | 3.404416 | 1.014183 |
integrity_checks = ['branch_tee',
'disconnection_point', 'mv_transformer',
'lv_station'#,'line',
]
data_integrity = {}
data_integrity.update({_: {'ding0': None, 'edisgo': None, 'msg': None}
for _ in int... | def _validate_ding0_mv_grid_import(grid, ding0_grid) | Verify imported data with original data from Ding0
Parameters
----------
grid: MVGrid
MV Grid data (eDisGo)
ding0_grid: ding0.MVGridDing0
Ding0 MV grid object
Notes
-----
The data validation excludes grid components located in aggregated load
areas as these are represen... | 3.798484 | 3.408723 | 1.114342 |
integrity_checks = ['branch_tee', 'lv_transformer',
'generator', 'load','line']
data_integrity = {}
for grid in grids:
data_integrity.update({grid:{_: {'ding0': None, 'edisgo': None, 'msg': None}
for _ in integrity_checks}})
# Chec... | def _validate_ding0_lv_grid_import(grids, ding0_grid, lv_grid_mapping) | Verify imported data with original data from Ding0
Parameters
----------
grids: list of LVGrid
LV Grid data (eDisGo)
ding0_grid: ding0.MVGridDing0
Ding0 MV grid object
lv_grid_mapping: dict
Defines relationship between Ding0 and eDisGo grid objects
Notes
-----
T... | 3.028367 | 2.809408 | 1.077937 |
if data_source == 'oedb':
logging.warning('Right now only solar and wind generators can be '
'imported from the oedb.')
_import_genos_from_oedb(network=network)
network.mv_grid._weather_cells = None
if network.pypsa is not None:
pypsa_io.upda... | def import_generators(network, data_source=None, file=None) | Import generator data from source.
The generator data include
* nom. capacity
* type ToDo: specify!
* timeseries
Additional data which can be processed (e.g. used in OEDB data) are
* location
* type
* subtype
* capacity
Parameters
----------... | 5.439495 | 5.57397 | 0.975874 |
genos_mv = pd.DataFrame(columns=
('id', 'obj'))
genos_lv = pd.DataFrame(columns=
('id', 'obj'))
genos_lv_agg = pd.DataFrame(columns=
('la_id', 'id', 'obj'))
# MV genos
for geno in network.mv_grid.graph.nod... | def _build_generator_list(network) | Builds DataFrames with all generators in MV and LV grids
Returns
-------
:pandas:`pandas.DataFrame<dataframe>`
A DataFrame with id of and reference to MV generators
:pandas:`pandas.DataFrame<dataframe>`
A DataFrame with id of and reference to LV generators
:pandas:`pandas.Da... | 2.79019 | 2.437738 | 1.144581 |
lv_grid_dict = {}
for lv_grid in network.mv_grid.lv_grids:
lv_grid_dict[lv_grid.id] = lv_grid
return lv_grid_dict | def _build_lv_grid_dict(network) | Creates dict of LV grids
LV grid ids are used as keys, LV grid references as values.
Parameters
----------
network: :class:`~.grid.network.Network`
The eDisGo container object
Returns
-------
:obj:`dict`
Format: {:obj:`int`: :class:`~.grid.grids.LVGrid`} | 2.758379 | 2.963569 | 0.930763 |
def _retrieve_timeseries_from_oedb(config_data, weather_cell_ids):
if config_data['data_source']['oedb_data_source'] == 'model_draft':
orm_feedin_name = config_data['model_draft']['res_feedin_data']
orm_feedin = model_draft.__getattribute__(orm_feedin_name)
... | def import_feedin_timeseries(config_data, weather_cell_ids) | Import RES feed-in time series data and process
Parameters
----------
config_data : dict
Dictionary containing config data from config files.
weather_cell_ids : :obj:`list`
List of weather cell id's (integers) to obtain feed-in data for.
Returns
-------
:pandas:`pandas.Data... | 3.244127 | 3.319261 | 0.977364 |
# calculate curtailment in each time step of each generator
curtailment = feedin.divide(feedin.sum(axis=1), axis=0). \
multiply(curtailment_timeseries, axis=0)
# substitute NaNs from division with 0 by 0
curtailment.fillna(0, inplace=True)
# check if curtailment target was met
_ch... | def feedin_proportional(feedin, generators, curtailment_timeseries, edisgo,
curtailment_key, **kwargs) | Implements curtailment methodology 'feedin-proportional'.
The curtailment that has to be met in each time step is allocated
equally to all generators depending on their share of total
feed-in in that time step.
Parameters
----------
feedin : :pandas:`pandas.DataFrame<dataframe>`
Datafr... | 3.470765 | 3.432173 | 1.011244 |
if not (abs(curtailment.sum(axis=1) - curtailment_target) < 1e-1).all():
message = 'Curtailment target not met for {}.'.format(curtailment_key)
logging.error(message)
raise TypeError(message) | def _check_curtailment_target(curtailment, curtailment_target,
curtailment_key) | Raises an error if curtailment target was not met in any time step.
Parameters
-----------
curtailment : :pandas:`pandas:DataFrame<dataframe>`
Dataframe containing the curtailment in kW per generator and time step.
Index is a :pandas:`pandas.DatetimeIndex<datetimeindex>`, columns are
... | 3.356536 | 3.401092 | 0.986899 |
gen_object_list = []
for gen in curtailment.columns:
# get generator object from representative
gen_object = generators.loc[generators.gen_repr == gen].index[0]
# assign curtailment to individual generators
gen_object.curtailment = curtailment.loc[:, gen]
gen_object... | def _assign_curtailment(curtailment, edisgo, generators, curtailment_key) | Helper function to write curtailment time series to generator objects.
This function also writes a list of the curtailed generators to curtailment
in :class:`edisgo.grid.network.TimeSeries` and
:class:`edisgo.grid.network.Results`.
Parameters
----------
curtailment : :pandas:`pandas.DataFrame<... | 3.242624 | 2.886088 | 1.123536 |
# get parameters for standard transformer
try:
standard_transformer = network.equipment_data['lv_trafos'].loc[
network.config['grid_expansion_standard_equipment'][
'mv_lv_transformer']]
except KeyError:
print('Standard MV/LV transformer is not in equipment l... | def extend_distribution_substation_overloading(network, critical_stations) | Reinforce MV/LV substations due to overloading issues.
In a first step a parallel transformer of the same kind is installed.
If this is not sufficient as many standard transformers as needed are
installed.
Parameters
----------
network : :class:`~.grid.network.Network`
critical_stations : ... | 4.02694 | 3.665482 | 1.098611 |
# get parameters for standard transformer
try:
standard_transformer = network.equipment_data['lv_trafos'].loc[
network.config['grid_expansion_standard_equipment'][
'mv_lv_transformer']]
except KeyError:
print('Standard MV/LV transformer is not in equipment l... | def extend_distribution_substation_overvoltage(network, critical_stations) | Reinforce MV/LV substations due to voltage issues.
A parallel standard transformer is installed.
Parameters
----------
network : :class:`~.grid.network.Network`
critical_stations : :obj:`dict`
Dictionary with :class:`~.grid.grids.LVGrid` as key and a
:pandas:`pandas.DataFrame<dataf... | 6.567576 | 5.776654 | 1.136917 |
# load standard line data
try:
standard_line_lv = network.equipment_data['lv_cables'].loc[
network.config['grid_expansion_standard_equipment']['lv_line']]
except KeyError:
print('Chosen standard LV line is not in equipment list.')
try:
standard_line_mv = network... | def reinforce_branches_overloading(network, crit_lines) | Reinforce MV or LV grid due to overloading.
Parameters
----------
network : :class:`~.grid.network.Network`
crit_lines : :pandas:`pandas.DataFrame<dataframe>`
Dataframe containing over-loaded lines, their maximum relative
over-loading and the corresponding time step.
Index o... | 3.570007 | 2.973044 | 1.200792 |
url = ctx.sources.ST_TONER_LITE
xmin, xmax, ymin, ymax = ax.axis()
basemap, extent = ctx.bounds2img(xmin, ymin, xmax, ymax,
zoom=zoom, url=url)
ax.imshow(basemap, extent=extent, interpolation='bilinear')
# restore original x/y limits
ax.axis((xmin... | def add_basemap(ax, zoom=12) | Adds map to a plot. | 4.752239 | 5.157954 | 0.921342 |
# make DB session
conn = connection(section=config['db_connection']['section'])
Session = sessionmaker(bind=conn)
session = Session()
# get polygon from versioned schema
if config['data_source']['oedb_data_source'] == 'versioned':
version = config['versioned']['version']
... | def get_grid_district_polygon(config, subst_id=None, projection=4326) | Get MV grid district polygon from oedb for plotting. | 3.534761 | 3.365823 | 1.050192 |
mv_load_timeseries_p = []
lv_load_timeseries_p = []
# add MV grid loads
if mode is 'mv' or mode is None:
for load in network.mv_grid.graph.nodes_by_attribute('load'):
mv_load_timeseries_p.append(load.pypsa_timeseries('p').rename(
repr(load)).to_frame().loc[times... | def _pypsa_load_timeseries(network, timesteps, mode=None) | Time series in PyPSA compatible format for load instances
Parameters
----------
network : Network
The eDisGo grid topology model overall container
timesteps : array_like
Timesteps is an array-like object with entries of type
:pandas:`pandas.Timestamp<timestamp>` specifying which... | 4.058821 | 3.996188 | 1.015673 |
mv_gen_timeseries_p_min = []
mv_gen_timeseries_p_max = []
lv_gen_timeseries_p_min = []
lv_gen_timeseries_p_max = []
# MV generator timeseries
if mode is 'mv' or mode is None:
for gen in network.mv_grid.graph.nodes_by_attribute('generator') + \
network.mv_grid.graph... | def _pypsa_generator_timeseries(network, timesteps, mode=None) | Timeseries in PyPSA compatible format for generator instances
Parameters
----------
network : Network
The eDisGo grid topology model overall container
timesteps : array_like
Timesteps is an array-like object with entries of type
:pandas:`pandas.Timestamp<timestamp>` specifying w... | 1.972297 | 1.921593 | 1.026386 |
mv_storage_timeseries_p_min = []
mv_storage_timeseries_p_max = []
# MV storage time series
if mode is 'mv' or mode is None:
for storage in network.mv_grid.graph.nodes_by_attribute('storage'):
mv_storage_timeseries_p_min.append(
storage.timeseries.p.rename(repr(... | def _pypsa_storage_timeseries(network, timesteps, mode=None) | Timeseries in PyPSA compatible format for storage instances
Parameters
----------
network : Network
The eDisGo grid topology model overall container
timesteps : array_like
Timesteps is an array-like object with entries of type
:pandas:`pandas.Timestamp<timestamp>` specifying whi... | 2.824572 | 2.824403 | 1.00006 |
if self._timeseries is None:
if isinstance(self.grid, MVGrid):
voltage_level = 'mv'
elif isinstance(self.grid, LVGrid):
voltage_level = 'lv'
ts_total = None
for sector in self.consumption.keys():
consumpti... | def timeseries(self) | Load time series
It returns the actual time series used in power flow analysis. If
:attr:`_timeseries` is not :obj:`None`, it is returned. Otherwise,
:meth:`timeseries()` looks for time series of the according sector in
:class:`~.grid.network.TimeSeries` object.
Returns
... | 4.435693 | 3.668672 | 1.209073 |
if self._timeseries_reactive is None:
# if normalized reactive power time series are given, they are
# scaled by the annual consumption; if none are given reactive
# power time series are calculated timeseries getter using a given
# power factor
... | def timeseries_reactive(self) | Reactive power time series in kvar.
Parameters
-----------
timeseries_reactive : :pandas:`pandas.Seriese<series>`
Series containing reactive power in kvar.
Returns
-------
:pandas:`pandas.Series<series>` or None
Series containing reactive power t... | 5.688306 | 5.403619 | 1.052684 |
peak_load = pd.Series(self.consumption).mul(pd.Series(
self.grid.network.config['peakload_consumption_ratio']).astype(
float), fill_value=0)
return peak_load | def peak_load(self) | Get sectoral peak load | 8.210471 | 8.086493 | 1.015331 |
if self._power_factor is None:
if isinstance(self.grid, MVGrid):
self._power_factor = self.grid.network.config[
'reactive_power_factor']['mv_load']
elif isinstance(self.grid, LVGrid):
self._power_factor = self.grid.network.conf... | def power_factor(self) | Power factor of load
Parameters
-----------
power_factor : :obj:`float`
Ratio of real power to apparent power.
Returns
--------
:obj:`float`
Ratio of real power to apparent power. If power factor is not set
it is retrieved from the ne... | 3.243488 | 2.850022 | 1.138057 |
if self._reactive_power_mode is None:
if isinstance(self.grid, MVGrid):
self._reactive_power_mode = self.grid.network.config[
'reactive_power_mode']['mv_load']
elif isinstance(self.grid, LVGrid):
self._reactive_power_mode = sel... | def reactive_power_mode(self) | Power factor mode of Load.
This information is necessary to make the load behave in an inductive
or capacitive manner. Essentially this changes the sign of the reactive
power.
The convention used here in a load is that:
- when `reactive_power_mode` is 'inductive' then Q is posi... | 2.677644 | 2.772825 | 0.965674 |
if self._timeseries is None:
# calculate time series for active and reactive power
try:
timeseries = \
self.grid.network.timeseries.generation_dispatchable[
self.type].to_frame('p')
except KeyError:
... | def timeseries(self) | Feed-in time series of generator
It returns the actual dispatch time series used in power flow analysis.
If :attr:`_timeseries` is not :obj:`None`, it is returned. Otherwise,
:meth:`timeseries` looks for time series of the according type of
technology in :class:`~.grid.network.TimeSerie... | 4.649827 | 3.647581 | 1.27477 |
if self._timeseries_reactive is None:
if self.grid.network.timeseries.generation_reactive_power \
is not None:
try:
timeseries = \
self.grid.network.timeseries.generation_reactive_power[
... | def timeseries_reactive(self) | Reactive power time series in kvar.
Parameters
-----------
timeseries_reactive : :pandas:`pandas.Seriese<series>`
Series containing reactive power in kvar.
Returns
-------
:pandas:`pandas.Series<series>` or None
Series containing reactive power t... | 4.451702 | 4.034074 | 1.103525 |
if self._timeseries is None:
# get time series for active power depending on if they are
# differentiated by weather cell ID or not
if isinstance(self.grid.network.timeseries.generation_fluctuating.
columns, pd.MultiIndex):
... | def timeseries(self) | Feed-in time series of generator
It returns the actual time series used in power flow analysis. If
:attr:`_timeseries` is not :obj:`None`, it is returned. Otherwise,
:meth:`timeseries` looks for generation and curtailment time series
of the according type of technology (and weather cell... | 3.802877 | 3.264061 | 1.165075 |
if self._timeseries_reactive is None:
# try to get time series for reactive power depending on if they
# are differentiated by weather cell ID or not
# raise warning if no time series for generator type (and weather
# cell ID) can be retrieved
... | def timeseries_reactive(self) | Reactive power time series in kvar.
Parameters
-------
:pandas:`pandas.Series<series>`
Series containing reactive power time series in kvar.
Returns
----------
:pandas:`pandas.DataFrame<dataframe>` or None
Series containing reactive power time se... | 3.51899 | 3.275979 | 1.07418 |
if self._curtailment is not None:
return self._curtailment
elif isinstance(self.grid.network.timeseries._curtailment,
pd.DataFrame):
if isinstance(self.grid.network.timeseries.curtailment.
columns, pd.MultiIndex):... | def curtailment(self) | Parameters
----------
curtailment_ts : :pandas:`pandas.Series<series>`
See class definition for details.
Returns
-------
:pandas:`pandas.Series<series>`
If self._curtailment is set it returns that. Otherwise, if
curtailment in :class:`~.grid.n... | 2.823672 | 2.458565 | 1.148504 |
# check if time series for reactive power is given, otherwise
# calculate it
if 'q' in self._timeseries.columns:
return self._timeseries
else:
self._timeseries['q'] = abs(self._timeseries.p) * self.q_sign * \
tan(acos(s... | def timeseries(self) | Time series of storage operation
Parameters
----------
ts : :pandas:`pandas.DataFrame<dataframe>`
DataFrame containing active power the storage is charged (negative)
and discharged (positive) with (on the grid side) in kW in column
'p' and reactive power in ... | 9.053712 | 8.021444 | 1.128688 |
if self.reactive_power_mode.lower() == 'inductive':
return -1
elif self.reactive_power_mode.lower() == 'capacitive':
return 1
else:
raise ValueError("Unknown value {} in reactive_power_mode".format(
self.reactive_power_mode)) | def q_sign(self) | Get the sign reactive power based on the
:attr: `_reactive_power_mode`
Returns
-------
:obj: `int` : +1 or -1 | 3.414972 | 2.724074 | 1.253626 |
if self._state != 'open':
if self._line is not None:
self._state = 'open'
self._nodes = self.grid.graph.nodes_from_line(self._line)
self.grid.graph.remove_edge(
self._nodes[0], self._nodes[1])
else:
... | def open(self) | Toggle state to open switch disconnector | 4.52685 | 4.570426 | 0.990466 |
self._state = 'closed'
self.grid.graph.add_edge(
self._nodes[0], self._nodes[1], {'line': self._line}) | def close(self) | Toggle state to closed switch disconnector | 8.593439 | 7.870216 | 1.091894 |
adj_nodes = self._grid._graph.nodes_from_line(self)
return LineString([adj_nodes[0].geom, adj_nodes[1].geom]) | def geom(self) | Provide :shapely:`Shapely LineString object<linestrings>` geometry of
:class:`Line` | 11.2879 | 9.166615 | 1.231414 |
@functools.wraps(func)
def wrapper(self, request, context):
return func(self, request, LogFieldsContext(context))
return wrapper | def wrap_context(func) | Wraps the provided servicer method by passing a wrapped context
The context is wrapped using `lookout.sdk.grpc.log_fields.LogFieldsContext`.
:param func: the servicer method to wrap_context
:returns: the wrapped servicer method | 4.302364 | 4.080059 | 1.054486 |
self._log_fields.add_fields(fields) | def add_log_fields(self, fields: Dict[str, Any]) | Add the provided log fields
If a key is already present, then it is ignored.
:param fields: the log fields to add | 13.331674 | 12.452669 | 1.070588 |
metadata = [(k, v) for k, v in self._invocation_metadata.items()
if k != LOG_FIELDS_KEY_META]
metadata.append((LOG_FIELDS_KEY_META, self._log_fields.dumps()))
return metadata | def pack_metadata(self) -> List[Tuple[str, Any]] | Packs the log fields and the invocation metadata into a new metadata
The log fields are added in the new metadata with the key
`LOG_FIELDS_KEY_META`. | 5.021659 | 2.81858 | 1.781627 |
return cls(fields=json.loads(metadata.get(LOG_FIELDS_KEY_META, '{}'))) | def from_metadata(cls, metadata: Dict[str, Any]) -> 'LogFields' | Initialize the log fields from the provided metadata
The log fields are taken from the `LOG_FIELDS_KEY_META` key of the
provided metadata. | 8.594823 | 4.835995 | 1.777261 |
for k, v in fields.items():
if k not in self._fields:
self._fields[k] = v | def add_fields(self, fields) | Add the provided log fields
If a key is already present, then it is ignored.
:param fields: the log fields to add | 2.774429 | 3.303904 | 0.839743 |
if self.network.pypsa is None:
try:
timesteps = self.network.timeseries.timeindex
self.network.pypsa = pypsa_io.to_pypsa(
self.network, mode=None, timesteps=timesteps)
except:
logging.warning(
... | def plot_mv_grid_topology(self, technologies=False, **kwargs) | Plots plain MV grid topology and optionally nodes by technology type
(e.g. station or generator).
Parameters
----------
technologies : :obj:`Boolean`
If True plots stations, generators, etc. in the grid in different
colors. If False does not plot any nodes. Defau... | 3.705071 | 3.594008 | 1.030902 |
if self.network.pypsa is not None:
try:
v_res = self.network.results.v_res()
except:
logging.warning("Voltages `pfa_v_mag_pu` from power flow "
"analysis must be available to plot them.")
return
... | def plot_mv_voltages(self, **kwargs) | Plots voltages in MV grid on grid topology plot.
For more information see :func:`edisgo.tools.plots.mv_grid_topology`. | 5.263297 | 4.727306 | 1.113382 |
if self.network.pypsa is not None and \
self.network.results.i_res is not None:
plots.mv_grid_topology(
self.network.pypsa, self.network.config,
timestep=kwargs.get('timestep', None),
line_color='loading',
node_... | def plot_mv_line_loading(self, **kwargs) | Plots relative line loading (current from power flow analysis to
allowed current) of MV lines.
For more information see :func:`edisgo.tools.plots.mv_grid_topology`. | 3.778459 | 3.425702 | 1.102973 |
if self.network.pypsa is not None and \
self.network.results.grid_expansion_costs is not None:
if isinstance(self, EDisGo):
# convert index of grid expansion costs to str
grid_expansion_costs = \
self.network.results.grid_e... | def plot_mv_grid_expansion_costs(self, **kwargs) | Plots costs per MV line.
For more information see :func:`edisgo.tools.plots.mv_grid_topology`. | 3.18045 | 2.899644 | 1.096842 |
if self.network.pypsa is not None:
plots.mv_grid_topology(
self.network.pypsa, self.network.config,
node_color='storage_integration',
filename=kwargs.get('filename', None),
grid_district_geom=kwargs.get('grid_district_geom', Tr... | def plot_mv_storage_integration(self, **kwargs) | Plots storage position in MV grid of integrated storages.
For more information see :func:`edisgo.tools.plots.mv_grid_topology`. | 4.754109 | 4.102881 | 1.158725 |
data = self.network.results.v_res()
if title is True:
if timestep is not None:
title = "Voltage histogram for time step {}".format(timestep)
else:
title = "Voltage histogram \nfor time steps {} to {}".format(
data.index... | def histogram_voltage(self, timestep=None, title=True, **kwargs) | Plots histogram of voltages.
For more information see :func:`edisgo.tools.plots.histogram`.
Parameters
----------
timestep : :pandas:`pandas.Timestamp<timestamp>` or None, optional
Specifies time step histogram is plotted for. If timestep is None
all time steps ... | 3.746971 | 3.862722 | 0.970034 |
residual_load = tools.get_residual_load_from_pypsa_network(
self.network.pypsa)
case = residual_load.apply(
lambda _: 'feedin_case' if _ < 0 else 'load_case')
if timestep is not None:
timeindex = [timestep]
else:
timeindex = self.n... | def histogram_relative_line_load(self, timestep=None, title=True,
voltage_level='mv_lv', **kwargs) | Plots histogram of relative line loads.
For more information see :func:`edisgo.tools.plots.histogram`.
Parameters
----------
Parameters
----------
timestep : :pandas:`pandas.Timestamp<timestamp>` or None, optional
Specifies time step histogram is plotted for... | 3.675094 | 3.653773 | 1.005835 |
CurtailmentControl(edisgo=self, methodology=methodology,
curtailment_timeseries=curtailment_timeseries,
**kwargs) | def curtail(self, methodology, curtailment_timeseries, **kwargs) | Sets up curtailment time series.
Curtailment time series are written into
:class:`~.grid.network.TimeSeries`. See
:class:`~.grid.network.CurtailmentControl` for more information on
parameters and methodologies. | 6.966642 | 6.807575 | 1.023366 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.