code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
p_by_carrier = network.generators_t.p.groupby\ (network.generators.carrier, axis=1).sum() capacity = network.generators.groupby("carrier").sum().at[carrier, "p_nom"] p_available = network.generators_t.p_max_pu.multiply( network.generators["p_nom"]) p_available_by_carrier = p_ava...
def curtailment(network, carrier='solar', filename=None)
Plot curtailment of selected carrier Parameters ---------- network : PyPSA network container Holds topology of grid including results from powerflow analysis carrier: str Plot curtailemt of this carrier filename: str or None Save figure in this direction Returns ...
2.522874
2.571408
0.981126
stores = network.storage_units storage_distribution = network.storage_units.p_nom_opt[stores.index]\ .groupby(network.storage_units.bus)\ .sum().reindex(network.buses.index, fill_value=0.) fig, ax = plt.subplots(1, 1) fig.set_size_inches(6, 6) msd_max = storage_distri...
def storage_distribution(network, scaling=1, filename=None)
Plot storage distribution as circles on grid nodes Displays storage size and distribution in network. Parameters ---------- network : PyPSA network container Holds topology of grid including results from powerflow analysis filename : str Specify filename If not given, f...
2.900803
2.915169
0.995072
if techs is None: techs = networkA.generators.carrier.unique() else: techs = techs n_graphs = len(techs) n_cols = n_cols if n_graphs % n_cols == 0: n_rows = n_graphs // n_cols else: n_rows = n_graphs // n_cols + 1 fig, axes = plt.subplots(nrows=n_rows,...
def gen_dist_diff( networkA, networkB, techs=None, snapshot=0, n_cols=3, gen_size=0.2, filename=None, buscmap=plt.cm.jet)
Difference in generation distribution Green/Yellow/Red colors mean that the generation at a location is bigger with switches than without Blue colors mean that the generation at a location is smaller with switches than without Parameters ---------- networkA : PyPSA network container ...
2.029393
2.083839
0.973872
if techs is None: techs = network.generators.carrier.unique() else: techs = techs n_graphs = len(techs) n_cols = n_cols if n_graphs % n_cols == 0: n_rows = n_graphs // n_cols else: n_rows = n_graphs // n_cols + 1 fig, axes = plt.subplots(nrows=n_rows, ...
def gen_dist( network, techs=None, snapshot=1, n_cols=3, gen_size=0.2, filename=None)
Generation distribution Parameters ---------- network : PyPSA network container Holds topology of grid including results from powerflow analysis techs : dict type of technologies which shall be plotted snapshot : int snapshot n_cols : int number of columns of the...
2.590289
2.620305
0.988545
if techs: gens = network.generators[network.generators.carrier.isin(techs)] elif techs is None: gens = network.generators techs = gens.carrier.unique() if item == 'capacity': dispatch = gens.p_nom.groupby([network.generators.bus, ...
def nodal_gen_dispatch( network, networkB=None, techs=['wind_onshore', 'solar'], item='energy', direction=None, scaling=1, filename=None)
Plot nodal dispatch or capacity. If networkB is given, difference in dispatch is plotted. Parameters ---------- network : PyPSA network container Holds topology of grid including results from powerflow analysis networkB : PyPSA network container If given and item is 'energy', di...
2.822678
2.758387
1.023307
fig, ax = plt.subplots(1, 1) gen = network.generators_t.p.groupby(network.generators.bus, axis=1).sum() load = network.loads_t.p.groupby(network.loads.bus, axis=1).sum() if snapshot == 'all': diff = (gen - load).sum() else: timestep = network.snapshots[snapshot] dif...
def nodal_production_balance( network, snapshot='all', scaling=0.00001, filename=None)
Plots the nodal difference between generation and consumption. Parameters ---------- network : PyPSA network container Holds topology of grid including results from powerflow analysis snapshot : int or 'all' Snapshot to plot. default 'all' scaling : int Scaling t...
3.276385
3.349572
0.97815
sbatt = network.storage_units.index[(network.storage_units.p_nom_opt>1) & (network.storage_units.capital_cost>10) & (network.storage_units.max_hours==6)] shydr = network.storage_units.index[(network.storage_units.p_nom_opt>1) & ...
def storage_soc_sorted(network, filename = None)
Plots the soc (state-pf-charge) of extendable storages Parameters ---------- network : PyPSA network container Holds topology of grid including results from powerflow analysis filename : path to folder
1.991628
2.011743
0.990001
# logger.debug("StateMachineEditionChangeHistory register state_machine old/new sm_id %s/%s" % # (self.__my_selected_sm_id, self.model.selected_state_machine_id)) # relieve old models if self.__my_selected_sm_id is not None: # no old models available s...
def register(self)
Change the state machine that is observed for new selected states to the selected state machine. :return:
4.10946
3.845108
1.06875
shortcut_manager.add_callback_for_action("undo", self.undo) shortcut_manager.add_callback_for_action("redo", self.redo)
def register_actions(self, shortcut_manager)
Register callback methods for triggered actions :param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager:
3.688374
3.062398
1.204407
# TODO re-organize as request to controller which holds source-editor-view or any parent to it for key, tab in gui_singletons.main_window_controller.get_controller('states_editor_ctrl').tabs.items(): if tab['controller'].get_controller('source_ctrl') is not None and \ ...
def undo(self, key_value, modifier_mask)
Undo for selected state-machine if no state-source-editor is open and focused in states-editor-controller. :return: True if a undo was performed, False if focus on source-editor. :rtype: bool
6.222304
5.263705
1.182115
if self.has_error: exception_data = self._raw.get("exception", {}) return exception_data.get("message") return None
def exception_message(self) -> Union[str, None]
On Lavalink V3, if there was an exception during a load or get tracks call this property will be populated with the error message. If there was no error this property will be ``None``.
4.908858
4.834388
1.015404
self.__check_node_ready() url = self._uri + quote(str(query)) data = await self._get(url) if isinstance(data, dict): return LoadResult(data) elif isinstance(data, list): modified_data = { "loadType": LoadType.V2_COMPAT, ...
async def load_tracks(self, query) -> LoadResult
Executes a loadtracks request. Only works on Lavalink V3. Parameters ---------- query : str Returns ------- LoadResult
5.04823
5.616357
0.898844
if not self._warned: log.warn("get_tracks() is now deprecated. Please switch to using load_tracks().") self._warned = True result = await self.load_tracks(query) return result.tracks
async def get_tracks(self, query) -> Tuple[Track, ...]
Gets tracks from lavalink. Parameters ---------- query : str Returns ------- Tuple[Track, ...]
4.483798
4.900452
0.914976
rel_path = os.path.join(*rel_path) target_path = os.path.join("share", *rel_path.split(os.sep)[1:]) # remove source/ (package_dir) if "path_to_file" in kwargs and kwargs["path_to_file"]: source_files = [rel_path] target_path = os.path.dirname(target_path) else: source_files...
def get_data_files_tuple(*rel_path, **kwargs)
Return a tuple which can be used for setup.py's data_files :param tuple path: List of path elements pointing to a file or a directory of files :param dict kwargs: Set path_to_file to True is `path` points to a file :return: tuple of install directory and list of source files :rtype: tuple(str, [str])
3.147067
2.813834
1.118427
result_list = list() rel_root_dir = os.path.join(*rel_root_path) share_target_root = os.path.join("share", kwargs.get("share_target_root", "rafcon")) distutils.log.debug("recursively generating data files for folder '{}' ...".format( rel_root_dir)) for dir_, _, files in os.walk(rel_roo...
def get_data_files_recursively(*rel_root_path, **kwargs)
Adds all files of the specified path to a data_files compatible list :param tuple rel_root_path: List of path elements pointing to a directory of files :return: list of tuples of install directory and list of source files :rtype: list(tuple(str, [str]))
3.211619
3.237546
0.991992
assets_folder = path.join('source', 'rafcon', 'gui', 'assets') share_folder = path.join(assets_folder, 'share') themes_folder = path.join(share_folder, 'themes', 'RAFCON') examples_folder = path.join('share', 'examples') libraries_folder = path.join('share', 'libraries') gui_data_files = [...
def generate_data_files()
Generate the data_files list used in the setup function :return: list of tuples of install directory and list of source files :rtype: list(tuple(str, [str]))
2.764007
2.734873
1.010653
# Allow to handle a subset of events while having a grabbed tool (between a button press & release event) suppressed_grabbed_tool = None if event.type in (Gdk.EventType.SCROLL, Gdk.EventType.KEY_PRESS, Gdk.EventType.KEY_RELEASE): suppressed_grabbed_tool = self._grabbed_tool ...
def handle(self, event)
Handle the event by calling each tool until the event is handled or grabbed. If a tool is returning True on a button press event, the motion and button release events are also passed to this
4.644051
4.386493
1.058716
view = self.view if self._move_name_v: yield InMotion(self._item, view) else: selected_items = set(view.selected_items) for item in selected_items: if not isinstance(item, Item): continue yield InMo...
def movable_items(self)
Filter selection Filter items of selection that cannot be moved (i.e. are not instances of `Item`) and return the rest.
6.515059
5.83957
1.115674
if event.get_button()[1] not in self._buttons: return False # Only handle events for registered buttons (left mouse clicks) if event.get_state()[1] & constants.RUBBERBAND_MODIFIER: return False # Mouse clicks with pressed shift key are handled in another tool ...
def on_button_press(self, event)
Select items When the mouse button is pressed, the selection is updated. :param event: The button event
6.300363
6.429091
0.979977
affected_models = {} for inmotion in self._movable_items: inmotion.move((event.x, event.y)) rel_pos = gap_helper.calc_rel_pos_to_parent(self.view.canvas, inmotion.item, inmotion.item.handles()[NW]) if i...
def on_button_release(self, event)
Write back changes If one or more items have been moved, the new position are stored in the corresponding meta data and a signal notifying the change is emitted. :param event: The button event
3.030632
3.005596
1.00833
if not items: return items top_most_item = items[0] # If the hovered item is e.g. a connection, we need to get the parental state top_most_state_v = top_most_item if isinstance(top_most_item, StateView) else top_most_item.parent state = top_most_state_v.mode...
def _filter_library_state(self, items)
Filters out child elements of library state when they cannot be hovered Checks if hovered item is within a LibraryState * if not, the list is returned unfiltered * if so, STATE_SELECTION_INSIDE_LIBRARY_STATE_ENABLED is checked * if enabled, the library is selected (instead of the st...
5.132707
4.227069
1.214247
items = self._filter_library_state(items) if not items: return items top_most_item = items[0] second_top_most_item = items[1] if len(items) > 1 else None # States/Names take precedence over connections if the connections are on the same hierarchy and if ther...
def _filter_hovered_items(self, items, event)
Filters out items that cannot be hovered :param list items: Sorted list of items beneath the cursor :param Gtk.Event event: Motion event :return: filtered items :rtype: list
4.152774
4.124651
1.006818
self.queue_draw(self.view) x0, y0, x1, y1 = self.x0, self.y0, self.x1, self.y1 rectangle = (min(x0, x1), min(y0, y1), abs(x1 - x0), abs(y1 - y0)) selected_items = self.view.get_items_in_rectangle(rectangle, intersect=False) self.view.handle_new_selection(selected_items) ...
def on_button_release(self, event)
Select or deselect rubber banded groups of items The selection of elements is prior and never items are selected or deselected at the same time.
2.944931
2.834742
1.038871
if not event.get_button()[1] == 1: # left mouse button return False view = self.view if isinstance(view.hovered_item, StateView): distance = view.hovered_item.border_width / 2. item, handle = HandleFinder(view.hovered_item, view).get_handle_at_point...
def on_button_press(self, event)
Handle button press events. If the (mouse) button is pressed on top of a Handle (item.Handle), that handle is grabbed and can be dragged around.
4.718287
4.486949
1.051558
item = self.grabbed_item handle = self.grabbed_handle pos = event.x, event.y self.motion_handle = HandleInMotion(item, handle, self.view) self.motion_handle.GLUE_DISTANCE = self._parent_state_v.border_width self.motion_handle.start_move(pos)
def _set_motion_handle(self, event)
Sets motion handle to currently grabbed handle
7.341442
6.443148
1.139418
if self._is_transition: self._connection_v = TransitionPlaceholderView(self._parent_state_v.hierarchy_level) else: self._connection_v = DataFlowPlaceholderView(self._parent_state_v.hierarchy_level) self.view.canvas.add(self._connection_v, self._parent_state_v)
def _create_temporary_connection(self)
Creates a placeholder connection view :return: New placeholder connection :rtype: rafcon.gui.mygaphas.items.connection.ConnectionPlaceholderView
6.550096
4.986767
1.313495
def sink_set_and_differs(sink_a, sink_b): if not sink_a: return False if not sink_b: return True if sink_a.port != sink_b.port: return True return False if sink_set_and_differs(old_sink, new_sink):...
def _handle_temporary_connection(self, old_sink, new_sink, of_target=True)
Connect connection to new_sink If new_sink is set, the connection origin or target will be set to new_sink. The connection to old_sink is being removed. :param gaphas.aspect.ConnectionSink old_sink: Old sink (if existing) :param gaphas.aspect.ConnectionSink new_sink: New sink (if exist...
2.567623
2.520963
1.018509
if target: handle = self._connection_v.to_handle() else: handle = self._connection_v.from_handle() port_v.add_connected_handle(handle, self._connection_v, moving=True) port_v.tmp_connect(handle, self._connection_v) self._connection_v.set_port_for_...
def _connect_temporarily(self, port_v, target=True)
Set a connection between the current connection and the given port :param rafcon.gui.mygaphas.items.ports.PortView port_v: The port to be connected :param bool target: Whether the connection origin or target should be connected
5.21373
5.215847
0.999594
if target: handle = self._connection_v.to_handle() else: handle = self._connection_v.from_handle() port_v.remove_connected_handle(handle) port_v.tmp_disconnect() self._connection_v.reset_port_for_handle(handle) # Redraw state of port to ma...
def _disconnect_temporarily(self, port_v, target=True)
Removes a connection between the current connection and the given port :param rafcon.gui.mygaphas.items.ports.PortView port_v: The port that was connected :param bool target: Whether the connection origin or target should be disconnected
6.231379
6.295002
0.989893
if not event.get_button()[1] == 1: # left mouse button return False view = self.view item, handle = HandleFinder(view.hovered_item, view).get_handle_at_point((event.x, event.y)) if not handle: # Require a handle return False # Connection hand...
def on_button_press(self, event)
Handle button press events. If the (mouse) button is pressed on top of a Handle (item.Handle), that handle is grabbed and can be dragged around.
6.199263
6.060274
1.022935
if not event.get_button()[1] == 1: # left mouse button return False view = self.view item, handle = HandleFinder(view.hovered_item, view).get_handle_at_point((event.x, event.y)) # Handle must be the end handle of a connection if not handle or not isinstanc...
def on_button_press(self, event)
Handle button press events. If the (mouse) button is pressed on top of a Handle (item.Handle), that handle is grabbed and can be dragged around.
5.199651
5.085186
1.022509
super(ToolBarController, self).register_view(view) self.view['button_new'].connect('clicked', self.on_button_new_clicked) self.view['button_open'].connect('clicked', self.on_button_open_clicked) self.view['button_save'].connect('clicked', self.on_button_save_clicked) sel...
def register_view(self, view)
Called when the View was registered
1.899487
1.87476
1.013189
logger.debug("Initializing LibraryManager: Loading libraries ... ") self._libraries = {} self._library_root_paths = {} self._replaced_libraries = {} self._skipped_states = [] self._skipped_library_roots = [] # 1. Load libraries from config.yaml f...
def initialize(self)
Initializes the library manager It searches through all library paths given in the config file for libraries, and loads the states. This cannot be done in the __init__ function as the library_manager can be compiled and executed by singleton.py before the state*.pys are loaded
2.384995
2.326799
1.025011
path = path.replace('"', '') path = path.replace("'", '') # Replace ~ with /home/user path = os.path.expanduser(path) # Replace environment variables path = os.path.expandvars(path) # If the path is relative, assume it is relative to the config file direc...
def _clean_path(path)
Create a fully fissile absolute system path with no symbolic links and environment variables
2.880808
2.767839
1.040815
for library_name in os.listdir(library_path): library_folder_path, library_name = self.check_clean_path_of_library(library_path, library_name) full_library_path = os.path.join(library_path, library_name) if os.path.isdir(full_library_path) and library_name[0] != '.':...
def _load_nested_libraries(self, library_path, target_dict)
Recursively load libraries within path Adds all libraries specified in a given path and stores them into the provided library dictionary. The library entries in the dictionary consist only of the path to the library in the file system. :param library_path: the path to add all libraries from ...
2.134261
2.230484
0.95686
if library_path is None or library_name is None: return None path_list = library_path.split(os.sep) target_lib_dict = self.libraries # go down the path to the correct library for path_element in path_list: if path_element not in target_lib_dict: ...
def _get_library_os_path_from_library_dict_tree(self, library_path, library_name)
Hand verified library os path from libraries dictionary tree.
2.471174
2.298716
1.075023
path = os.path.realpath(path) library_root_key = None for library_root_key, library_root_path in self._library_root_paths.items(): rel_path = os.path.relpath(path, library_root_path) if rel_path.startswith('..'): library_root_key = None ...
def _get_library_root_key_for_os_path(self, path)
Return library root key if path is within library root paths
1.990038
1.777869
1.119339
library_path = None library_name = None library_root_key = self._get_library_root_key_for_os_path(path) if library_root_key is not None: library_root_path = self._library_root_paths[library_root_key] path_elements_without_library_root = path[len(library_r...
def get_library_path_and_name_for_os_path(self, path)
Generate valid library_path and library_name The method checks if the given os path is in the list of loaded library root paths and use respective library root key/mounting point to concatenate the respective library_path and separate respective library_name. :param str path: A library os pat...
2.012537
1.983921
1.014424
if self.is_library_in_libraries(library_path, library_name): from rafcon.core.states.library_state import LibraryState return LibraryState(library_path, library_name, "0.1") else: logger.warning("Library manager will not create a library instance which is not...
def get_library_instance(self, library_path, library_name)
Generate a Library instance from within libraries dictionary tree.
6.63076
6.00289
1.104595
# originally libraries were called like this; DO NOT DELETE; interesting for performance tests # state_machine = storage.load_state_machine_from_path(lib_os_path) # return state_machine.version, state_machine.root_state # TODO observe changes on file system and update data ...
def get_library_state_copy_instance(self, lib_os_path)
A method to get a state copy of the library specified via the lib_os_path. :param lib_os_path: the location of the library to get a copy for :return:
5.376646
5.554215
0.96803
library_file_system_path = self.get_os_path_to_library(library_path, library_name)[0] shutil.rmtree(library_file_system_path) self.refresh_libraries()
def remove_library_from_file_system(self, library_path, library_name)
Remove library from hard disk.
3.392913
3.125491
1.085562
mask = network.buses.v_nom.isin(voltage_level) df = network.buses[mask] return df.index
def buses_of_vlvl(network, voltage_level)
Get bus-ids of given voltage level(s). Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA voltage_level: list Returns ------- list List containing bus-ids.
6.216528
6.58532
0.943998
mask = ((network.buses.index.isin(network.lines.bus0) | (network.buses.index.isin(network.lines.bus1))) & (network.buses.v_nom.isin(voltage_level))) df = network.buses[mask] return df.index
def buses_grid_linked(network, voltage_level)
Get bus-ids of a given voltage level connected to the grid. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA voltage_level: list Returns ------- list List containing bus-ids.
3.495089
3.614209
0.967041
# get foreign buses by country foreign_buses = network.buses[network.buses.country_code != 'DE'] network.buses = network.buses.drop( network.buses.loc[foreign_buses.index].index) # identify transborder lines (one bus foreign, one bus not) and the country # it is coming from ...
def clip_foreign(network)
Delete all components and timelines located outside of Germany. Add transborder flows divided by country of origin as network.foreign_trade. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns ------- network : :class:`pypsa.Network ...
2.524439
2.412168
1.046544
foreign_buses = network.buses[network.buses.country_code != 'DE'] foreign_lines = network.lines[network.lines.bus0.astype(str).isin( foreign_buses.index) | network.lines.bus1.astype(str).isin( foreign_buses.index)] foreign_links = network.links[network.links.bus0.astyp...
def foreign_links(network)
Change transmission technology of foreign lines from AC to DC (links). Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns ------- network : :class:`pypsa.Network Overall container of PyPSA
2.584567
2.480592
1.041915
foreign_buses = network.buses[network.buses.country_code != 'DE'] network.loads_t['q_set'][network.loads.index[ network.loads.bus.astype(str).isin(foreign_buses.index)]] = \ network.loads_t['p_set'][network.loads.index[ network.loads.bus.astype(str).isin( foreig...
def set_q_foreign_loads(network, cos_phi=1)
Set reative power timeseries of loads in neighbouring countries Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA cos_phi: float Choose ration of active and reactive power of foreign loads Returns ------- network : :class:`pypsa.Network ...
3.654483
3.682743
0.992326
mask = network.lines.bus1.isin(busids) |\ network.lines.bus0.isin(busids) return network.lines[mask]
def connected_grid_lines(network, busids)
Get grid lines connected to given buses. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA busids : list List containing bus-ids. Returns ------- :class:`pandas.DataFrame PyPSA lines.
3.824444
5.321826
0.718634
mask = (network.transformers.bus0.isin(busids)) return network.transformers[mask]
def connected_transformer(network, busids)
Get transformer connected to given buses. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA busids : list List containing bus-ids. Returns ------- :class:`pandas.DataFrame PyPSA transformer.
7.901562
10.373949
0.761674
marginal_cost_def = 10000 # network.generators.marginal_cost.max()*2 p_nom_def = network.loads_t.p_set.max().max() marginal_cost = kwargs.get('marginal_cost', marginal_cost_def) p_nom = kwargs.get('p_nom', p_nom_def) network.add("Carrier", "load") start = network.generators.index.to_ser...
def load_shedding(network, **kwargs)
Implement load shedding in existing network to identify feasibility problems Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA marginal_cost : int Marginal costs for load shedding p_nom : int Installed capacity of load shedding generato...
4.059524
3.490202
1.16312
from shapely.geometry import Point, LineString, MultiLineString from geoalchemy2.shape import from_shape, to_shape # add connection from Luebeck to Siems new_bus = str(network.buses.index.astype(np.int64).max() + 1) new_trafo = str(network.transformers.index.astype(np.int64).max() + 1) new...
def data_manipulation_sh(network)
Adds missing components to run calculations with SH scenarios. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA
2.662034
2.660653
1.000519
path = args['csv_export'] if path == False: return None if not os.path.exists(path): os.makedirs(path, exist_ok=True) network.export_to_csv_folder(path) data = pd.read_csv(os.path.join(path, 'network.csv')) data['time'] = network.results['Solver'].Time data = data.ap...
def results_to_csv(network, args, pf_solution=None)
Function the writes the calaculation results in csv-files in the desired directory. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA args: dict Contains calculation settings of appl.py pf_solution: pandas.Dataframe or None If pf was calcu...
2.705808
2.771883
0.976162
print("Performing linear OPF, {} snapshot(s) at a time:". format(group_size)) t = time.time() for i in range(int((args['end_snapshot'] - args['start_snapshot'] + 1) / group_size)): if i > 0: network.storage_units.state_of_charge_initial = network.\ ...
def parallelisation(network, args, group_size, extra_functionality=None)
Function that splits problem in selected number of snapshot groups and runs optimization successive for each group. Not useful for calculations with storage untis or extension. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA args: dict ...
4.250364
3.895481
1.091101
old_slack = network.generators.index[network. generators.control == 'Slack'][0] # check if old slack was PV or PQ control: if network.generators.p_nom[old_slack] > 50 and network.generators.\ carrier[old_slack] in ('solar', 'wind'): ...
def set_slack(network)
Function that chosses the bus with the maximum installed power as slack Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns ------- network : :class:`pypsa.Network Overall container of PyPSA
3.041092
2.898739
1.049109
network.allocation = allocation if allocation == 'p': p_sum = network.generators_t['p'].\ groupby(network.generators.bus, axis=1).sum().\ add(network.storage_units_t['p'].abs().groupby( network.storage_units.bus, axis=1).sum(), fill_value=0) q_su...
def distribute_q(network, allocation='p_nom')
Function that distributes reactive power at bus to all installed generators and storages. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA allocation: str Choose key to distribute reactive power: 'p_nom' to dirstribute via p_nom 'p' t...
2.190187
2.217782
0.987558
# Line losses # calculate apparent power S = sqrt(p² + q²) [in MW] s0_lines = ((network.lines_t.p0**2 + network.lines_t.q0**2). apply(np.sqrt)) # calculate current I = S / U [in A] i0_lines = np.multiply(s0_lines, 1000000) / \ np.multiply(network.lines.v_nom, 1000) ...
def calc_line_losses(network)
Calculate losses per line with PF result data Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA s0 : series apparent power of line i0 : series current of line -------
7.069207
6.591951
1.0724
network.lines["v_nom"] = network.lines.bus0.map(network.buses.v_nom) network.lines.loc[(network.lines.v_nom == 110), 'capital_cost'] = cost110 * network.lines.length /\ args['branch_capacity_factor']['HV'] network.lines.loc[(networ...
def set_line_costs(network, args, cost110=230, cost220=290, cost380=85, costDC=375)
Set capital costs for extendable lines in respect to PyPSA [€/MVA] Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA args: dict containing settings from appl.py cost110 : capital costs per km for 110kV lines and cables default: 230€/MVA/km,...
2.744699
2.48159
1.106025
network.transformers["v_nom0"] = network.transformers.bus0.map( network.buses.v_nom) network.transformers["v_nom1"] = network.transformers.bus1.map( network.buses.v_nom) network.transformers.loc[(network.transformers.v_nom0 == 110) & ( network.transformers.v_nom1 == 220), 'capi...
def set_trafo_costs(network, args, cost110_220=7500, cost110_380=17333, cost220_380=14166)
Set capital costs for extendable transformers in respect to PyPSA [€/MVA] Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA cost110_220 : capital costs for 110/220kV transformer default: 7500€/MVA, source: costs for extra trafo in ...
2.134501
2.015058
1.059275
# Add costs for DC-converter network.links.capital_cost = network.links.capital_cost + 400000 # Calculate present value of an annuity (PVA) PVA = (1 / p) - (1 / (p * (1 + p) ** T)) # Apply function on lines, links, trafos and storages # Storage costs are already annuized yearly networ...
def convert_capital_costs(network, start_snapshot, end_snapshot, p=0.05, T=40)
Convert capital_costs to fit to pypsa and caluculated time Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA p : interest rate, default 0.05 T : number of periods, default 40 years (source: StromNEV Anlage 1) -------
3.175518
3.078729
1.031438
if carrier == 'residual load': power_plants = network.generators[network.generators.carrier. isin(['solar', 'wind', 'wind_onshore'])] power_plants_t = network.generators.p_nom[power_plants.index] * \ network.generators_t.p_ma...
def find_snapshots(network, carrier, maximum = True, minimum = True, n = 3)
Function that returns snapshots with maximum and/or minimum feed-in of selected carrier. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA carrier: str Selected carrier of generators maximum: bool Choose if timestep of maximal feed-in is r...
2.63279
2.412617
1.091259
carrier = ['coal', 'biomass', 'gas', 'oil', 'waste', 'lignite', 'uranium', 'geothermal'] data = {'start_up_cost':[77, 57, 42, 57, 57, 77, 50, 57], #€/MW 'start_up_fuel':[4.3, 2.8, 1.45, 2.8, 2.8, 4.3, 16.7, 2.8], #MWh/MW 'min_up_time':[5, 2, 3, 2, 2, 5, 12, 2]...
def ramp_limits(network)
Add ramping constraints to thermal power plants. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns -------
2.672175
2.637323
1.013215
if not jsonpath == None: with open(jsonpath) as f: args = json.load(f) return args
def get_args_setting(args, jsonpath='scenario_setting.json')
Get and open json file with scenaio settings of eTraGo ``args``. The settings incluedes all eTraGo specific settings of arguments and parameters for a reproducible calculation. Parameters ---------- json_file : str Default: ``scenario_setting.json`` Name of scenario setting json fi...
4.016329
6.283728
0.639163
transborder_lines_0 = network.lines[network.lines['bus0'].isin( network.buses.index[network.buses['country_code'] != 'DE'])].index transborder_lines_1 = network.lines[network.lines['bus1'].isin( network.buses.index[network.buses['country_code']!= 'DE'])].index #set country tag...
def set_line_country_tags(network)
Set country tag for AC- and DC-lines. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA
1.508114
1.507689
1.000282
network.lines["s_nom_total"] = network.lines.s_nom.copy() network.transformers["s_nom_total"] = network.transformers.s_nom.copy() network.lines["v_nom"] = network.lines.bus0.map( network.buses.v_nom) network.transformers["v_nom0"] = network.transformers.bus0.map( network.buses.v...
def set_branch_capacity(network, args)
Set branch capacity factor of lines and transformers, different factors for HV (110kV) and eHV (220kV, 380kV). Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA args: dict Settings in appl.py
2.290634
1.819938
1.258633
lines_snom = network.lines.s_nom.sum() links_pnom = network.links.p_nom.sum() def _rule(m): lines_opt = sum(m.passive_branch_s_nom[index] for index in m.passive_branch_s_nom_index) links_opt = sum(m.link_p_nom[index] ...
def max_line_ext(network, snapshots, share=1.01)
Sets maximal share of overall network extension as extra functionality in LOPF Parameters ---------- share: float Maximal share of network extension in p.u.
3.899347
4.03535
0.966297
renewables = ['wind_onshore', 'wind_offshore', 'biomass', 'solar', 'run_of_river'] res = list(network.generators.index[ network.generators.carrier.isin(renewables)]) total = list(network.generators.index) snapshots = network.snapshots def _rule(m): ...
def min_renewable_share(network, snapshots, share=0.72)
Sets minimal renewable share of generation as extra functionality in LOPF Parameters ---------- share: float Minimal share of renewable generation in p.u.
3.988125
3.975637
1.003141
renewables = ['wind_onshore', 'wind_offshore', 'solar'] res = list(network.generators.index[ (network.generators.carrier.isin(renewables)) & (network.generators.bus.astype(str).isin(network.buses.index[network.buses.country_code == 'DE']))]) # network.i...
def max_curtailment(network, snapshots, curtail_max=0.03)
each RE can only be curtailed (over all snapshots) with respect to curtail_max Parameters ---------- curtail_max: float maximal curtailment per power plant in p.u.
4.724497
4.670208
1.011625
guild_count = 1e10 least_used = None for node in _nodes: guild_ids = node.player_manager.guild_ids if ignore_ready_status is False and not node.ready.is_set(): continue elif len(guild_ids) < guild_count: guild_count = len(guild_ids) least_us...
def get_node(guild_id: int, ignore_ready_status: bool = False) -> Node
Gets a node based on a guild ID, useful for noding separation. If the guild ID does not already have a node association, the least used node is returned. Skips over nodes that are not yet ready. Parameters ---------- guild_id : int ignore_ready_status : bool Returns ------- Node
3.258406
3.665847
0.888855
node = get_node(guild_id) voice_ws = node.get_voice_ws(guild_id) await voice_ws.voice_state(guild_id, channel_id)
async def join_voice(guild_id: int, channel_id: int)
Joins a voice channel by ID's. Parameters ---------- guild_id : int channel_id : int
3.777473
3.876988
0.974332
self._is_shutdown = False combo_uri = "ws://{}:{}".format(self.host, self.rest) uri = "ws://{}:{}".format(self.host, self.port) log.debug( "Lavalink WS connecting to %s or %s with headers %s", combo_uri, uri, self.headers ) tasks = tuple({self._mul...
async def connect(self, timeout=None)
Connects to the Lavalink player event websocket. Parameters ---------- timeout : int Time after which to timeout on attempting to connect to the Lavalink websocket, ``None`` is considered never, but the underlying code may stop trying past a certain point. ...
4.574697
4.415573
1.036037
while self._ws.open and self._is_shutdown is False: try: data = json.loads(await self._ws.recv()) except websockets.ConnectionClosed: break raw_op = data.get("op") try: op = LavalinkIncomingOp(raw_op) ...
async def listener(self)
Listener task for receiving ops from Lavalink.
3.863347
3.479713
1.110249
voice_ws = self.get_voice_ws(guild_id) await voice_ws.voice_state(guild_id, channel_id)
async def join_voice_channel(self, guild_id, channel_id)
Alternative way to join a voice channel if node is known.
3.850003
3.239176
1.188575
self._is_shutdown = True self.ready.clear() self.update_state(NodeState.DISCONNECTING) await self.player_manager.disconnect() if self._ws is not None and self._ws.open: await self._ws.close() if self._listener_task is not None and not self.loop.is...
async def disconnect(self)
Shuts down and disconnects the websocket.
4.889569
4.790731
1.020631
# prepare State Type Change ComboBox super(StateOverviewController, self).register_view(view) self.allowed_state_classes = self.get_allowed_state_classes(self.model.state) view['entry_name'].connect('focus-out-event', self.on_focus_out) view['entry_name'].connect('key-p...
def register_view(self, view)
Called when the View was registered Can be used e.g. to connect signals. Here, the destroy signal is connected to close the application :param rafcon.gui.views.state_editor.overview.StateOverviewView view: A state overview view instance
3.006519
2.978143
1.009528
logger.debug("Starting execution of {0}{1}".format(self, " (backwards)" if self.backward_execution else "")) self.setup_run() # data to be accessed by the decider state child_errors = {} final_outcomes_dict = {} decider_state = self.states[UNIQUE_DECIDER_STATE_I...
def run(self)
This defines the sequence of actions that are taken when the barrier concurrency state is executed :return:
3.865596
3.861499
1.001061
decider_state.state_execution_status = StateExecutionStatus.ACTIVE # forward the decider specific data decider_state.child_errors = child_errors decider_state.final_outcomes_dict = final_outcomes_dict # standard state execution decider_state.input_data = self.get...
def run_decider_state(self, decider_state, child_errors, final_outcomes_dict)
Runs the decider state of the barrier concurrency state. The decider state decides on which outcome the barrier concurrency is left. :param decider_state: the decider state of the barrier concurrency state :param child_errors: error of the concurrent branches :param final_outcomes_dict:...
3.265498
3.549058
0.920103
valid, message = super(BarrierConcurrencyState, self)._check_transition_validity(check_transition) if not valid: return False, message # Only the following transitions are allowed in barrier concurrency states: # - Transitions from the decider state to the parent st...
def _check_transition_validity(self, check_transition)
Transition of BarrierConcurrencyStates must least fulfill the condition of a ContainerState. Start transitions are forbidden in the ConcurrencyState. :param check_transition: the transition to check for validity :return:
3.64205
3.404873
1.069658
state_id = super(BarrierConcurrencyState, self).add_state(state) if not storage_load and not self.__init_running and not state.state_id == UNIQUE_DECIDER_STATE_ID: # the transitions must only be created for the initial add_state call and not during each load procedure fo...
def add_state(self, state, storage_load=False)
Overwrite the parent class add_state method Add automatic transition generation for the decider_state. :param state: The state to be added :return:
6.831786
6.517438
1.048232
# First safely remove all existing states (recursively!), as they will be replaced state_ids = list(self.states.keys()) for state_id in state_ids: # Do not remove decider state, if teh new list of states doesn't contain an alternative one if state_id == UNIQUE_DE...
def states(self, states)
Overwrite the setter of the container state base class as special handling for the decider state is needed. :param states: the dictionary of new states :raises exceptions.TypeError: if the states parameter is not of type dict
4.354705
3.969538
1.097031
if state_id == UNIQUE_DECIDER_STATE_ID and force is False: raise AttributeError("You are not allowed to delete the decider state.") else: return ContainerState.remove_state(self, state_id, recursive=recursive, force=force, destroy=destroy)
def remove_state(self, state_id, recursive=True, force=False, destroy=True)
Overwrite the parent class remove state method by checking if the user tries to delete the decider state :param state_id: the id of the state to remove :param recursive: a flag to indicate a recursive disassembling of all substates :param force: a flag to indicate forcefully deletion of all sta...
4.691826
3.779212
1.241483
return_value = None for state_id, name_outcome_tuple in self.final_outcomes_dict.items(): if name_outcome_tuple[0] == name: return_value = name_outcome_tuple[1] break return return_value
def get_outcome_for_state_name(self, name)
Returns the final outcome of the child state specified by name. Note: This is utility function that is used by the programmer to make a decision based on the final outcome of its child states. A state is not uniquely specified by the name, but as the programmer normally does not want to use sta...
2.881663
3.218688
0.895291
return_value = None for s_id, name_outcome_tuple in self.final_outcomes_dict.items(): if s_id == state_id: return_value = name_outcome_tuple[1] break return return_value
def get_outcome_for_state_id(self, state_id)
Returns the final outcome of the child state specified by the state_id. :param state_id: The id of the state to get the final outcome for. :return:
3.421376
4.010911
0.853017
return_value = None for state_id, name_outcome_tuple in self.child_errors.items(): if name_outcome_tuple[0] == name: return_value = name_outcome_tuple[1] break return return_value
def get_errors_for_state_name(self, name)
Returns the error message of the child state specified by name. Note: This is utility function that is used by the programmer to make a decision based on the final outcome of its child states. A state is not uniquely specified by the name, but as the programmer normally does not want to use sta...
3.729596
4.032992
0.924771
assert isinstance(controller, ExtendedController) controller.parent = self self.__child_controllers[key] = controller if self.__shortcut_manager is not None and controller not in self.__action_registered_controllers: controller.register_actions(self.__shortcut_manage...
def add_controller(self, key, controller)
Add child controller The passed controller is registered as child of self. The register_actions method of the child controller is called, allowing the child controller to register shortcut callbacks. :param key: Name of the controller (unique within self), to later access it again :par...
4.094392
3.134997
1.306028
# Get name of controller if isinstance(controller, ExtendedController): # print(self.__class__.__name__, " remove ", controller.__class__.__name__) for key, child_controller in self.__child_controllers.items(): if controller is child_controller: ...
def remove_controller(self, controller)
Remove child controller and destroy it Removes all references to the child controller and calls destroy() on the controller. :param str | ExtendedController controller: Either the child controller object itself or its registered name :return: Whether the controller was existing :rtype:...
3.072303
2.814634
1.091546
assert isinstance(shortcut_manager, ShortcutManager) self.__shortcut_manager = shortcut_manager for controller in list(self.__child_controllers.values()): if controller not in self.__action_registered_controllers: try: controller.register...
def register_actions(self, shortcut_manager)
Register callback methods for triggered actions in all child controllers. :param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings between shortcuts and actions.
2.712991
2.625838
1.03319
self.disconnect_all_signals() controller_names = [key for key in self.__child_controllers] for controller_name in controller_names: self.remove_controller(controller_name) self.relieve_all_models() if self.parent: self.__parent = None if s...
def destroy(self)
Recursively destroy all Controllers The method remove all controllers, which calls the destroy method of the child controllers. Then, all registered models are relieved and and the widget hand by the initial view argument is destroyed.
6.296669
5.793082
1.086929
self.__registered_models.add(model) return super(ExtendedController, self).observe_model(model)
def observe_model(self, model)
Make this model observable within the controller The method also keeps track of all observed models, in order to be able to relieve them later on. :param gtkmvc3.Model model: The model to be observed
7.207209
8.322705
0.86597
self.__registered_models.remove(model) return super(ExtendedController, self).relieve_model(model)
def relieve_model(self, model)
Do no longer observe the model The model is also removed from the internal set of tracked models. :param gtkmvc3.Model model: The model to be relieved
6.726155
7.644793
0.879835
map(self.relieve_model, list(self.__registered_models)) self.__registered_models.clear()
def relieve_all_models(self)
Relieve all registered models The method uses the set of registered models to relieve them.
6.045024
4.621396
1.308052
old_data_type = self.data_type self.data_type = data_type if default_value is None: default_value = self.default_value if type_helpers.type_inherits_of_type(type(default_value), self._data_type): self._default_value = default_value else: ...
def change_data_type(self, data_type, default_value=None)
This method changes both the data type and default value. If one of the parameters does not fit, an exception is thrown and no property is changed. Using this method ensures a consistent data type and default value and only notifies once. :param data_type: The new data type :param defau...
2.050031
2.176552
0.941871
if data_type is None: data_type = self.data_type if default_value is not None: # If the default value is passed as string, we have to convert it to the data type if isinstance(default_value, string_types): if len(default_value) > 1 and defaul...
def check_default_value(self, default_value, data_type=None)
Check whether the passed default value suits to the passed data type. If no data type is passed, the data type of the data port is used. If the default value does not fit, an exception is thrown. If the default value is of type string, it is tried to convert that value to the data type. :param ...
2.796844
2.732151
1.023678
user_input = input(query + ': ') if len(user_input) == 0: user_input = default_path if not user_input or not os.path.isdir(user_input): return None return user_input
def open_folder_cmd_line(query, default_path=None)
Queries the user for a path to open :param str query: Query that asks the user for a specific folder path to be opened :param str default_path: Path to use if the user doesn't specify a path :return: Input path from the user or `default_path` if nothing is specified or None if path does not exist ...
2.372576
2.573534
0.921913
default = None if default_name and default_path: default = os.path.join(default_path, default_name) user_input = input(query + ' [default {}]: '.format(default)) if len(user_input) == 0: user_input = default if not user_input: return None if not os.path.isdir(user_i...
def create_folder_cmd_line(query, default_name=None, default_path=None)
Queries the user for a path to be created :param str query: Query that asks the user for a specific folder path to be created :param str default_name: Default name of the folder to be created :param str default_path: Path in which the folder is created if the user doesn't specify a path :return: Input...
2.08986
2.307019
0.905871
default = None if default_name and default_path: default = os.path.join(default_path, default_name) user_input = input(query + ' [default {}]: '.format(default)) if len(user_input) == 0: user_input = default if not user_input or not os.path.isdir(os.path.dirname(user_input)): ...
def save_folder_cmd_line(query, default_name=None, default_path=None)
Queries the user for a path or file to be saved into The folder or file has not to be created already and will not be created by this function. The parent directory of folder and file has to exist otherwise the function will return None. :param str query: Query that asks the user for a specific folder/fil...
2.303898
2.54501
0.905261
super(StateTransitionsListController, self).register_view(view) def cell_text(column, cell_renderer, model, iter, data): t_id = model.get_value(iter, self.ID_STORAGE_ID) in_external = 'external' if model.get_value(iter, self.IS_EXTERNAL_STORAGE_ID) else 'internal' ...
def register_view(self, view)
Called when the View was registered
2.000536
1.998949
1.000794
assert model.transition.parent is self.model.state or model.transition.parent is self.model.parent.state gui_helper_state_machine.delete_core_element_of_model(model)
def remove_core_element(self, model)
Remove respective core element of handed transition model :param TransitionModel model: Transition model which core element should be removed :return:
10.297846
10.124716
1.0171
model = self.model # print("clean data base") ### FOR COMBOS # internal transitions # - take all internal states # - take all not used internal outcomes of this states # external transitions # - take all external states # - take all ex...
def _update_internal_data_base(self)
Updates Internal combo knowledge for any actual transition by calling get_possible_combos_for_transition- function for those.
2.209808
2.128923
1.037993
shortcut_manager.add_callback_for_action("delete", self.trans_list_ctrl.remove_action_callback) shortcut_manager.add_callback_for_action("add", self.trans_list_ctrl.add_action_callback)
def register_actions(self, shortcut_manager)
Register callback methods for triggered actions :param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager:
4.755438
4.105953
1.158181
if dirty_lock_file is not None \ and not dirty_lock_file == os.path.join(sm_path, dirty_lock_file.split(os.sep)[-1]): logger.debug("Move dirty lock from root tmp folder {0} to state machine folder {1}" "".format(dirty_lock_file, os.path.join(sm_path, dirty_lock_file.spl...
def move_dirty_lock_file(dirty_lock_file, sm_path)
Move the dirt_lock file to the sm_path and thereby is not found by auto recovery of backup anymore
2.296429
2.238973
1.025662
auto_backup_meta_file = os.path.join(self._tmp_storage_path, FILE_NAME_AUTO_BACKUP) storage.storage_utils.write_dict_to_json(self.meta, auto_backup_meta_file)
def write_backup_meta_data(self)
Write the auto backup meta data into the current tmp-storage path
5.336219
3.804453
1.402625