sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def update_port_side(self): """Updates the initial position of the port The port side is ignored but calculated from the port position. Then the port position is limited to the four side lines of the state. """ from rafcon.utils.geometry import point_left_of_line p = (self._initial_pos.x, self._initial_pos.y) nw_x, nw_y, se_x, se_y = self.get_adjusted_border_positions() if point_left_of_line(p, (nw_x, nw_y), (se_x, se_y)): # upper right triangle of state if point_left_of_line(p, (nw_x, se_y), (se_x, nw_y)): # upper quarter triangle of state self._port.side = SnappedSide.TOP self.limit_pos(p[0], se_x, nw_x) else: # right quarter triangle of state self._port.side = SnappedSide.RIGHT self.limit_pos(p[1], se_y, nw_y) else: # lower left triangle of state if point_left_of_line(p, (nw_x, se_y), (se_x, nw_y)): # left quarter triangle of state self._port.side = SnappedSide.LEFT self.limit_pos(p[1], se_y, nw_y) else: # lower quarter triangle of state self._port.side = SnappedSide.BOTTOM self.limit_pos(p[0], se_x, nw_x) self.set_nearest_border()
Updates the initial position of the port The port side is ignored but calculated from the port position. Then the port position is limited to the four side lines of the state.
entailment
def _solve(self): """ Calculates the correct position of the port and keeps it aligned with the binding rect """ # As the size of the containing state may has changed we need to update the distance to the border self.update_distance_to_border() px, py = self._point nw_x, nw_y, se_x, se_y = self.get_adjusted_border_positions() # If the port is located in one of the corners it is possible to move in two directions if ((self._initial_pos.x == nw_x and self._initial_pos.y == nw_y) or (self._initial_pos.x == se_x and self._initial_pos.y == nw_y) or (self._initial_pos.x == se_x and self._initial_pos.y == se_y) or (self._initial_pos.x == nw_x and self._initial_pos.y == se_y)): self.limit_pos(px, se_x, nw_x) self.limit_pos(py, se_y, nw_y) # If port movement starts at LEFT position, keep X position at place and move Y elif self._initial_pos.x == nw_x: _update(px, nw_x) self.limit_pos(py, se_y, nw_y) self._port.side = SnappedSide.LEFT # If port movement starts at TOP position, keep Y position at place and move X elif self._initial_pos.y == nw_y: _update(py, nw_y) self.limit_pos(px, se_x, nw_x) self._port.side = SnappedSide.TOP # If port movement starts at RIGHT position, keep X position at place and move Y elif self._initial_pos.x == se_x: _update(px, se_x) self.limit_pos(py, se_y, nw_y) self._port.side = SnappedSide.RIGHT # If port movement starts at BOTTOM position, keep Y position at place and move X elif self._initial_pos.y == se_y: _update(py, se_y) self.limit_pos(px, se_x, nw_x) self._port.side = SnappedSide.BOTTOM # If containing state has been resized, snap ports accordingly to border else: self.set_nearest_border() # Update initial position for next reference _update(self._initial_pos.x, deepcopy(px.value)) _update(self._initial_pos.y, deepcopy(py.value))
Calculates the correct position of the port and keeps it aligned with the binding rect
entailment
def limit_pos(p, se_pos, nw_pos): """ Limits position p to stay inside containing state :param p: Position to limit :param se_pos: Bottom/Right boundary :param nw_pos: Top/Left boundary :return: """ if p > se_pos: _update(p, se_pos) elif p < nw_pos: _update(p, nw_pos)
Limits position p to stay inside containing state :param p: Position to limit :param se_pos: Bottom/Right boundary :param nw_pos: Top/Left boundary :return:
entailment
def get_adjusted_border_positions(self): """ Calculates the positions to limit the port movement to :return: Adjusted positions nw_x, nw_y, se_x, se_y """ nw_x, nw_y = self._rect[0] se_x, se_y = self._rect[1] nw_x += self._distance_to_border nw_y += self._distance_to_border se_x -= self._distance_to_border se_y -= self._distance_to_border return nw_x, nw_y, se_x, se_y
Calculates the positions to limit the port movement to :return: Adjusted positions nw_x, nw_y, se_x, se_y
entailment
def set_nearest_border(self): """Snaps the port to the correct side upon state size change """ px, py = self._point nw_x, nw_y, se_x, se_y = self.get_adjusted_border_positions() if self._port.side == SnappedSide.RIGHT: _update(px, se_x) elif self._port.side == SnappedSide.BOTTOM: _update(py, se_y) elif self._port.side == SnappedSide.LEFT: _update(px, nw_x) elif self._port.side == SnappedSide.TOP: _update(py, nw_y)
Snaps the port to the correct side upon state size change
entailment
def remove_obsolete_folders(states, path): """Removes obsolete state machine folders This function removes all folders in the file system folder `path` that do not belong to the states given by `states`. :param list states: the states that should reside in this very folder :param str path: the file system path to be checked for valid folders """ elements_in_folder = os.listdir(path) # find all state folder elements in system path state_folders_in_file_system = [] for folder_name in elements_in_folder: if os.path.exists(os.path.join(path, folder_name, FILE_NAME_CORE_DATA)) or \ os.path.exists(os.path.join(path, folder_name, FILE_NAME_CORE_DATA_OLD)): state_folders_in_file_system.append(folder_name) # remove elements used by existing states and storage format for state in states: storage_folder_for_state = get_storage_id_for_state(state) if storage_folder_for_state in state_folders_in_file_system: state_folders_in_file_system.remove(storage_folder_for_state) # remove the remaining state folders for folder_name in state_folders_in_file_system: shutil.rmtree(os.path.join(path, folder_name))
Removes obsolete state machine folders This function removes all folders in the file system folder `path` that do not belong to the states given by `states`. :param list states: the states that should reside in this very folder :param str path: the file system path to be checked for valid folders
entailment
def clean_path_from_deprecated_naming(base_path): """ Checks if the base path includes deprecated characters/format and returns corrected version The state machine folder name should be according the universal RAFCON path format. In case the state machine path is inside a mounted library_root_path also the library_path has to have this format. The library path is a partial path of the state machine path. This rules are followed to always provide secure paths for RAFCON and all operating systems. :param base_path: :return: cleaned base_path :rtype: str """ def warning_logger_message(insert_string): not_allowed_characters = "'" + "', '".join(REPLACED_CHARACTERS_FOR_NO_OS_LIMITATION.keys()) + "'" logger.warning("Deprecated {2} in {0}. Please avoid to use the following characters {1}." "".format(base_path, not_allowed_characters, insert_string)) from rafcon.core.singleton import library_manager if library_manager.is_os_path_within_library_root_paths(base_path): library_path, library_name = library_manager.get_library_path_and_name_for_os_path(base_path) clean_library_path = clean_path(library_path) clean_library_name = clean_path(library_name) if library_name != clean_library_name or library_path != clean_library_path: warning_logger_message("library path") library_root_key = library_manager._get_library_root_key_for_os_path(base_path) library_root_path = library_manager._library_root_paths[library_root_key] clean_base_path = os.path.join(library_root_path, clean_library_path, clean_library_name) else: path_elements = base_path.split(os.path.sep) state_machine_folder_name = base_path.split(os.path.sep)[-1] path_elements[-1] = clean_path(state_machine_folder_name) if not state_machine_folder_name == path_elements[-1]: warning_logger_message("state machine folder name") clean_base_path = os.path.sep.join(path_elements) return clean_base_path
Checks if the base path includes deprecated characters/format and returns corrected version The state machine folder name should be according the universal RAFCON path format. In case the state machine path is inside a mounted library_root_path also the library_path has to have this format. The library path is a partial path of the state machine path. This rules are followed to always provide secure paths for RAFCON and all operating systems. :param base_path: :return: cleaned base_path :rtype: str
entailment
def clean_path(base_path): """ This function cleans a file system path in terms of removing all not allowed characters of each path element. A path element is an element of a path between the path separator of the operating system. :param base_path: the path to be cleaned :return: the clean path """ path_elements = base_path.split(os.path.sep) reduced_path_elements = [clean_path_element(elem, max_length=255) for elem in path_elements] if not all(path_elements[i] == elem for i, elem in enumerate(reduced_path_elements)): # logger.info("State machine storage path is reduced") base_path = os.path.sep.join(reduced_path_elements) return base_path
This function cleans a file system path in terms of removing all not allowed characters of each path element. A path element is an element of a path between the path separator of the operating system. :param base_path: the path to be cleaned :return: the clean path
entailment
def save_state_machine_to_path(state_machine, base_path, delete_old_state_machine=False, as_copy=False): """Saves a state machine recursively to the file system The `as_copy` flag determines whether the state machine is saved as copy. If so (`as_copy=True`), some state machine attributes will be left untouched, such as the `file_system_path` or the `dirty_flag`. :param rafcon.core.state_machine.StateMachine state_machine: the state_machine to be saved :param str base_path: base_path to which all further relative paths refers to :param bool delete_old_state_machine: Whether to delete any state machine existing at the given path :param bool as_copy: Whether to use a copy storage for the state machine """ # warns the user in the logger when using deprecated names clean_path_from_deprecated_naming(base_path) state_machine.acquire_modification_lock() try: root_state = state_machine.root_state # clean old path first if delete_old_state_machine: if os.path.exists(base_path): shutil.rmtree(base_path) # Ensure that path is existing if not os.path.exists(base_path): os.makedirs(base_path) old_update_time = state_machine.last_update state_machine.last_update = storage_utils.get_current_time_string() state_machine_dict = state_machine.to_dict() storage_utils.write_dict_to_json(state_machine_dict, os.path.join(base_path, STATEMACHINE_FILE)) # set the file_system_path of the state machine if not as_copy: state_machine.file_system_path = copy.copy(base_path) else: state_machine.last_update = old_update_time # add root state recursively remove_obsolete_folders([root_state], base_path) save_state_recursively(root_state, base_path, "", as_copy) if state_machine.marked_dirty and not as_copy: state_machine.marked_dirty = False logger.debug("State machine with id {0} was saved at {1}".format(state_machine.state_machine_id, base_path)) except Exception: raise finally: state_machine.release_modification_lock()
Saves a state machine recursively to the file system The `as_copy` flag determines whether the state machine is saved as copy. If so (`as_copy=True`), some state machine attributes will be left untouched, such as the `file_system_path` or the `dirty_flag`. :param rafcon.core.state_machine.StateMachine state_machine: the state_machine to be saved :param str base_path: base_path to which all further relative paths refers to :param bool delete_old_state_machine: Whether to delete any state machine existing at the given path :param bool as_copy: Whether to use a copy storage for the state machine
entailment
def save_script_file_for_state_and_source_path(state, state_path_full, as_copy=False): """Saves the script file for a state to the directory of the state. The script name will be set to the SCRIPT_FILE constant. :param state: The state of which the script file should be saved :param str state_path_full: The path to the file system storage location of the state :param bool as_copy: Temporary storage flag to signal that the given path is not the new file_system_path """ from rafcon.core.states.execution_state import ExecutionState if isinstance(state, ExecutionState): source_script_file = os.path.join(state.script.path, state.script.filename) destination_script_file = os.path.join(state_path_full, SCRIPT_FILE) try: write_file(destination_script_file, state.script_text) except Exception: logger.exception("Storing of script file failed: {0} -> {1}".format(state.get_path(), destination_script_file)) raise if not source_script_file == destination_script_file and not as_copy: state.script.filename = SCRIPT_FILE state.script.path = state_path_full
Saves the script file for a state to the directory of the state. The script name will be set to the SCRIPT_FILE constant. :param state: The state of which the script file should be saved :param str state_path_full: The path to the file system storage location of the state :param bool as_copy: Temporary storage flag to signal that the given path is not the new file_system_path
entailment
def save_semantic_data_for_state(state, state_path_full): """Saves the semantic data in a separate json file. :param state: The state of which the script file should be saved :param str state_path_full: The path to the file system storage location of the state """ destination_script_file = os.path.join(state_path_full, SEMANTIC_DATA_FILE) try: storage_utils.write_dict_to_json(state.semantic_data, destination_script_file) except IOError: logger.exception("Storing of semantic data for state {0} failed! Destination path: {1}". format(state.get_path(), destination_script_file)) raise
Saves the semantic data in a separate json file. :param state: The state of which the script file should be saved :param str state_path_full: The path to the file system storage location of the state
entailment
def save_state_recursively(state, base_path, parent_path, as_copy=False): """Recursively saves a state to a json file It calls this method on all its substates. :param state: State to be stored :param base_path: Path to the state machine :param parent_path: Path to the parent state :param bool as_copy: Temporary storage flag to signal that the given path is not the new file_system_path :return: """ from rafcon.core.states.execution_state import ExecutionState from rafcon.core.states.container_state import ContainerState state_path = os.path.join(parent_path, get_storage_id_for_state(state)) state_path_full = os.path.join(base_path, state_path) if not os.path.exists(state_path_full): os.makedirs(state_path_full) storage_utils.write_dict_to_json(state, os.path.join(state_path_full, FILE_NAME_CORE_DATA)) if not as_copy: state.file_system_path = state_path_full if isinstance(state, ExecutionState): save_script_file_for_state_and_source_path(state, state_path_full, as_copy) save_semantic_data_for_state(state, state_path_full) # create yaml files for all children if isinstance(state, ContainerState): remove_obsolete_folders(state.states.values(), os.path.join(base_path, state_path)) for state in state.states.values(): save_state_recursively(state, base_path, state_path, as_copy)
Recursively saves a state to a json file It calls this method on all its substates. :param state: State to be stored :param base_path: Path to the state machine :param parent_path: Path to the parent state :param bool as_copy: Temporary storage flag to signal that the given path is not the new file_system_path :return:
entailment
def load_state_machine_from_path(base_path, state_machine_id=None): """Loads a state machine from the given path :param base_path: An optional base path for the state machine. :return: a tuple of the loaded container state, the version of the state and the creation time :raises ValueError: if the provided path does not contain a valid state machine """ logger.debug("Loading state machine from path {0}...".format(base_path)) state_machine_file_path = os.path.join(base_path, STATEMACHINE_FILE) state_machine_file_path_old = os.path.join(base_path, STATEMACHINE_FILE_OLD) # was the root state specified as state machine base_path to load from? if not os.path.exists(state_machine_file_path) and not os.path.exists(state_machine_file_path_old): # catch the case that a state machine root file is handed if os.path.exists(base_path) and os.path.isfile(base_path): base_path = os.path.dirname(base_path) state_machine_file_path = os.path.join(base_path, STATEMACHINE_FILE) state_machine_file_path_old = os.path.join(base_path, STATEMACHINE_FILE_OLD) if not os.path.exists(state_machine_file_path) and not os.path.exists(state_machine_file_path_old): raise ValueError("Provided path doesn't contain a valid state machine: {0}".format(base_path)) state_machine_dict = storage_utils.load_objects_from_json(state_machine_file_path) if 'used_rafcon_version' in state_machine_dict: previously_used_rafcon_version = StrictVersion(state_machine_dict['used_rafcon_version']).version active_rafcon_version = StrictVersion(rafcon.__version__).version rafcon_newer_than_sm_version = "You are trying to load a state machine that was stored with an older " \ "version of RAFCON ({0}) than the one you are using ({1}).".format( state_machine_dict['used_rafcon_version'], rafcon.__version__) rafcon_older_than_sm_version = "You are trying to load a state machine that was stored with an newer " \ "version of RAFCON ({0}) than the one you are using ({1}).".format( state_machine_dict['used_rafcon_version'], rafcon.__version__) note_about_possible_incompatibility = "The state machine will be loaded with no guarantee of success." if active_rafcon_version[0] > previously_used_rafcon_version[0]: # this is the default case # for a list of breaking changes please see: doc/breaking_changes.rst # logger.warning(rafcon_newer_than_sm_version) # logger.warning(note_about_possible_incompatibility) pass if active_rafcon_version[0] == previously_used_rafcon_version[0]: if active_rafcon_version[1] > previously_used_rafcon_version[1]: # this is the default case # for a list of breaking changes please see: doc/breaking_changes.rst # logger.info(rafcon_newer_than_sm_version) # logger.info(note_about_possible_incompatibility) pass elif active_rafcon_version[1] == previously_used_rafcon_version[1]: # Major and minor version of RAFCON and the state machine match # It should be safe to load the state machine, as the patch level does not change the format pass else: logger.warning(rafcon_older_than_sm_version) logger.warning(note_about_possible_incompatibility) else: logger.warning(rafcon_older_than_sm_version) logger.warning(note_about_possible_incompatibility) state_machine = StateMachine.from_dict(state_machine_dict, state_machine_id) if "root_state_storage_id" not in state_machine_dict: root_state_storage_id = state_machine_dict['root_state_id'] state_machine.supports_saving_state_names = False else: root_state_storage_id = state_machine_dict['root_state_storage_id'] root_state_path = os.path.join(base_path, root_state_storage_id) state_machine.file_system_path = base_path dirty_states = [] state_machine.root_state = load_state_recursively(parent=state_machine, state_path=root_state_path, dirty_states=dirty_states) if len(dirty_states) > 0: state_machine.marked_dirty = True else: state_machine.marked_dirty = False hierarchy_level = 0 number_of_states, hierarchy_level = state_machine.root_state.get_states_statistics(hierarchy_level) logger.debug("Loaded state machine ({1}) has {0} states. (Max hierarchy level {2})".format( number_of_states, base_path, hierarchy_level)) logger.debug("Loaded state machine ({1}) has {0} transitions.".format( state_machine.root_state.get_number_of_transitions(), base_path)) return state_machine
Loads a state machine from the given path :param base_path: An optional base path for the state machine. :return: a tuple of the loaded container state, the version of the state and the creation time :raises ValueError: if the provided path does not contain a valid state machine
entailment
def load_state_recursively(parent, state_path=None, dirty_states=[]): """Recursively loads the state It calls this method on each sub-state of a container state. :param parent: the root state of the last load call to which the loaded state will be added :param state_path: the path on the filesystem where to find the meta file for the state :param dirty_states: a dict of states which changed during loading :return: """ from rafcon.core.states.execution_state import ExecutionState from rafcon.core.states.container_state import ContainerState from rafcon.core.states.hierarchy_state import HierarchyState path_core_data = os.path.join(state_path, FILE_NAME_CORE_DATA) logger.debug("Load state recursively: {0}".format(str(state_path))) # TODO: Should be removed with next minor release if not os.path.exists(path_core_data): path_core_data = os.path.join(state_path, FILE_NAME_CORE_DATA_OLD) try: state_info = load_data_file(path_core_data) except ValueError as e: logger.exception("Error while loading state data: {0}".format(e)) return except LibraryNotFoundException as e: logger.error("Library could not be loaded: {0}\n" "Skipping library and continuing loading the state machine".format(e)) state_info = storage_utils.load_objects_from_json(path_core_data, as_dict=True) state_id = state_info["state_id"] dummy_state = HierarchyState(LIBRARY_NOT_FOUND_DUMMY_STATE_NAME, state_id=state_id) # set parent of dummy state if isinstance(parent, ContainerState): parent.add_state(dummy_state, storage_load=True) else: dummy_state.parent = parent return dummy_state # Transitions and data flows are not added when loading a state, as also states are not added. # We have to wait until the child states are loaded, before adding transitions and data flows, as otherwise the # validity checks for transitions and data flows would fail if not isinstance(state_info, tuple): state = state_info else: state = state_info[0] transitions = state_info[1] data_flows = state_info[2] # set parent of state if parent is not None and isinstance(parent, ContainerState): parent.add_state(state, storage_load=True) else: state.parent = parent # read script file if an execution state if isinstance(state, ExecutionState): script_text = read_file(state_path, state.script.filename) state.script_text = script_text # load semantic data try: semantic_data = load_data_file(os.path.join(state_path, SEMANTIC_DATA_FILE)) state.semantic_data = semantic_data except Exception as e: # semantic data file does not have to be there pass one_of_my_child_states_not_found = False # load child states for p in os.listdir(state_path): child_state_path = os.path.join(state_path, p) if os.path.isdir(child_state_path): child_state = load_state_recursively(state, child_state_path, dirty_states) if child_state.name is LIBRARY_NOT_FOUND_DUMMY_STATE_NAME: one_of_my_child_states_not_found = True if one_of_my_child_states_not_found: # omit adding transitions and data flows in this case pass else: # Now we can add transitions and data flows, as all child states were added if isinstance(state_info, tuple): state.transitions = transitions state.data_flows = data_flows state.file_system_path = state_path if state.marked_dirty: dirty_states.append(state) return state
Recursively loads the state It calls this method on each sub-state of a container state. :param parent: the root state of the last load call to which the loaded state will be added :param state_path: the path on the filesystem where to find the meta file for the state :param dirty_states: a dict of states which changed during loading :return:
entailment
def load_data_file(path_of_file): """ Loads the content of a file by using json.load. :param path_of_file: the path of the file to load :return: the file content as a string :raises exceptions.ValueError: if the file was not found """ if os.path.exists(path_of_file): return storage_utils.load_objects_from_json(path_of_file) raise ValueError("Data file not found: {0}".format(path_of_file))
Loads the content of a file by using json.load. :param path_of_file: the path of the file to load :return: the file content as a string :raises exceptions.ValueError: if the file was not found
entailment
def limit_text_max_length(text, max_length, separator='_'): """ Limits the length of a string. The returned string will be the first `max_length/2` characters of the input string plus a separator plus the last `max_length/2` characters of the input string. :param text: the text to be limited :param max_length: the maximum length of the output string :param separator: the separator between the first "max_length"/2 characters of the input string and the last "max_length/2" characters of the input string :return: the shortened input string """ if max_length is not None: if isinstance(text, string_types) and len(text) > max_length: max_length = int(max_length) half_length = float(max_length - 1) / 2 return text[:int(math.ceil(half_length))] + separator + text[-int(math.floor(half_length)):] return text
Limits the length of a string. The returned string will be the first `max_length/2` characters of the input string plus a separator plus the last `max_length/2` characters of the input string. :param text: the text to be limited :param max_length: the maximum length of the output string :param separator: the separator between the first "max_length"/2 characters of the input string and the last "max_length/2" characters of the input string :return: the shortened input string
entailment
def clean_path_element(text, max_length=None, separator='_'): """ Replace characters that conflict with a free OS choice when in a file system path. :param text: the string to be cleaned :param max_length: the maximum length of the output string :param separator: the separator used for rafcon.core.storage.storage.limit_text_max_length :return: """ elements_to_replace = REPLACED_CHARACTERS_FOR_NO_OS_LIMITATION for elem, replace_with in elements_to_replace.items(): text = text.replace(elem, replace_with) if max_length is not None: text = limit_text_max_length(text, max_length, separator) return text
Replace characters that conflict with a free OS choice when in a file system path. :param text: the string to be cleaned :param max_length: the maximum length of the output string :param separator: the separator used for rafcon.core.storage.storage.limit_text_max_length :return:
entailment
def limit_text_to_be_path_element(text, max_length=None, separator='_'): """ Replace characters that are not in the valid character set of RAFCON. :param text: the string to be cleaned :param max_length: the maximum length of the output string :param separator: the separator used for rafcon.core.storage.storage.limit_text_max_length :return: """ # TODO: Should there not only be one method i.e. either this one or "clean_path_element" elements_to_replace = {' ': '_', '*': '_'} for elem, replace_with in elements_to_replace.items(): text = text.replace(elem, replace_with) text = re.sub('[^a-zA-Z0-9-_]', '', text) if max_length is not None: text = limit_text_max_length(text, max_length, separator) return text
Replace characters that are not in the valid character set of RAFCON. :param text: the string to be cleaned :param max_length: the maximum length of the output string :param separator: the separator used for rafcon.core.storage.storage.limit_text_max_length :return:
entailment
def get_storage_id_for_state(state): """ Calculates the storage id of a state. This ID can be used for generating the file path for a state. :param rafcon.core.states.state.State state: state the storage_id should is composed for """ if global_config.get_config_value('STORAGE_PATH_WITH_STATE_NAME'): max_length = global_config.get_config_value('MAX_LENGTH_FOR_STATE_NAME_IN_STORAGE_PATH') max_length_of_state_name_in_folder_name = 255 - len(ID_NAME_DELIMITER + state.state_id) # TODO: should we allow "None" in config file? if max_length is None or max_length == "None" or max_length > max_length_of_state_name_in_folder_name: if max_length_of_state_name_in_folder_name < len(state.name): logger.info("The storage folder name is forced to be maximal 255 characters in length.") max_length = max_length_of_state_name_in_folder_name return limit_text_to_be_path_element(state.name, max_length) + ID_NAME_DELIMITER + state.state_id else: return state.state_id
Calculates the storage id of a state. This ID can be used for generating the file path for a state. :param rafcon.core.states.state.State state: state the storage_id should is composed for
entailment
def pane_position_check(self): """ Update right bar pane position if needed Checks calculates if the cursor is still visible and updates the pane position if it is close to not be seen. In case of an un-docked right-bar this method does nothing. :return: """ text_buffer = self.get_buffer() # not needed if the right side bar is un-docked from rafcon.gui.singleton import main_window_controller if main_window_controller is None or main_window_controller.view is None: return from rafcon.gui.runtime_config import global_runtime_config if global_runtime_config.get_config_value('RIGHT_BAR_WINDOW_UNDOCKED'): return # move the pane left if the cursor is to far right and the pane position is less then 440 from its max position button_container_min_width = self.button_container_min_width width_of_all = button_container_min_width + self.tab_width text_view_width = button_container_min_width - self.line_numbers_width min_line_string_length = float(button_container_min_width)/float(self.source_view_character_size) current_pane_pos = main_window_controller.view['right_h_pane'].get_property('position') max_position = main_window_controller.view['right_h_pane'].get_property('max_position') pane_rel_pos = main_window_controller.view['right_h_pane'].get_property('max_position') - current_pane_pos if pane_rel_pos >= width_of_all + self.line_numbers_width: pass else: cursor_line_offset = text_buffer.get_iter_at_offset(text_buffer.props.cursor_position).get_line_offset() needed_rel_pos = text_view_width/min_line_string_length*cursor_line_offset \ + self.tab_width + self.line_numbers_width needed_rel_pos = min(width_of_all, needed_rel_pos) if pane_rel_pos >= needed_rel_pos: pass else: main_window_controller.view['right_h_pane'].set_property('position', max_position - needed_rel_pos) spacer_width = int(width_of_all + self.line_numbers_width - needed_rel_pos) self.spacer_frame.set_size_request(width=spacer_width, height=-1)
Update right bar pane position if needed Checks calculates if the cursor is still visible and updates the pane position if it is close to not be seen. In case of an un-docked right-bar this method does nothing. :return:
entailment
def push_call_history_item(self, state, call_type, state_for_scoped_data, input_data=None): """Adds a new call-history-item to the history item list A call history items stores information about the point in time where a method (entry, execute, exit) of certain state was called. :param state: the state that was called :param call_type: the call type of the execution step, i.e. if it refers to a container state or an execution state :param state_for_scoped_data: the state of which the scoped data needs to be saved for further usages (e.g. backward stepping) """ last_history_item = self.get_last_history_item() from rafcon.core.states.library_state import LibraryState # delayed imported on purpose if isinstance(state_for_scoped_data, LibraryState): state_for_scoped_data = state_for_scoped_data.state_copy return_item = CallItem(state, last_history_item, call_type, state_for_scoped_data, input_data, state.run_id) return self._push_item(last_history_item, return_item)
Adds a new call-history-item to the history item list A call history items stores information about the point in time where a method (entry, execute, exit) of certain state was called. :param state: the state that was called :param call_type: the call type of the execution step, i.e. if it refers to a container state or an execution state :param state_for_scoped_data: the state of which the scoped data needs to be saved for further usages (e.g. backward stepping)
entailment
def push_return_history_item(self, state, call_type, state_for_scoped_data, output_data=None): """Adds a new return-history-item to the history item list A return history items stores information about the point in time where a method (entry, execute, exit) of certain state returned. :param state: the state that returned :param call_type: the call type of the execution step, i.e. if it refers to a container state or an execution state :param state_for_scoped_data: the state of which the scoped data needs to be saved for further usages (e.g. backward stepping) """ last_history_item = self.get_last_history_item() from rafcon.core.states.library_state import LibraryState # delayed imported on purpose if isinstance(state_for_scoped_data, LibraryState): state_for_scoped_data = state_for_scoped_data.state_copy return_item = ReturnItem(state, last_history_item, call_type, state_for_scoped_data, output_data, state.run_id) return self._push_item(last_history_item, return_item)
Adds a new return-history-item to the history item list A return history items stores information about the point in time where a method (entry, execute, exit) of certain state returned. :param state: the state that returned :param call_type: the call type of the execution step, i.e. if it refers to a container state or an execution state :param state_for_scoped_data: the state of which the scoped data needs to be saved for further usages (e.g. backward stepping)
entailment
def push_concurrency_history_item(self, state, number_concurrent_threads): """Adds a new concurrency-history-item to the history item list A concurrent history item stores information about the point in time where a certain number of states is launched concurrently (e.g. in a barrier concurrency state). :param state: the state that launches the state group :param number_concurrent_threads: the number of states that are launched """ last_history_item = self.get_last_history_item() return_item = ConcurrencyItem(state, self.get_last_history_item(), number_concurrent_threads, state.run_id, self.execution_history_storage) return self._push_item(last_history_item, return_item)
Adds a new concurrency-history-item to the history item list A concurrent history item stores information about the point in time where a certain number of states is launched concurrently (e.g. in a barrier concurrency state). :param state: the state that launches the state group :param number_concurrent_threads: the number of states that are launched
entailment
def update_hash_from_dict(obj_hash, object_): """Updates an existing hash object with another Hashable, list, set, tuple, dict or stringifyable object :param obj_hash: The hash object (see Python hashlib documentation) :param object_: The value that should be added to the hash (can be another Hashable or a dictionary) """ if isinstance(object_, Hashable): object_.update_hash(obj_hash) elif isinstance(object_, (list, set, tuple)): if isinstance(object_, set): # A set is not ordered object_ = sorted(object_) for element in object_: Hashable.update_hash_from_dict(obj_hash, element) elif isinstance(object_, dict): for key in sorted(object_.keys()): # A dict is not ordered Hashable.update_hash_from_dict(obj_hash, key) Hashable.update_hash_from_dict(obj_hash, object_[key]) else: obj_hash.update(Hashable.get_object_hash_string(object_))
Updates an existing hash object with another Hashable, list, set, tuple, dict or stringifyable object :param obj_hash: The hash object (see Python hashlib documentation) :param object_: The value that should be added to the hash (can be another Hashable or a dictionary)
entailment
def mutable_hash(self, obj_hash=None): """Creates a hash with the (im)mutable data fields of the object Example: >>> my_obj = type("MyDerivedClass", (Hashable,), { "update_hash": lambda self, h: h.update("RAFCON") })() >>> my_obj_hash = my_obj.mutable_hash() >>> print('Hash: ' + my_obj_hash.hexdigest()) Hash: c8b2e32dcb31c5282e4b9dbc6a9975b65bf59cd80a7cee66d195e320484df5c6 :param obj_hash: The hash object (see Python hashlib) :return: The updated hash object """ if obj_hash is None: obj_hash = hashlib.sha256() self.update_hash(obj_hash) return obj_hash
Creates a hash with the (im)mutable data fields of the object Example: >>> my_obj = type("MyDerivedClass", (Hashable,), { "update_hash": lambda self, h: h.update("RAFCON") })() >>> my_obj_hash = my_obj.mutable_hash() >>> print('Hash: ' + my_obj_hash.hexdigest()) Hash: c8b2e32dcb31c5282e4b9dbc6a9975b65bf59cd80a7cee66d195e320484df5c6 :param obj_hash: The hash object (see Python hashlib) :return: The updated hash object
entailment
def emit(self, record): """Logs a new record If a logging view is given, it is used to log the new record to. The code is partially copied from the StreamHandler class. :param record: :return: """ try: # Shorten the source name of the record (remove rafcon.) if sys.version_info >= (2, 7): record.__setattr__("name", record.name.replace("rafcon.", "")) msg = self.format(record) fs = "%s" try: ufs = u'%s' try: entry = ufs % msg except UnicodeEncodeError: entry = fs % msg except UnicodeError: entry = fs % msg for logging_view in self._logging_views.values(): logging_view.print_message(entry, record.levelno) except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record)
Logs a new record If a logging view is given, it is used to log the new record to. The code is partially copied from the StreamHandler class. :param record: :return:
entailment
def get_meta_data_editor(self, for_gaphas=True): """Returns the editor for the specified editor This method should be used instead of accessing the meta data of an editor directly. It return the meta data of the editor available (with priority to the one specified by `for_gaphas`) and converts it if needed. :param bool for_gaphas: True (default) if the meta data is required for gaphas, False if for OpenGL :return: Meta data for the editor :rtype: Vividict """ meta_gaphas = self.meta['gui']['editor_gaphas'] meta_opengl = self.meta['gui']['editor_opengl'] assert isinstance(meta_gaphas, Vividict) and isinstance(meta_opengl, Vividict) # Use meta data of editor with more keys (typically one of the editors has zero keys) # TODO check if the magic length condition in the next line can be improved (consistent behavior getter/setter?) parental_conversion_from_opengl = self._parent and self._parent().temp['conversion_from_opengl'] from_gaphas = len(meta_gaphas) > len(meta_opengl) or (len(meta_gaphas) == len(meta_opengl) and for_gaphas and not parental_conversion_from_opengl) # Convert meta data if meta data target and origin differ if from_gaphas and not for_gaphas: self.meta['gui']['editor_opengl'] = self._meta_data_editor_gaphas2opengl(meta_gaphas) elif not from_gaphas and for_gaphas: self.meta['gui']['editor_gaphas'] = self._meta_data_editor_opengl2gaphas(meta_opengl) # only keep meta data for one editor del self.meta['gui']['editor_opengl' if for_gaphas else 'editor_gaphas'] return self.meta['gui']['editor_gaphas'] if for_gaphas else self.meta['gui']['editor_opengl']
Returns the editor for the specified editor This method should be used instead of accessing the meta data of an editor directly. It return the meta data of the editor available (with priority to the one specified by `for_gaphas`) and converts it if needed. :param bool for_gaphas: True (default) if the meta data is required for gaphas, False if for OpenGL :return: Meta data for the editor :rtype: Vividict
entailment
def set_meta_data_editor(self, key, meta_data, from_gaphas=True): """Sets the meta data for a specific key of the desired editor :param str key: The meta data key, separated by dots if it is nested :param meta_data: The value to be set :param bool from_gaphas: If the data comes from a gaphas editor """ self.do_convert_meta_data_if_no_data(from_gaphas) meta_gui = self.meta['gui'] meta_gui = meta_gui['editor_gaphas'] if from_gaphas else meta_gui['editor_opengl'] key_path = key.split('.') for key in key_path: if isinstance(meta_gui, list): meta_gui[int(key)] = meta_data break if key == key_path[-1]: meta_gui[key] = meta_data else: meta_gui = meta_gui[key] return self.get_meta_data_editor(for_gaphas=from_gaphas)
Sets the meta data for a specific key of the desired editor :param str key: The meta data key, separated by dots if it is nested :param meta_data: The value to be set :param bool from_gaphas: If the data comes from a gaphas editor
entailment
def meta_data_hash(self, obj_hash=None): """Creates a hash with the meta data of the model :param obj_hash: The hash object (see Python hashlib) :return: The updated hash object """ if obj_hash is None: obj_hash = hashlib.sha256() self.update_meta_data_hash(obj_hash) return obj_hash
Creates a hash with the meta data of the model :param obj_hash: The hash object (see Python hashlib) :return: The updated hash object
entailment
def prepare_destruction(self): """Prepares the model for destruction """ self._Observer__PROP_TO_METHS.clear() self._Observer__METH_TO_PROPS.clear() self._Observer__PAT_TO_METHS.clear() self._Observer__METH_TO_PAT.clear() self._Observer__PAT_METH_TO_KWARGS.clear()
Prepares the model for destruction
entailment
def limit_value_string_length(value): """This method limits the string representation of the value to MAX_VALUE_LABEL_TEXT_LENGTH + 3 characters. :param value: Value to limit string representation :return: String holding the value with a maximum length of MAX_VALUE_LABEL_TEXT_LENGTH + 3 """ if isinstance(value, string_types) and len(value) > constants.MAX_VALUE_LABEL_TEXT_LENGTH: value = value[:constants.MAX_VALUE_LABEL_TEXT_LENGTH] + "..." final_string = " " + value + " " elif isinstance(value, (dict, list)) and len(str(value)) > constants.MAX_VALUE_LABEL_TEXT_LENGTH: value_text = str(value)[:constants.MAX_VALUE_LABEL_TEXT_LENGTH] + "..." final_string = " " + value_text + " " else: final_string = " " + str(value) + " " return final_string
This method limits the string representation of the value to MAX_VALUE_LABEL_TEXT_LENGTH + 3 characters. :param value: Value to limit string representation :return: String holding the value with a maximum length of MAX_VALUE_LABEL_TEXT_LENGTH + 3
entailment
def get_col_rgba(color, transparency=None, opacity=None): """This class converts a Gdk.Color into its r, g, b parts and adds an alpha according to needs If both transparency and opacity is None, alpha is set to 1 => opaque :param Gdk.Color color: Color to extract r, g and b from :param float | None transparency: Value between 0 (opaque) and 1 (transparent) or None if opacity is to be used :param float | None opacity: Value between 0 (transparent) and 1 (opaque) or None if transparency is to be used :return: Red, Green, Blue and Alpha value (all between 0.0 - 1.0) """ r, g, b = color.red, color.green, color.blue # Convert from 0-6535 to 0-1 r /= 65535. g /= 65535. b /= 65535. if transparency is not None or opacity is None: transparency = 0 if transparency is None else transparency # default value if transparency < 0 or transparency > 1: raise ValueError("Transparency must be between 0 and 1") alpha = 1 - transparency else: if opacity < 0 or opacity > 1: raise ValueError("Opacity must be between 0 and 1") alpha = opacity return r, g, b, alpha
This class converts a Gdk.Color into its r, g, b parts and adds an alpha according to needs If both transparency and opacity is None, alpha is set to 1 => opaque :param Gdk.Color color: Color to extract r, g and b from :param float | None transparency: Value between 0 (opaque) and 1 (transparent) or None if opacity is to be used :param float | None opacity: Value between 0 (transparent) and 1 (opaque) or None if transparency is to be used :return: Red, Green, Blue and Alpha value (all between 0.0 - 1.0)
entailment
def get_side_length_of_resize_handle(view, item): """Calculate the side length of a resize handle :param rafcon.gui.mygaphas.view.ExtendedGtkView view: View :param rafcon.gui.mygaphas.items.state.StateView item: StateView :return: side length :rtype: float """ from rafcon.gui.mygaphas.items.state import StateView, NameView if isinstance(item, StateView): return item.border_width * view.get_zoom_factor() / 1.5 elif isinstance(item, NameView): return item.parent.border_width * view.get_zoom_factor() / 2.5 return 0
Calculate the side length of a resize handle :param rafcon.gui.mygaphas.view.ExtendedGtkView view: View :param rafcon.gui.mygaphas.items.state.StateView item: StateView :return: side length :rtype: float
entailment
def draw_data_value_rect(cairo_context, color, value_size, name_size, pos, port_side): """This method draws the containing rect for the data port value, depending on the side and size of the label. :param cairo_context: Draw Context :param color: Background color of value part :param value_size: Size (width, height) of label holding the value :param name_size: Size (width, height) of label holding the name :param pos: Position of name label start point (upper left corner of label) :param port_side: Side on which the value part should be drawn :return: Rotation Angle (to rotate value accordingly), X-Position of value label start point, Y-Position of value label start point """ c = cairo_context rot_angle = .0 move_x = 0. move_y = 0. if port_side is SnappedSide.RIGHT: move_x = pos[0] + name_size[0] move_y = pos[1] c.rectangle(move_x, move_y, value_size[0], value_size[1]) elif port_side is SnappedSide.BOTTOM: move_x = pos[0] - value_size[1] move_y = pos[1] + name_size[0] rot_angle = pi / 2. c.rectangle(move_x, move_y, value_size[1], value_size[0]) elif port_side is SnappedSide.LEFT: move_x = pos[0] - value_size[0] move_y = pos[1] c.rectangle(move_x, move_y, value_size[0], value_size[1]) elif port_side is SnappedSide.TOP: move_x = pos[0] - value_size[1] move_y = pos[1] - value_size[0] rot_angle = -pi / 2. c.rectangle(move_x, move_y, value_size[1], value_size[0]) c.set_source_rgba(*color) c.fill_preserve() c.set_source_rgb(*gui_config.gtk_colors['BLACK'].to_floats()) c.stroke() return rot_angle, move_x, move_y
This method draws the containing rect for the data port value, depending on the side and size of the label. :param cairo_context: Draw Context :param color: Background color of value part :param value_size: Size (width, height) of label holding the value :param name_size: Size (width, height) of label holding the name :param pos: Position of name label start point (upper left corner of label) :param port_side: Side on which the value part should be drawn :return: Rotation Angle (to rotate value accordingly), X-Position of value label start point, Y-Position of value label start point
entailment
def draw_connected_scoped_label(context, color, name_size, handle_pos, port_side, port_side_size, draw_connection_to_port=False): """Draw label of scoped variable This method draws the label of a scoped variable connected to a data port. This is represented by drawing a bigger label where the top part is filled and the bottom part isn't. :param context: Draw Context :param Gdk.Color color: Color to draw the label in (border and background fill color) :param name_size: Size of the name labels (scoped variable and port name) combined :param handle_pos: Position of port which label is connected to :param port_side: Side on which the label should be drawn :param port_side_size: Size of port (to have a relative size) :param draw_connection_to_port: Whether there should be a line connecting the label to the port :return: Rotation Angle (to rotate names accordingly), X-Position of name labels start point, Y-Position of name labels start point """ c = context.cairo c.set_line_width(port_side_size * .03) c.set_source_rgb(*color.to_floats()) rot_angle = .0 move_x = 0. move_y = 0. if port_side is SnappedSide.RIGHT: move_x = handle_pos.x + 2 * port_side_size move_y = handle_pos.y - name_size[1] / 2. c.move_to(move_x + name_size[0], move_y + name_size[1] / 2.) c.line_to(move_x + name_size[0], move_y) c.line_to(move_x, move_y) c.line_to(handle_pos.x + port_side_size, handle_pos.y) c.fill_preserve() c.stroke() if draw_connection_to_port: c.line_to(handle_pos.x + port_side_size / 2., handle_pos.y) c.line_to(handle_pos.x + port_side_size, handle_pos.y) else: c.move_to(handle_pos.x + port_side_size, handle_pos.y) c.line_to(move_x, move_y + name_size[1]) c.line_to(move_x + name_size[0], move_y + name_size[1]) c.line_to(move_x + name_size[0], move_y + name_size[1] / 2.) elif port_side is SnappedSide.BOTTOM: move_x = handle_pos.x + name_size[1] / 2. move_y = handle_pos.y + 2 * port_side_size rot_angle = pi / 2. c.move_to(move_x - name_size[1] / 2., move_y + name_size[0]) c.line_to(move_x, move_y + name_size[0]) c.line_to(move_x, move_y) c.line_to(handle_pos.x, move_y - port_side_size) c.fill_preserve() c.stroke() if draw_connection_to_port: c.line_to(handle_pos.x, handle_pos.y + port_side_size / 2.) c.line_to(handle_pos.x, move_y - port_side_size) else: c.move_to(handle_pos.x, move_y - port_side_size) c.line_to(move_x - name_size[1], move_y) c.line_to(move_x - name_size[1], move_y + name_size[0]) c.line_to(move_x - name_size[1] / 2., move_y + name_size[0]) elif port_side is SnappedSide.LEFT: move_x = handle_pos.x - 2 * port_side_size - name_size[0] move_y = handle_pos.y - name_size[1] / 2. c.move_to(move_x, move_y + name_size[1] / 2.) c.line_to(move_x, move_y) c.line_to(move_x + name_size[0], move_y) c.line_to(handle_pos.x - port_side_size, move_y + name_size[1] / 2.) c.fill_preserve() c.stroke() if draw_connection_to_port: c.line_to(handle_pos.x - port_side_size / 2., handle_pos.y) c.line_to(handle_pos.x - port_side_size, handle_pos.y) else: c.move_to(handle_pos.x - port_side_size, move_y + name_size[1] / 2.) c.line_to(move_x + name_size[0], move_y + name_size[1]) c.line_to(move_x, move_y + name_size[1]) c.line_to(move_x, move_y + name_size[1] / 2.) elif port_side is SnappedSide.TOP: move_x = handle_pos.x - name_size[1] / 2. move_y = handle_pos.y - 2 * port_side_size rot_angle = -pi / 2. c.move_to(move_x + name_size[1] / 2., move_y - name_size[0]) c.line_to(move_x, move_y - name_size[0]) c.line_to(move_x, move_y) c.line_to(handle_pos.x, move_y + port_side_size) c.fill_preserve() c.stroke() if draw_connection_to_port: c.line_to(handle_pos.x, handle_pos.y - port_side_size / 2.) c.line_to(handle_pos.x, move_y + port_side_size) else: c.move_to(handle_pos.x, move_y + port_side_size) c.line_to(move_x + name_size[1], move_y) c.line_to(move_x + name_size[1], move_y - name_size[0]) c.line_to(move_x + name_size[1] / 2., move_y - name_size[0]) c.stroke() return rot_angle, move_x, move_y
Draw label of scoped variable This method draws the label of a scoped variable connected to a data port. This is represented by drawing a bigger label where the top part is filled and the bottom part isn't. :param context: Draw Context :param Gdk.Color color: Color to draw the label in (border and background fill color) :param name_size: Size of the name labels (scoped variable and port name) combined :param handle_pos: Position of port which label is connected to :param port_side: Side on which the label should be drawn :param port_side_size: Size of port (to have a relative size) :param draw_connection_to_port: Whether there should be a line connecting the label to the port :return: Rotation Angle (to rotate names accordingly), X-Position of name labels start point, Y-Position of name labels start point
entailment
def draw_port_label(context, port, transparency, fill, label_position, show_additional_value=False, additional_value=None, only_extent_calculations=False): """Draws a normal label indicating the port name. :param context: Draw Context :param port: The PortView :param transparency: Transparency of the text :param fill: Whether the label should be filled or not :param label_position: Side on which the label should be drawn :param show_additional_value: Whether to show an additional value (for data ports) :param additional_value: The additional value to be shown :param only_extent_calculations: Calculate only the extends and do not actually draw """ c = context cairo_context = c if isinstance(c, CairoBoundingBoxContext): cairo_context = c._cairo # Gtk TODO # c.set_antialias(Antialias.GOOD) text = port.name label_color = get_col_rgba(port.fill_color, transparency) text_color = port.text_color port_height = port.port_size[1] port_position = c.get_current_point() layout = PangoCairo.create_layout(cairo_context) layout.set_text(text, -1) font_name = constants.INTERFACE_FONT font = FontDescription(font_name + " " + str(FONT_SIZE)) layout.set_font_description(font) ink_extents, logical_extents = layout.get_extents() extents = [extent / float(SCALE) for extent in [logical_extents.x, logical_extents.y, logical_extents.width, logical_extents.height]] real_text_size = extents[2], extents[3] desired_height = port_height scale_factor = real_text_size[1] / desired_height # margin is the distance between the text and the border line margin = desired_height / 2.5 arrow_height = desired_height # The real_text_size dimensions are rotated by 90 deg compared to the label, as the label is drawn upright text_size = desired_height, real_text_size[0] / scale_factor, text_size_with_margin = text_size[0] + 2 * margin, text_size[1] + 2 * margin + arrow_height port_distance = desired_height port_offset = desired_height / 2. if label_position is SnappedSide.RIGHT: label_angle = deg2rad(-90) text_angle = 0 elif label_position is SnappedSide.BOTTOM: label_angle = 0 text_angle = deg2rad(-90) elif label_position is SnappedSide.LEFT: label_angle = deg2rad(90) text_angle = 0 else: # label_position is SnappedSide.TOP: label_angle = deg2rad(180) text_angle = deg2rad(90) # Draw (filled) outline of label c.move_to(*port_position) c.save() c.rotate(label_angle) draw_label_path(c, text_size_with_margin[0], text_size_with_margin[1], arrow_height, port_distance, port_offset) c.restore() c.set_line_width(port_height * .03) c.set_source_rgba(*label_color) label_extents = c.stroke_extents() if label_extents[0] == 0: label_extents = c.fill_extents() if only_extent_calculations: c.new_path() else: if fill: c.fill_preserve() c.stroke() # Move to the upper left corner of the desired text position c.save() c.move_to(*port_position) c.rotate(label_angle) c.rel_move_to(0, port_distance + arrow_height + 2 * margin) c.scale(1. / scale_factor, 1. / scale_factor) c.rel_move_to(-real_text_size[1] / 2 - extents[1], real_text_size[0] - extents[0]) c.restore() # Show text in correct orientation c.save() c.rotate(text_angle) c.scale(1. / scale_factor, 1. / scale_factor) # Correction for labels positioned right: as the text is mirrored, the anchor point must be moved if label_position is SnappedSide.RIGHT: c.rel_move_to(-real_text_size[0], -real_text_size[1]) c.set_source_rgba(*get_col_rgba(text_color, transparency)) PangoCairo.update_layout(cairo_context, layout) PangoCairo.show_layout(cairo_context, layout) c.restore() if show_additional_value: value_text = limit_value_string_length(additional_value) value_layout = PangoCairo.create_layout(cairo_context) value_layout.set_text(value_text, -1) value_layout.set_font_description(font) ink_extents, logical_extents = value_layout.get_extents() extents = [extent / float(SCALE) for extent in [logical_extents.x, logical_extents.y, logical_extents.width, logical_extents.height]] value_text_size = extents[2], real_text_size[1] # Move to the upper left corner of the additional value box c.save() c.move_to(*port_position) c.rotate(label_angle) c.rel_move_to(-text_size_with_margin[0] / 2., text_size_with_margin[1] + port_distance) # Draw rectangular path c.rel_line_to(text_size_with_margin[0], 0) c.rel_line_to(0, value_text_size[0] / scale_factor + 2 * margin) c.rel_line_to(-text_size_with_margin[0], 0) c.close_path() c.restore() value_extents = c.stroke_extents() if only_extent_calculations: c.new_path() else: # Draw filled outline c.set_source_rgba(*get_col_rgba(gui_config.gtk_colors['DATA_VALUE_BACKGROUND'])) c.fill_preserve() c.set_source_rgb(*gui_config.gtk_colors['BLACK'].to_floats()) c.stroke() # Move to the upper left corner of the desired text position c.save() c.move_to(*port_position) c.rotate(label_angle) c.rel_move_to(0, margin + text_size_with_margin[1] + port_distance) c.scale(1. / scale_factor, 1. / scale_factor) c.rel_move_to(-real_text_size[1] / 2., value_text_size[0]) c.restore() # Show text in correct orientation c.save() c.rotate(text_angle) c.scale(1. / scale_factor, 1. / scale_factor) # Correction for labels positioned right: as the text is mirrored, the anchor point must be moved if label_position is SnappedSide.RIGHT: c.rel_move_to(-value_text_size[0] - margin * scale_factor, -real_text_size[1]) c.set_source_rgba(*get_col_rgba(gui_config.gtk_colors['SCOPED_VARIABLE_TEXT'])) PangoCairo.update_layout(cairo_context, value_layout) PangoCairo.show_layout(cairo_context, value_layout) c.restore() label_extents = min(label_extents[0], value_extents[0]), min(label_extents[1], value_extents[1]), \ max(label_extents[2], value_extents[2]), max(label_extents[3], value_extents[3]) return label_extents
Draws a normal label indicating the port name. :param context: Draw Context :param port: The PortView :param transparency: Transparency of the text :param fill: Whether the label should be filled or not :param label_position: Side on which the label should be drawn :param show_additional_value: Whether to show an additional value (for data ports) :param additional_value: The additional value to be shown :param only_extent_calculations: Calculate only the extends and do not actually draw
entailment
def draw_label_path(context, width, height, arrow_height, distance_to_port, port_offset): """Draws the path for an upright label :param context: The Cairo context :param float width: Width of the label :param float height: Height of the label :param float distance_to_port: Distance to the port related to the label :param float port_offset: Distance from the port center to its border :param bool draw_connection_to_port: Whether to draw a line from the tip of the label to the port """ c = context # The current point is the port position # Mover to outer border of state c.rel_move_to(0, port_offset) # Draw line to arrow tip of label c.rel_line_to(0, distance_to_port) # Line to upper left corner c.rel_line_to(-width / 2., arrow_height) # Line to lower left corner c.rel_line_to(0, height - arrow_height) # Line to lower right corner c.rel_line_to(width, 0) # Line to upper right corner c.rel_line_to(0, -(height - arrow_height)) # Line to center top (tip of label) c.rel_line_to(-width / 2., -arrow_height) # Close path c.close_path()
Draws the path for an upright label :param context: The Cairo context :param float width: Width of the label :param float height: Height of the label :param float distance_to_port: Distance to the port related to the label :param float port_offset: Distance from the port center to its border :param bool draw_connection_to_port: Whether to draw a line from the tip of the label to the port
entailment
def prepare_destruction(self, recursive=True): """Prepares the model for destruction Recursively un-registers all observers and removes references to child models """ self.destruction_signal.emit() try: self.unregister_observer(self) except KeyError: # Might happen if the observer was already unregistered pass if recursive: if self.state_copy: self.state_copy.prepare_destruction(recursive) self.state_copy = None else: if self.state_copy_initialized: logger.verbose("Multiple calls of prepare destruction for {0}".format(self)) # The next lines are commented because not needed and create problems if used why it is an open to-do # for port in self.input_data_ports[:] + self.output_data_ports[:] + self.outcomes[:]: # if port.core_element is not None: # # TODO setting data ports None in a Library state cause gtkmvc3 attribute getter problems why? # port.prepare_destruction() del self.input_data_ports[:] del self.output_data_ports[:] del self.outcomes[:] self.state = None
Prepares the model for destruction Recursively un-registers all observers and removes references to child models
entailment
def _load_input_data_port_models(self): """Reloads the input data port models directly from the the state""" if not self.state_copy_initialized: return self.input_data_ports = [] for input_data_port_m in self.state_copy.input_data_ports: new_ip_m = deepcopy(input_data_port_m) new_ip_m.parent = self new_ip_m.data_port = input_data_port_m.data_port self.input_data_ports.append(new_ip_m)
Reloads the input data port models directly from the the state
entailment
def _load_output_data_port_models(self): """Reloads the output data port models directly from the the state""" if not self.state_copy_initialized: return self.output_data_ports = [] for output_data_port_m in self.state_copy.output_data_ports: new_op_m = deepcopy(output_data_port_m) new_op_m.parent = self new_op_m.data_port = output_data_port_m.data_port self.output_data_ports.append(new_op_m)
Reloads the output data port models directly from the the state
entailment
def _load_income_model(self): """Reloads the income model directly from the state""" if not self.state_copy_initialized: return self.income = None income_m = deepcopy(self.state_copy.income) income_m.parent = self income_m.income = income_m.income self.income = income_m
Reloads the income model directly from the state
entailment
def _load_outcome_models(self): """Reloads the outcome models directly from the state""" if not self.state_copy_initialized: return self.outcomes = [] for outcome_m in self.state_copy.outcomes: new_oc_m = deepcopy(outcome_m) new_oc_m.parent = self new_oc_m.outcome = outcome_m.outcome self.outcomes.append(new_oc_m)
Reloads the outcome models directly from the state
entailment
def show_content(self): """Check if content of library is to be shown Content is shown, if the uppermost state's meta flag "show_content" is True and the library hierarchy depth (up to MAX_VISIBLE_LIBRARY_HIERARCHY level) is not to high. :return: Whether the content is to be shown :rtype: bool """ current_hierarchy_depth = self.state.library_hierarchy_depth max_hierarchy_depth = global_gui_config.get_config_value("MAX_VISIBLE_LIBRARY_HIERARCHY", 2) if current_hierarchy_depth >= max_hierarchy_depth: return False if current_hierarchy_depth > 1: uppermost_lib_state = self.state.get_uppermost_library_root_state().parent uppermost_lib_state_m = self.get_state_machine_m().get_state_model_by_path(uppermost_lib_state.get_path()) else: uppermost_lib_state_m = self uppermost_lib_meta = uppermost_lib_state_m.meta return False if 'show_content' not in uppermost_lib_meta['gui'] else uppermost_lib_meta['gui']['show_content']
Check if content of library is to be shown Content is shown, if the uppermost state's meta flag "show_content" is True and the library hierarchy depth (up to MAX_VISIBLE_LIBRARY_HIERARCHY level) is not to high. :return: Whether the content is to be shown :rtype: bool
entailment
def prepare_destruction(self): """Prepares the model for destruction Unregisters the model from observing itself. """ if self.core_element is None: logger.verbose("Multiple calls of prepare destruction for {0}".format(self)) self.destruction_signal.emit() try: self.unregister_observer(self) except KeyError: # Might happen if the observer was already unregistered pass super(StateElementModel, self).prepare_destruction()
Prepares the model for destruction Unregisters the model from observing itself.
entailment
def model_changed(self, model, prop_name, info): """This method notifies the parent state about changes made to the state element """ if self.parent is not None: self.parent.model_changed(model, prop_name, info)
This method notifies the parent state about changes made to the state element
entailment
def meta_changed(self, model, prop_name, info): """This method notifies the parent state about changes made to the meta data """ if self.parent is not None: msg = info.arg # Add information about notification to the signal message notification = Notification(model, prop_name, info) msg = msg._replace(notification=notification) info.arg = msg self.parent.meta_changed(model, prop_name, info)
This method notifies the parent state about changes made to the meta data
entailment
def on_config_value_changed(self, config_m, prop_name, info): """Callback when a config value has been changed :param ConfigModel config_m: The config model that has been changed :param str prop_name: Should always be 'config' :param dict info: Information e.g. about the changed config key """ config_key = info['args'][1] if config_key in ["EXECUTION_TICKER_ENABLED"]: self.check_configuration()
Callback when a config value has been changed :param ConfigModel config_m: The config model that has been changed :param str prop_name: Should always be 'config' :param dict info: Information e.g. about the changed config key
entailment
def disable(self): """ Relieve all state machines that have no active execution and hide the widget """ self.ticker_text_label.hide() if self.current_observed_sm_m: self.stop_sm_m_observation(self.current_observed_sm_m)
Relieve all state machines that have no active execution and hide the widget
entailment
def on_state_execution_status_changed_after(self, model, prop_name, info): """ Show current execution status in the widget This function specifies what happens if the state machine execution status of a state changes :param model: the model of the state that has changed (most likely its execution status) :param prop_name: property name that has been changed :param info: notification info dictionary :return: """ from rafcon.gui.utils.notification_overview import NotificationOverview from rafcon.core.states.state import State def name_and_next_state(state): assert isinstance(state, State) if state.is_root_state_of_library: return state.parent.parent, state.parent.name else: return state.parent, state.name def create_path(state, n=3, separator='/'): next_parent, name = name_and_next_state(state) path = separator + name n -= 1 while n > 0 and isinstance(next_parent, State): next_parent, name = name_and_next_state(next_parent) path = separator + name + path n -= 1 if isinstance(next_parent, State): path = separator + '..' + path return path if 'kwargs' in info and 'method_name' in info['kwargs']: overview = NotificationOverview(info) if overview['method_name'][-1] == 'state_execution_status': active_state = overview['model'][-1].state assert isinstance(active_state, State) path_depth = rafcon.gui.singleton.global_gui_config.get_config_value("EXECUTION_TICKER_PATH_DEPTH", 3) message = self._fix_text_of_label + create_path(active_state, path_depth) if rafcon.gui.singleton.main_window_controller.view is not None: self.ticker_text_label.set_text(message) else: logger.warn("Not initialized yet")
Show current execution status in the widget This function specifies what happens if the state machine execution status of a state changes :param model: the model of the state that has changed (most likely its execution status) :param prop_name: property name that has been changed :param info: notification info dictionary :return:
entailment
def execution_engine_model_changed(self, model, prop_name, info): """Active observation of state machine and show and hide widget. """ if not self._view_initialized: return active_sm_id = rafcon.gui.singleton.state_machine_manager_model.state_machine_manager.active_state_machine_id if active_sm_id is None: # relieve all state machines that have no active execution and hide the widget self.disable() else: # observe all state machines that have an active execution and show the widget self.check_configuration()
Active observation of state machine and show and hide widget.
entailment
def register_observer(self): """ Register all observable which are of interest """ self.execution_engine.add_observer(self, "start", notify_before_function=self.on_start) self.execution_engine.add_observer(self, "pause", notify_before_function=self.on_pause) self.execution_engine.add_observer(self, "stop", notify_before_function=self.on_stop)
Register all observable which are of interest
entailment
def register_states_of_state_machine(self, state_machine): """ This functions registers all states of state machine. :param state_machine: the state machine to register all states of :return: """ root = state_machine.root_state root.add_observer(self, "state_execution_status", notify_after_function=self.on_state_execution_status_changed_after) self.recursively_register_child_states(root)
This functions registers all states of state machine. :param state_machine: the state machine to register all states of :return:
entailment
def recursively_register_child_states(self, state): """ A function tha registers recursively all child states of a state :param state: :return: """ self.logger.info("Execution status observer add new state {}".format(state)) if isinstance(state, ContainerState): state.add_observer(self, "add_state", notify_after_function=self.on_add_state) for state in list(state.states.values()): self.recursively_register_child_states(state) state.add_observer(self, "state_execution_status", notify_after_function=self.on_state_execution_status_changed_after) if isinstance(state, LibraryState): self.recursively_register_child_states(state.state_copy) state.add_observer(self, "state_execution_status", notify_after_function=self.on_state_execution_status_changed_after)
A function tha registers recursively all child states of a state :param state: :return:
entailment
def on_add_state_machine_after(self, observable, return_value, args): """ This method specifies what happens when a state machine is added to the state machine manager :param observable: the state machine manager :param return_value: the new state machine :param args: :return: """ self.logger.info("Execution status observer register new state machine sm_id: {}".format(args[1].state_machine_id)) self.register_states_of_state_machine(args[1])
This method specifies what happens when a state machine is added to the state machine manager :param observable: the state machine manager :param return_value: the new state machine :param args: :return:
entailment
def on_state_execution_status_changed_after(self, observable, return_value, args): """ This function specifies what happens if the state machine execution status of a state changes :param observable: the state whose execution status changed :param return_value: the new execution status :param args: a list of all arguments of the observed function :return: """ self.logger.info("Execution status has changed for state '{0}' to status: {1}" "".format(observable.get_path(by_name=True), observable.state_execution_status))
This function specifies what happens if the state machine execution status of a state changes :param observable: the state whose execution status changed :param return_value: the new execution status :param args: a list of all arguments of the observed function :return:
entailment
def _initialize_hierarchy(self): """ This function covers the whole initialization routine before executing a hierarchy state. :return: """ logger.debug("Starting execution of {0}{1}".format(self, " (backwards)" if self.backward_execution else "")) # reset variables self.child_state = None self.last_error = None self.last_child = None self.last_transition = None if self.backward_execution: self.setup_backward_run() else: # forward_execution self.setup_run() self.state_execution_status = StateExecutionStatus.WAIT_FOR_NEXT_STATE if self.backward_execution: last_history_item = self.execution_history.pop_last_item() assert isinstance(last_history_item, ReturnItem) self.scoped_data = last_history_item.scoped_data else: # forward_execution self.execution_history.push_call_history_item(self, CallType.CONTAINER, self, self.input_data) self.child_state = self.get_start_state(set_final_outcome=True) if self.child_state is None: self.child_state = self.handle_no_start_state()
This function covers the whole initialization routine before executing a hierarchy state. :return:
entailment
def run(self): """ This defines the sequence of actions that are taken when the hierarchy is executed. A hierarchy state executes all its child states recursively. Principally this code collects all input data for the next child state, executes it, stores its output data and determines the next state based on the outcome of the child state. :return: """ try: self._initialize_hierarchy() while self.child_state is not self: # print("hs1", self.name) self.handling_execution_mode = True execution_mode = singleton.state_machine_execution_engine.handle_execution_mode(self, self.child_state) # in the case of starting the sm from a specific state not the transitions define the logic flow # but the the execution_engine.run_to_states; thus, do not alter the next state in this case if not self._start_state_modified: # check if e.g. the state machine was paused and the next state was modified (e.g. removed) self.check_if_child_state_was_modified() self.handling_execution_mode = False if self.state_execution_status is not StateExecutionStatus.EXECUTE_CHILDREN: self.state_execution_status = StateExecutionStatus.EXECUTE_CHILDREN # print("hs2", self.name) self.backward_execution = False if self.preempted: if self.last_transition and self.last_transition.from_outcome == -2: logger.debug("Execute preemption handling for '{0}'".format(self.child_state)) else: break elif execution_mode == StateMachineExecutionStatus.BACKWARD: break_loop = self._handle_backward_execution_before_child_execution() if break_loop: break # This is only the case if this hierarchy-state is started in backward mode, # but the user directly switches to the forward execution mode if self.child_state is None: break # print("hs3", self.name) self._execute_current_child() if self.backward_execution: # print("hs4", self.name) break_loop = self._handle_backward_execution_after_child_execution() if break_loop: # print("hs4.1", self.name) break else: # print("hs5", self.name) break_loop = self._handle_forward_execution_after_child_execution() if break_loop: break # print("hs6", self.name) return self._finalize_hierarchy() except Exception as e: logger.error("{0} had an internal error: {1}\n{2}".format(self, str(e), str(traceback.format_exc()))) self.output_data["error"] = e self.state_execution_status = StateExecutionStatus.WAIT_FOR_NEXT_STATE self.child_state = None self.last_child = None return self.finalize(Outcome(-1, "aborted"))
This defines the sequence of actions that are taken when the hierarchy is executed. A hierarchy state executes all its child states recursively. Principally this code collects all input data for the next child state, executes it, stores its output data and determines the next state based on the outcome of the child state. :return:
entailment
def _handle_backward_execution_before_child_execution(self): """ Sets up all data after receiving a backward execution step from the execution engine :return: a flag to indicate if normal child state execution should abort """ self.backward_execution = True last_history_item = self.execution_history.pop_last_item() if last_history_item.state_reference is self: # if the the next child_state in the history is self exit this hierarchy-state if self.child_state: # do not set the last state to inactive before executing the new one self.child_state.state_execution_status = StateExecutionStatus.INACTIVE return True assert isinstance(last_history_item, ReturnItem) self.scoped_data = last_history_item.scoped_data self.child_state = last_history_item.state_reference return False
Sets up all data after receiving a backward execution step from the execution engine :return: a flag to indicate if normal child state execution should abort
entailment
def _execute_current_child(self): """ Collect all data for a child state and execute it. :return: """ self.child_state.input_data = self.get_inputs_for_state(self.child_state) self.child_state.output_data = self.create_output_dictionary_for_state(self.child_state) # process data of last state if self.last_error: self.child_state.input_data['error'] = copy.deepcopy(self.last_error) self.last_error = None if self.last_child: # do not set the last state to inactive before executing the new one self.last_child.state_execution_status = StateExecutionStatus.INACTIVE self.child_state.generate_run_id() if not self.backward_execution: # only add history item if it is not a backward execution self.execution_history.push_call_history_item( self.child_state, CallType.EXECUTE, self, self.child_state.input_data) self.child_state.start(self.execution_history, backward_execution=self.backward_execution, generate_run_id=False) self.child_state.join() # this line is important to indicate the parent the current execution status # it may also change during the execution of an hierarchy state # e.g. a hierarchy state may be started in forward execution mode but can leave in backward execution mode # print(self.child_state) # print(self.child_state.backward_execution) self.backward_execution = self.child_state.backward_execution # for h in self.execution_history._history_items: # print(h) if self.preempted: if self.backward_execution: # this is the case if the user backward step through its state machine and stops it # as preemption behaviour in backward mode is not defined, set the state to forward mode # to ensure clean state machine shutdown self.backward_execution = False # set last_error and self.last_child if self.child_state.final_outcome is not None: # final outcome can be None if only one state in a # hierarchy state is executed and immediately backward executed if self.child_state.final_outcome.outcome_id == -1: # if the child_state aborted save the error self.last_error = "" if 'error' in self.child_state.output_data: self.last_error = self.child_state.output_data['error'] self.last_child = self.child_state
Collect all data for a child state and execute it. :return:
entailment
def _handle_backward_execution_after_child_execution(self): """Cleanup the former child state execution and prepare for the next state execution in the backward execution case. :return: a flag to indicate if normal child state execution should abort """ self.child_state.state_execution_status = StateExecutionStatus.WAIT_FOR_NEXT_STATE # the item popped now from the history will be a CallItem and will contain the scoped data, # that was valid before executing the child_state last_history_item = self.execution_history.pop_last_item() assert isinstance(last_history_item, CallItem) # copy the scoped_data of the history from the point before the child_state was executed self.scoped_data = last_history_item.scoped_data # this is a look-ahead step to directly leave this hierarchy-state if the last child_state # was executed; this leads to the backward and forward execution of a hierarchy child_state # having the exact same number of steps last_history_item = self.execution_history.get_last_history_item() if last_history_item.state_reference is self: last_history_item = self.execution_history.pop_last_item() assert isinstance(last_history_item, CallItem) self.scoped_data = last_history_item.scoped_data self.child_state.state_execution_status = StateExecutionStatus.INACTIVE return True return False
Cleanup the former child state execution and prepare for the next state execution in the backward execution case. :return: a flag to indicate if normal child state execution should abort
entailment
def _handle_forward_execution_after_child_execution(self): """ Cleanup the former child state execution and prepare for the next state execution in the forward execution case. :return: a flag to indicate if normal child state execution should abort """ self.add_state_execution_output_to_scoped_data(self.child_state.output_data, self.child_state) self.update_scoped_variables_with_output_dictionary(self.child_state.output_data, self.child_state) self.execution_history.push_return_history_item( self.child_state, CallType.EXECUTE, self, self.child_state.output_data) # not explicitly connected preempted outcomes are implicit connected to parent preempted outcome transition = self.get_transition_for_outcome(self.child_state, self.child_state.final_outcome) if transition is None: transition = self.handle_no_transition(self.child_state) # if the transition is still None, then the child_state was preempted or aborted, in this case # return if transition is None: return True self.last_transition = transition self.child_state = self.get_state_for_transition(transition) if transition is not None and self.child_state is self: self.final_outcome = self.outcomes[transition.to_outcome] if self.child_state is self: singleton.state_machine_execution_engine._modify_run_to_states(self) return False
Cleanup the former child state execution and prepare for the next state execution in the forward execution case. :return: a flag to indicate if normal child state execution should abort
entailment
def _finalize_hierarchy(self): """ This function finalizes the execution of a hierarchy state. It sets the correct status and manages the output data handling. :return: """ if self.last_child: self.last_child.state_execution_status = StateExecutionStatus.INACTIVE if not self.backward_execution: if self.last_error: self.output_data['error'] = copy.deepcopy(self.last_error) self.write_output_data() self.check_output_data_type() self.execution_history.push_return_history_item(self, CallType.CONTAINER, self, self.output_data) # add error message from child_state to own output_data self.state_execution_status = StateExecutionStatus.WAIT_FOR_NEXT_STATE if self.preempted: self.final_outcome = Outcome(-2, "preempted") self.child_state = None self.last_child = None return self.finalize(self.final_outcome)
This function finalizes the execution of a hierarchy state. It sets the correct status and manages the output data handling. :return:
entailment
def rotate_and_detach_tab_labels(self): """Rotates tab labels of a given notebook by 90 degrees and makes them detachable. :param notebook: GTK Notebook container, whose tab labels are to be rotated and made detachable """ icons = {'Libraries': constants.SIGN_LIB, 'States Tree': constants.ICON_TREE, 'Global Variables': constants.ICON_GLOB, 'Modification History': constants.ICON_HIST, 'Execution History': constants.ICON_EHIST, 'network': constants.ICON_NET} for notebook in self.left_bar_notebooks: for i in range(notebook.get_n_pages()): child = notebook.get_nth_page(i) tab_label = notebook.get_tab_label(child) tab_label_text = tab_label.get_text() notebook.set_tab_label(child, gui_helper_label.create_tab_header_label(tab_label_text, icons)) notebook.set_tab_reorderable(child, True) notebook.set_tab_detachable(child, True)
Rotates tab labels of a given notebook by 90 degrees and makes them detachable. :param notebook: GTK Notebook container, whose tab labels are to be rotated and made detachable
entailment
def bring_tab_to_the_top(self, tab_label): """Find tab with label tab_label in list of notebooks and set it to the current page. :param tab_label: String containing the label of the tab to be focused """ found = False for notebook in self.left_bar_notebooks: for i in range(notebook.get_n_pages()): if gui_helper_label.get_notebook_tab_title(notebook, i) == gui_helper_label.get_widget_title(tab_label): found = True break if found: notebook.set_current_page(i) break
Find tab with label tab_label in list of notebooks and set it to the current page. :param tab_label: String containing the label of the tab to be focused
entailment
def add_transitions_from_selected_state_to_parent(): """ Generates the default success transition of a state to its parent success port :return: """ task_string = "create transition" sub_task_string = "to parent state" selected_state_m, msg = get_selected_single_state_model_and_check_for_its_parent() if selected_state_m is None: logger.warning("Can not {0} {1}: {2}".format(task_string, sub_task_string, msg)) return logger.debug("Check to {0} {1} ...".format(task_string, sub_task_string)) state = selected_state_m.state parent_state = state.parent # find all possible from outcomes from_outcomes = get_all_outcomes_except_of_abort_and_preempt(state) # find lowest valid outcome id possible_oc_ids = [oc_id for oc_id in state.parent.outcomes.keys() if oc_id >= 0] possible_oc_ids.sort() to_outcome = state.parent.outcomes[possible_oc_ids[0]] oc_connected_to_parent = [oc for oc in from_outcomes if is_outcome_connect_to_state(oc, parent_state.state_id)] oc_not_connected = [oc for oc in from_outcomes if not state.parent.get_transition_for_outcome(state, oc)] if all(oc in oc_connected_to_parent for oc in from_outcomes): logger.info("Remove transition {0} because all outcomes are connected to it.".format(sub_task_string)) for from_outcome in oc_connected_to_parent: transition = parent_state.get_transition_for_outcome(state, from_outcome) parent_state.remove(transition) elif oc_not_connected: logger.debug("Create transition {0} ... ".format(sub_task_string)) for from_outcome in from_outcomes: parent_state.add_transition(state.state_id, from_outcome.outcome_id, parent_state.state_id, to_outcome.outcome_id) else: if remove_transitions_if_target_is_the_same(from_outcomes): logger.info("Removed transitions origin from outcomes of selected state {0}" "because all point to the same target.".format(sub_task_string)) return add_transitions_from_selected_state_to_parent() logger.info("Will not create transition {0}: Not clear situation of connected transitions." "There will be no transitions to other states be touched.".format(sub_task_string)) return True
Generates the default success transition of a state to its parent success port :return:
entailment
def add_transitions_to_closest_sibling_state_from_selected_state(): """ Generates the outcome transitions from outcomes with positive outcome_id to the closest next state :return: """ task_string = "create transition" sub_task_string = "to closest sibling state" selected_state_m, msg = get_selected_single_state_model_and_check_for_its_parent() if selected_state_m is None: logger.warning("Can not {0} {1}: {2}".format(task_string, sub_task_string, msg)) return logger.debug("Check to {0} {1} ...".format(task_string, sub_task_string)) state = selected_state_m.state parent_state = state.parent # find closest other state to connect to -> to_state closest_sibling_state_tuple = gui_helper_meta_data.get_closest_sibling_state(selected_state_m, 'outcome') if closest_sibling_state_tuple is None: logger.info("Can not {0} {1}: There is no other sibling state.".format(task_string, sub_task_string)) return distance, sibling_state_m = closest_sibling_state_tuple to_state = sibling_state_m.state # find all possible from outcomes from_outcomes = get_all_outcomes_except_of_abort_and_preempt(state) from_oc_not_connected = [oc for oc in from_outcomes if not state.parent.get_transition_for_outcome(state, oc)] # all ports not connected connect to next state income if from_oc_not_connected: logger.debug("Create transition {0} ...".format(sub_task_string)) for from_outcome in from_oc_not_connected: parent_state.add_transition(state.state_id, from_outcome.outcome_id, to_state.state_id, None) # no transitions are removed if not all connected to the same other state else: target = remove_transitions_if_target_is_the_same(from_outcomes) if target: target_state_id, _ = target if not target_state_id == to_state.state_id: logger.info("Removed transitions from outcomes {0} " "because all point to the same target.".format(sub_task_string.replace('closest ', ''))) add_transitions_to_closest_sibling_state_from_selected_state() else: logger.info("Removed transitions from outcomes {0} " "because all point to the same target.".format(sub_task_string)) return True logger.info("Will not {0} {1}: Not clear situation of connected transitions." "There will be no transitions to other states be touched.".format(task_string, sub_task_string)) return True
Generates the outcome transitions from outcomes with positive outcome_id to the closest next state :return:
entailment
def add_coordinates(network): """ Add coordinates to nodes based on provided geom Parameters ---------- network : PyPSA network container Returns ------- Altered PyPSA network container ready for plotting """ for idx, row in network.buses.iterrows(): wkt_geom = to_shape(row['geom']) network.buses.loc[idx, 'x'] = wkt_geom.x network.buses.loc[idx, 'y'] = wkt_geom.y return network
Add coordinates to nodes based on provided geom Parameters ---------- network : PyPSA network container Returns ------- Altered PyPSA network container ready for plotting
entailment
def plot_line_loading( network, timesteps=range(1,2), filename=None, boundaries=[], arrows=False): """ Plots line loading as a colored heatmap. Line loading is displayed as relative to nominal capacity in %. Parameters ---------- network : PyPSA network container Holds topology of grid including results from powerflow analysis timesteps : range Defines which timesteps are considered. If more than one, an average line loading is calculated. filename : str Specify filename If not given, figure will be show directly boundaries : list If given, the colorbar is fixed to a given min and max value arrows : bool If True, the direction of the power flows is displayed as arrows. """ # TODO: replace p0 by max(p0,p1) and analogously for q0 # TODO: implement for all given snapshots # calculate relative line loading as S/S_nom # with S = sqrt(P^2 + Q^2) cmap = plt.cm.jet array_line = [['Line'] * len(network.lines), network.lines.index] array_link = [['Link'] * len(network.links), network.links.index] if network.lines_t.q0.empty: loading_lines = pd.Series((network.lines_t.p0.mul( network.snapshot_weightings, axis=0).loc[network.snapshots[ timesteps]].abs().sum() / (network.lines.s_nom_opt)).data, index=array_line) else: loading_lines = pd.Series(((network.lines_t.p0.mul( network.snapshot_weightings, axis=0)\ .loc[network.snapshots[timesteps]].abs().sum() ** 2 +\ network.lines_t.q0.mul( network.snapshot_weightings, axis=0)\ .loc[network.snapshots[timesteps]].abs().sum() ** 2).\ apply(sqrt) / (network.lines.s_nom_opt)).data, index = array_line) # Aviod covering of bidirectional links network.links['linked_to'] = 0 for i, row in network.links.iterrows(): if not (network.links.index[(network.links.bus0 == row['bus1']) & (network.links.bus1 == row['bus0']) & (network.links.length == row['length'] )]).empty: l = network.links.index[(network.links.bus0 == row['bus1']) & (network.links.bus1 == row['bus0']) & (network.links.length == row['length'])] network.links.set_value(i, 'linked_to',l.values[0]) network.links.linked_to = network.links.linked_to.astype(str) link_load = network.links_t.p0[network.links.index[ network.links.linked_to == '0']] for i, row in network.links[network.links.linked_to != '0'].iterrows(): load = pd.DataFrame(index = network.links_t.p0.index, columns = ['to', 'from']) load['to'] = network.links_t.p0[row['linked_to']] load['from'] = network.links_t.p0[i] link_load[i] = load.abs().max(axis = 1) loading_links = pd.Series((link_load.mul( network.snapshot_weightings, axis=0).loc[network.snapshots[ timesteps]].abs().sum()[network.links.index] / ( network.links.p_nom_opt)).data, index=array_link).dropna() load_links_rel = (loading_links/ network.snapshot_weightings\ [network.snapshots[timesteps]].sum())* 100 load_lines_rel = (loading_lines / network.snapshot_weightings\ [network.snapshots[timesteps]].sum()) * 100 loading = load_lines_rel.append(load_links_rel) ll = network.plot(line_colors=loading, line_cmap=cmap, title="Line loading", line_widths=0.55) # add colorbar, note mappable sliced from ll by [1] if not boundaries: v = np.linspace(min(loading), max(loading), 101) boundaries = [min(loading), max(loading)] else: v = np.linspace(boundaries[0], boundaries[1], 101) cb = plt.colorbar(ll[1], boundaries=v, ticks=v[0:101:10]) cb_Link = plt.colorbar(ll[2], boundaries=v, ticks=v[0:101:10]) cb.set_clim(vmin=boundaries[0], vmax=boundaries[1]) cb_Link.set_clim(vmin=boundaries[0], vmax=boundaries[1]) cb_Link.remove() cb.set_label('Line loading in %') if arrows: ax = plt.axes() path = ll[1].get_segments() x_coords_lines = np.zeros([len(path)]) cmap = cmap colors = cmap(ll[1].get_array() / 100) for i in range(0, len(path)): x_coords_lines[i] = network.buses.loc[str( network.lines.iloc[i, 2]), 'x'] color = colors[i] if (x_coords_lines[i] == path[i][0][0] and load_lines_rel[i] >= 0): arrowprops = dict(arrowstyle="->", color=color) else: arrowprops = dict(arrowstyle="<-", color=color) ax.annotate( "", xy=abs( (path[i][0] - path[i][1]) * 0.51 - path[i][0]), xytext=abs( (path[i][0] - path[i][1]) * 0.49 - path[i][0]), arrowprops=arrowprops, size=10) if filename is None: plt.show() else: plt.savefig(filename) plt.close()
Plots line loading as a colored heatmap. Line loading is displayed as relative to nominal capacity in %. Parameters ---------- network : PyPSA network container Holds topology of grid including results from powerflow analysis timesteps : range Defines which timesteps are considered. If more than one, an average line loading is calculated. filename : str Specify filename If not given, figure will be show directly boundaries : list If given, the colorbar is fixed to a given min and max value arrows : bool If True, the direction of the power flows is displayed as arrows.
entailment
def plot_line_loading_diff(networkA, networkB, timestep=0): """ Plot difference in line loading between two networks (with and without switches) as color on lines Positive values mean that line loading with switches is bigger than without Plot switches as small dots Parameters ---------- networkA : PyPSA network container Holds topology of grid with switches including results from powerflow analysis networkB : PyPSA network container Holds topology of grid without switches including results from powerflow analysis filename : str Specify filename If not given, figure will be show directly timestep : int timestep to show, default is 0 """ # new colormap to make sure 0% difference has the same color in every plot def shiftedColorMap( cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'): ''' Function to offset the "center" of a colormap. Useful for data with a negative min and positive max and you want the middle of the colormap's dynamic range to be at zero Input ----- cmap : The matplotlib colormap to be altered start : Offset from lowest point in the colormap's range. Defaults to 0.0 (no lower ofset). Should be between 0.0 and `midpoint`. midpoint : The new center of the colormap. Defaults to 0.5 (no shift). Should be between 0.0 and 1.0. In general, this should be 1 - vmax/(vmax + abs(vmin)) For example if your data range from -15.0 to +5.0 and you want the center of the colormap at 0.0, `midpoint` should be set to 1 - 5/(5 + 15)) or 0.75 stop : Offset from highets point in the colormap's range. Defaults to 1.0 (no upper ofset). Should be between `midpoint` and 1.0. ''' cdict = { 'red': [], 'green': [], 'blue': [], 'alpha': [] } # regular index to compute the colors reg_index = np.linspace(start, stop, 257) # shifted index to match the data shift_index = np.hstack([ np.linspace(0.0, midpoint, 128, endpoint=False), np.linspace(midpoint, 1.0, 129, endpoint=True) ]) for ri, si in zip(reg_index, shift_index): r, g, b, a = cmap(ri) cdict['red'].append((si, r, r)) cdict['green'].append((si, g, g)) cdict['blue'].append((si, b, b)) cdict['alpha'].append((si, a, a)) newcmap = matplotlib.colors.LinearSegmentedColormap(name, cdict) plt.register_cmap(cmap=newcmap) return newcmap # calculate difference in loading between both networks loading_switches = abs( networkA.lines_t.p0.mul(networkA.snapshot_weightings, axis=0).\ loc[networkA.snapshots[timestep]].to_frame()) loading_switches.columns = ['switch'] loading_noswitches = abs( networkB.lines_t.p0.mul(networkB.snapshot_weightings, axis=0).\ loc[networkB.snapshots[timestep]].to_frame()) loading_noswitches.columns = ['noswitch'] diff_network = loading_switches.join(loading_noswitches) diff_network['noswitch'] = diff_network['noswitch'].fillna( diff_network['switch']) diff_network[networkA.snapshots[timestep]] \ = diff_network['switch'] - diff_network['noswitch'] # get switches new_buses = pd.Series(index=networkA.buses.index.values) new_buses.loc[set(networkA.buses.index.values) - set(networkB.buses.index.values)] = 0.1 new_buses = new_buses.fillna(0) # plot network with difference in loading and shifted colormap loading = (diff_network.loc[:, networkA.snapshots[timestep]] / (networkA.lines.s_nom)) * 100 midpoint = 1 - max(loading) / (max(loading) + abs(min(loading))) shifted_cmap = shiftedColorMap( plt.cm.jet, midpoint=midpoint, name='shifted') ll = networkA.plot(line_colors=loading, line_cmap=shifted_cmap, title="Line loading", bus_sizes=new_buses, bus_colors='blue', line_widths=0.55) cb = plt.colorbar(ll[1]) cb.set_label('Difference in line loading in % of s_nom')
Plot difference in line loading between two networks (with and without switches) as color on lines Positive values mean that line loading with switches is bigger than without Plot switches as small dots Parameters ---------- networkA : PyPSA network container Holds topology of grid with switches including results from powerflow analysis networkB : PyPSA network container Holds topology of grid without switches including results from powerflow analysis filename : str Specify filename If not given, figure will be show directly timestep : int timestep to show, default is 0
entailment
def network_expansion(network, method = 'rel', ext_min=0.1, ext_width=False, filename=None, boundaries=[]): """Plot relative or absolute network extension of AC- and DC-lines. Parameters ---------- network: PyPSA network container Holds topology of grid including results from powerflow analysis method: str Choose 'rel' for extension relative to s_nom and 'abs' for absolute extensions. ext_min: float Choose minimum relative line extension shown in plot in p.u.. ext_width: float or bool Choose if line_width respects line extension. Turn off with 'False' or set linear factor to decremise extension line_width. filename: str or None Save figure in this direction boundaries: array Set boundaries of heatmap axis """ cmap = plt.cm.jet overlay_network = network.copy() overlay_network.lines = overlay_network.lines[ overlay_network.lines.s_nom_extendable & (( overlay_network.lines.s_nom_opt - overlay_network.lines.s_nom_min) / overlay_network.lines.s_nom >= ext_min)] overlay_network.links = overlay_network.links[ overlay_network.links.p_nom_extendable & (( overlay_network.links.p_nom_opt - overlay_network.links.p_nom_min)/ overlay_network.links.p_nom >= ext_min)] for i, row in overlay_network.links.iterrows(): linked = overlay_network.links[(row['bus1'] == overlay_network.links.bus0) & ( row['bus0'] == overlay_network.links.bus1)] if not linked.empty: if row['p_nom_opt'] < linked.p_nom_opt.values[0]: overlay_network.links.p_nom_opt[i] = linked.p_nom_opt.values[0] array_line = [['Line'] * len(overlay_network.lines), overlay_network.lines.index] array_link = [['Link'] * len(overlay_network.links), overlay_network.links.index] if method == 'rel': extension_lines = pd.Series((100 * (overlay_network.lines.s_nom_opt - overlay_network.lines.s_nom_min) / overlay_network.lines.s_nom).data, index=array_line) extension_links = pd.Series((100 * (overlay_network.links.p_nom_opt - overlay_network.links.p_nom_min)/ (overlay_network.links.p_nom)).data, index=array_link) if method == 'abs': extension_lines = pd.Series( (overlay_network.lines.s_nom_opt - overlay_network.lines.s_nom_min).data, index=array_line) extension_links = pd.Series( (overlay_network.links.p_nom_opt - overlay_network.links.p_nom_min).data, index=array_link) extension = extension_lines.append(extension_links) # Plot whole network in backgroud of plot network.plot( line_colors=pd.Series("grey", index = [['Line'] * len( network.lines), network.lines.index]).append( pd.Series("grey", index = [['Link'] * len(network.links), network.links.index])), bus_sizes=0, line_widths=pd.Series(0.5, index = [['Line'] * len(network.lines), network.lines.index]).append( pd.Series(0.55, index = [['Link'] * len(network.links), network.links.index]))) if not ext_width: line_widths= pd.Series(0.8, index = array_line).append( pd.Series(0.8, index = array_link)) else: line_widths= 0.5 + (extension / ext_width) ll = overlay_network.plot( line_colors=extension, line_cmap=cmap, bus_sizes=0, title="Optimized AC- and DC-line expansion", line_widths=line_widths) if not boundaries: v = np.linspace(min(extension), max(extension), 101) boundaries = [min(extension), max(extension)] else: v = np.linspace(boundaries[0], boundaries[1], 101) if not extension_links.empty: cb_Link = plt.colorbar(ll[2], boundaries=v, ticks=v[0:101:10]) cb_Link.set_clim(vmin=boundaries[0], vmax=boundaries[1]) cb_Link.remove() cb = plt.colorbar(ll[1], boundaries=v, ticks=v[0:101:10], fraction=0.046, pad=0.04) cb.set_clim(vmin=boundaries[0], vmax=boundaries[1]) if method == 'rel': cb.set_label('line expansion relative to s_nom in %') if method == 'abs': cb.set_label('line expansion in MW') if filename is None: plt.show() else: plt.savefig(filename) plt.close()
Plot relative or absolute network extension of AC- and DC-lines. Parameters ---------- network: PyPSA network container Holds topology of grid including results from powerflow analysis method: str Choose 'rel' for extension relative to s_nom and 'abs' for absolute extensions. ext_min: float Choose minimum relative line extension shown in plot in p.u.. ext_width: float or bool Choose if line_width respects line extension. Turn off with 'False' or set linear factor to decremise extension line_width. filename: str or None Save figure in this direction boundaries: array Set boundaries of heatmap axis
entailment
def network_expansion_diff (networkA, networkB, filename=None, boundaries=[]): """Plot relative network expansion derivation of AC- and DC-lines. Parameters ---------- networkA: PyPSA network container Holds topology of grid including results from powerflow analysis networkB: PyPSA network container Holds topology of grid including results from powerflow analysis filename: str or None Save figure in this direction boundaries: array Set boundaries of heatmap axis """ cmap = plt.cm.jet array_line = [['Line'] * len(networkA.lines), networkA.lines.index] extension_lines = pd.Series(100 *\ ((networkA.lines.s_nom_opt - \ networkB.lines.s_nom_opt)/\ networkA.lines.s_nom_opt ).values,\ index=array_line) array_link = [['Link'] * len(networkA.links), networkA.links.index] extension_links = pd.Series(100 * ((networkA.links.p_nom_opt -\ networkB.links.p_nom_opt)/\ networkA.links.p_nom_opt).values,\ index=array_link) extension = extension_lines.append(extension_links) ll = networkA.plot( line_colors=extension, line_cmap=cmap, bus_sizes=0, title="Derivation of AC- and DC-line extension", line_widths=2) if not boundaries: v = np.linspace(min(extension), max(extension), 101) boundaries = [min(extension).round(0), max(extension).round(0)] else: v = np.linspace(boundaries[0], boundaries[1], 101) if not extension_links.empty: cb_Link = plt.colorbar(ll[2], boundaries=v, ticks=v[0:101:10]) cb_Link.set_clim(vmin=boundaries[0], vmax=boundaries[1]) cb_Link.remove() cb = plt.colorbar(ll[1], boundaries=v, ticks=v[0:101:10], fraction=0.046, pad=0.04) cb.set_clim(vmin=boundaries[0], vmax=boundaries[1]) cb.set_label('line extension derivation in %') if filename is None: plt.show() else: plt.savefig(filename) plt.close()
Plot relative network expansion derivation of AC- and DC-lines. Parameters ---------- networkA: PyPSA network container Holds topology of grid including results from powerflow analysis networkB: PyPSA network container Holds topology of grid including results from powerflow analysis filename: str or None Save figure in this direction boundaries: array Set boundaries of heatmap axis
entailment
def full_load_hours(network, boundaries=[], filename=None, two_cb=False): """Plot loading of lines in equivalten full load hours. Parameters ---------- network: PyPSA network container Holds topology of grid including results from powerflow analysis filename: str or None Save figure in this direction boundaries: array Set boundaries of heatmap axis two_cb: bool Choose if an extra colorbar for DC-lines is plotted """ cmap = plt.cm.jet array_line = [['Line'] * len(network.lines), network.lines.index] load_lines = pd.Series(abs((network.lines_t.p0.mul( network.snapshot_weightings, axis=0).sum() / (network.lines.s_nom))).data, index=array_line) array_link = [['Link'] * len(network.links), network.links.index] load_links = pd.Series(abs((network.links_t.p0.mul( network.snapshot_weightings, axis=0).sum() / (network.links.p_nom))).data, index=array_link) load_hours = load_lines.append(load_links) ll = network.plot(line_colors=load_hours, line_cmap=cmap, bus_sizes=0, title="Full load-hours of lines", line_widths=2) if not boundaries: cb = plt.colorbar(ll[1]) cb_Link = plt.colorbar(ll[2]) elif boundaries: v = np.linspace(boundaries[0], boundaries[1], 101) cb_Link = plt.colorbar(ll[2], boundaries=v, ticks=v[0:101:10]) cb_Link.set_clim(vmin=boundaries[0], vmax=boundaries[1]) cb = plt.colorbar(ll[1], boundaries=v, ticks=v[0:101:10]) cb.set_clim(vmin=boundaries[0], vmax=boundaries[1]) if two_cb: cb_Link.set_label('Number of full-load hours of DC-lines') cb.set_label('Number of full-load hours of AC-lines') else: cb.set_label('Number of full-load hours') if filename is None: plt.show() else: plt.savefig(filename) plt.close()
Plot loading of lines in equivalten full load hours. Parameters ---------- network: PyPSA network container Holds topology of grid including results from powerflow analysis filename: str or None Save figure in this direction boundaries: array Set boundaries of heatmap axis two_cb: bool Choose if an extra colorbar for DC-lines is plotted
entailment
def plot_q_flows(network): """Plot maximal reactive line load. Parameters ---------- network: PyPSA network container Holds topology of grid including results from powerflow analysis """ cmap_line = plt.cm.jet q_flows_max = abs(network.lines_t.q0.abs().max()/(network.lines.s_nom)) ll = network.plot(line_colors = q_flows_max, line_cmap = cmap_line) boundaries = [min(q_flows_max), max(q_flows_max)] v = np.linspace(boundaries[0], boundaries[1], 101) cb = plt.colorbar(ll[1], boundaries=v, ticks=v[0:101:10]) cb.set_clim(vmin=boundaries[0], vmax=boundaries[1])
Plot maximal reactive line load. Parameters ---------- network: PyPSA network container Holds topology of grid including results from powerflow analysis
entailment
def max_load(network, boundaries=[], filename=None, two_cb=False): """Plot maximum loading of each line. Parameters ---------- network: PyPSA network container Holds topology of grid including results from powerflow analysis filename: str or None Save figure in this direction boundaries: array Set boundaries of heatmap axis two_cb: bool Choose if an extra colorbar for DC-lines is plotted """ cmap_line = plt.cm.jet cmap_link = plt.cm.jet array_line = [['Line'] * len(network.lines), network.lines.index] array_link = [['Link'] * len(network.links), network.links.index] if network.lines_t.q0.empty: load_lines = pd.Series((abs(network.lines_t.p0).max( ) / (network.lines.s_nom) * 100).data, index=array_line) else: load_lines = pd.Series(((network.lines_t.p0**2 + network.lines_t.q0 ** 2).max().apply(sqrt)/ (network.lines.s_nom) * 100).data, index=array_line) load_links = pd.Series((abs(network.links_t.p0.max( ) / (network.links.p_nom)) * 100).data, index=array_link) max_load = load_lines.append(load_links) ll = network.plot( line_colors=max_load, line_cmap={ 'Line': cmap_line, 'Link': cmap_link}, bus_sizes=0, title="Maximum of line loading", line_widths=2) if not boundaries: boundaries = [min(max_load), max(max_load)] v = np.linspace(boundaries[0], boundaries[1], 101) cb = plt.colorbar(ll[1], boundaries=v, ticks=v[0:101:10]) cb.set_clim(vmin=boundaries[0], vmax=boundaries[1]) cb_Link = plt.colorbar(ll[2], boundaries=v, ticks=v[0:101:10]) cb_Link.set_clim(vmin=boundaries[0], vmax=boundaries[1]) if two_cb: # cb_Link.set_label('Maximum load of DC-lines %') cb.set_label('Maximum load of AC-lines %') else: cb.set_label('Maximum load in %') if filename is None: plt.show() else: plt.savefig(filename) plt.close()
Plot maximum loading of each line. Parameters ---------- network: PyPSA network container Holds topology of grid including results from powerflow analysis filename: str or None Save figure in this direction boundaries: array Set boundaries of heatmap axis two_cb: bool Choose if an extra colorbar for DC-lines is plotted
entailment
def load_hours(network, min_load=0.9, max_load=1, boundaries=[0, 8760]): """Plot number of hours with line loading in selected range. Parameters ---------- network: PyPSA network container Holds topology of grid including results from powerflow analysis min_load: float Choose lower bound of relative load max_load: float Choose upper bound of relative load boundaries: array Set boundaries of heatmap axis """ cmap_line = plt.cm.jet cmap_link = plt.cm.jet array_line = [['Line'] * len(network.lines), network.lines.index] load_lines = pd.Series(((abs(network.lines_t.p0[( abs(network.lines_t.p0.mul(network.snapshot_weightings, axis=0)) / network.lines.s_nom_opt >= min_load) & ( abs(network.lines_t.p0.mul(network.snapshot_weightings, axis=0)) / network.lines.s_nom_opt <= max_load)]) / abs(network.lines_t.p0[( abs(network.lines_t.p0) / network.lines.s_nom_opt >= min_load) & (abs(network.lines_t.p0) / network.lines.s_nom_opt <= max_load)])) .sum()).data, index=array_line) array_link = [['Link'] * len(network.links), network.links.index] load_links = pd.Series(((abs(network.links_t.p0[( abs(network.links_t.p0.mul(network.snapshot_weightings, axis=0)) / network.links.p_nom_opt >= min_load) & ( abs(network.links_t.p0.mul(network.snapshot_weightings, axis=0)) / network.links.p_nom_opt <= max_load)]) / abs(network.links_t.p0[( abs(network.links_t.p0) / network.links.p_nom_opt >= min_load) & (abs(network.links_t.p0) / network.links.p_nom_opt <= max_load)])) .sum()).data, index=array_link) load_hours = load_lines.append(load_links) ll = network.plot( line_colors=load_hours, line_cmap={ 'Line': cmap_line, 'Link': cmap_link}, bus_sizes=0, title="Number of hours with more then 90% load", line_widths=2) v1 = np.linspace(boundaries[0], boundaries[1], 101) v = np.linspace(boundaries[0], boundaries[1], 101) cb_Link = plt.colorbar(ll[2], boundaries=v1, ticks=v[0:101:10]) cb_Link.set_clim(vmin=boundaries[0], vmax=boundaries[1]) cb = plt.colorbar(ll[1], boundaries=v, ticks=v[0:101:10]) cb.set_clim(vmin=boundaries[0], vmax=boundaries[1]) cb.set_label('Number of hours')
Plot number of hours with line loading in selected range. Parameters ---------- network: PyPSA network container Holds topology of grid including results from powerflow analysis min_load: float Choose lower bound of relative load max_load: float Choose upper bound of relative load boundaries: array Set boundaries of heatmap axis
entailment
def plot_residual_load(network): """ Plots residual load summed of all exisiting buses. Parameters ---------- network : PyPSA network containter """ renewables = network.generators[ network.generators.carrier.isin(['wind_onshore', 'wind_offshore', 'solar', 'run_of_river', 'wind'])] renewables_t = network.generators.p_nom[renewables.index] * \ network.generators_t.p_max_pu[renewables.index].mul( network.snapshot_weightings, axis=0) load = network.loads_t.p_set.mul(network.snapshot_weightings, axis=0).\ sum(axis=1) all_renew = renewables_t.sum(axis=1) residual_load = load - all_renew plot = residual_load.plot( title = 'Residual load', drawstyle='steps', lw=2, color='red', legend=False) plot.set_ylabel("MW") # sorted curve sorted_residual_load = residual_load.sort_values( ascending=False).reset_index() plot1 = sorted_residual_load.plot( title='Sorted residual load', drawstyle='steps', lw=2, color='red', legend=False) plot1.set_ylabel("MW")
Plots residual load summed of all exisiting buses. Parameters ---------- network : PyPSA network containter
entailment
def plot_stacked_gen(network, bus=None, resolution='GW', filename=None): """ Plot stacked sum of generation grouped by carrier type Parameters ---------- network : PyPSA network container bus: string Plot all generators at one specific bus. If none, sum is calulated for all buses resolution: string Unit for y-axis. Can be either GW/MW/KW Returns ------- Plot """ if resolution == 'GW': reso_int = 1e3 elif resolution == 'MW': reso_int = 1 elif resolution == 'KW': reso_int = 0.001 # sum for all buses if bus is None: p_by_carrier = pd.concat([network.generators_t.p[network.generators [network.generators.control != 'Slack'].index], network.generators_t.p.mul( network.snapshot_weightings, axis=0) [network.generators[network.generators.control == 'Slack'].index] .iloc[:, 0].apply(lambda x: x if x > 0 else 0)], axis=1)\ .groupby(network.generators.carrier, axis=1).sum() load = network.loads_t.p.sum(axis=1) if hasattr(network, 'foreign_trade'): trade_sum = network.foreign_trade.sum(axis=1) p_by_carrier['imports'] = trade_sum[trade_sum > 0] p_by_carrier['imports'] = p_by_carrier['imports'].fillna(0) # sum for a single bus elif bus is not None: filtered_gens = network.generators[network.generators['bus'] == bus] p_by_carrier = network.generators_t.p.mul(network.snapshot_weightings, axis=0).groupby(filtered_gens.carrier, axis=1).abs().sum() filtered_load = network.loads[network.loads['bus'] == bus] load = network.loads_t.p.mul(network.snapshot_weightings, axis=0)\ [filtered_load.index] colors = coloring() # TODO: column reordering based on available columns fig, ax = plt.subplots(1, 1) fig.set_size_inches(12, 6) colors = [colors[col] for col in p_by_carrier.columns] if len(colors) == 1: colors = colors[0] (p_by_carrier / reso_int).plot(kind="area", ax=ax, linewidth=0, color=colors) (load / reso_int).plot(ax=ax, legend='load', lw=2, color='darkgrey', style='--') ax.legend(ncol=4, loc="upper left") ax.set_ylabel(resolution) ax.set_xlabel("") matplotlib.rcParams.update({'font.size': 22}) if filename is None: plt.show() else: plt.savefig(filename) plt.close()
Plot stacked sum of generation grouped by carrier type Parameters ---------- network : PyPSA network container bus: string Plot all generators at one specific bus. If none, sum is calulated for all buses resolution: string Unit for y-axis. Can be either GW/MW/KW Returns ------- Plot
entailment
def plot_gen_diff( networkA, networkB, leave_out_carriers=[ 'geothermal', 'oil', 'other_non_renewable', 'reservoir', 'waste']): """ Plot difference in generation between two networks grouped by carrier type Parameters ---------- networkA : PyPSA network container with switches networkB : PyPSA network container without switches leave_out_carriers : list of carriers to leave out (default to all small carriers) Returns ------- Plot """ def gen_by_c(network): gen = pd.concat([network.generators_t.p.mul( network.snapshot_weightings, axis=0)[network.generators [network.generators.control != 'Slack'].index], network.generators_t.p.mul( network.snapshot_weightings, axis=0)[network.generators [network. generators.control == 'Slack'].index] .iloc[:, 0].apply(lambda x: x if x > 0 else 0)], axis=1)\ .groupby(network.generators.carrier,axis=1).sum() return gen gen = gen_by_c(networkB) gen_switches = gen_by_c(networkA) diff = gen_switches - gen colors = coloring() diff.drop(leave_out_carriers, axis=1, inplace=True) colors = [colors[col] for col in diff.columns] plot = diff.plot(kind='line', color=colors, use_index=False) plot.legend(loc='upper left', ncol=5, prop={'size': 8}) x = [] for i in range(0, len(diff)): x.append(i) plt.xticks(x, x) plot.set_xlabel('Timesteps') plot.set_ylabel('Difference in Generation in MW') plot.set_title('Difference in Generation') plt.tight_layout()
Plot difference in generation between two networks grouped by carrier type Parameters ---------- networkA : PyPSA network container with switches networkB : PyPSA network container without switches leave_out_carriers : list of carriers to leave out (default to all small carriers) Returns ------- Plot
entailment
def plot_voltage(network, boundaries=[]): """ Plot voltage at buses as hexbin Parameters ---------- network : PyPSA network container boundaries: list of 2 values, setting the lower and upper bound of colorbar Returns ------- Plot """ x = np.array(network.buses['x']) y = np.array(network.buses['y']) alpha = np.array(network.buses_t.v_mag_pu.loc[network.snapshots[0]]) fig, ax = plt.subplots(1, 1) fig.set_size_inches(6, 4) cmap = plt.cm.jet if not boundaries: plt.hexbin(x, y, C=alpha, cmap=cmap, gridsize=100) cb = plt.colorbar() elif boundaries: v = np.linspace(boundaries[0], boundaries[1], 101) norm = matplotlib.colors.BoundaryNorm(v, cmap.N) plt.hexbin(x, y, C=alpha, cmap=cmap, gridsize=100, norm=norm) cb = plt.colorbar(boundaries=v, ticks=v[0:101:10], norm=norm) cb.set_clim(vmin=boundaries[0], vmax=boundaries[1]) cb.set_label('Voltage Magnitude per unit of v_nom') network.plot( ax=ax, line_widths=pd.Series(0.5, network.lines.index), bus_sizes=0) plt.show()
Plot voltage at buses as hexbin Parameters ---------- network : PyPSA network container boundaries: list of 2 values, setting the lower and upper bound of colorbar Returns ------- Plot
entailment
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 ------- Plot """ 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_available.groupby( network.generators.carrier, axis=1).sum() p_curtailed_by_carrier = p_available_by_carrier - p_by_carrier print(p_curtailed_by_carrier.sum()) p_df = pd.DataFrame({carrier + " available": p_available_by_carrier[carrier], carrier + " dispatched": p_by_carrier[carrier], carrier + " curtailed": p_curtailed_by_carrier[carrier]}) p_df[carrier + " capacity"] = capacity p_df[carrier + " curtailed"][p_df[carrier + " curtailed"] < 0.] = 0. fig, ax = plt.subplots(1, 1) fig.set_size_inches(12, 6) p_df[[carrier + " dispatched", carrier + " curtailed"] ].plot(kind="area", ax=ax, linewidth=3) p_df[[carrier + " available", carrier + " capacity"] ].plot(ax=ax, linewidth=3) ax.set_xlabel("") ax.set_ylabel("Power [MW]") ax.set_ylim([0, capacity * 1.1]) ax.legend() if filename is None: plt.show() else: plt.savefig(filename) plt.close()
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 ------- Plot
entailment
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, figure will be show directly """ 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_distribution.max() msd_median = storage_distribution[storage_distribution != 0].median() msd_min = storage_distribution[storage_distribution > 1].min() if msd_max != 0: LabelVal = int(log10(msd_max)) else: LabelVal = 0 if LabelVal < 0: LabelUnit = 'kW' msd_max, msd_median, msd_min = msd_max * \ 1000, msd_median * 1000, msd_min * 1000 storage_distribution = storage_distribution * 1000 elif LabelVal < 3: LabelUnit = 'MW' else: LabelUnit = 'GW' msd_max, msd_median, msd_min = msd_max / \ 1000, msd_median / 1000, msd_min / 1000 storage_distribution = storage_distribution / 1000 if sum(storage_distribution) == 0: network.plot(bus_sizes=0, ax=ax, title="No storages") else: network.plot( bus_sizes=storage_distribution * scaling, ax=ax, line_widths=0.3, title="Storage distribution") # Here we create a legend: # we'll plot empty lists with the desired size and label for area in [msd_max, msd_median, msd_min]: plt.scatter([], [], c='white', s=area * scaling, label='= ' + str(round(area, 0)) + LabelUnit + ' ') plt.legend(scatterpoints=1, labelspacing=1, title='Storage size') if filename is None: plt.show() else: plt.savefig(filename) plt.close()
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, figure will be show directly
entailment
def storage_expansion(network, basemap=True, 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, figure will be show directly """ stores = network.storage_units[network.storage_units.carrier == 'extendable_storage'] batteries = stores[stores.max_hours == 6] hydrogen = stores[stores.max_hours == 168] storage_distribution =\ network.storage_units.p_nom_opt[stores.index].groupby( network.storage_units.bus).sum().reindex( network.buses.index, fill_value=0.) battery_distribution =\ network.storage_units.p_nom_opt[batteries.index].groupby( network.storage_units.bus).sum().reindex( network.buses.index, fill_value=0.) hydrogen_distribution =\ network.storage_units.p_nom_opt[hydrogen.index].groupby( network.storage_units.bus).sum().reindex( network.buses.index, fill_value=0.) 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) & ( network.storage_units.capital_cost > 10) & ( network.storage_units.max_hours == 168)] fig, ax = plt.subplots(1, 1) fig.set_size_inches(6, 6) msd_max = storage_distribution.max() msd_max_bat = battery_distribution.max() msd_max_hyd = hydrogen_distribution.max() if msd_max != 0: LabelVal = int(log10(msd_max)) else: LabelVal = 0 if LabelVal < 0: LabelUnit = 'kW' msd_max, msd_max_bat, msd_max_hyd = msd_max * \ 1000, msd_max_bat * 1000, msd_max_hyd * 1000 battery_distribution = battery_distribution * 1000 hydrogen_distribution = hydrogen_distribution * 1000 elif LabelVal < 3: LabelUnit = 'MW' else: LabelUnit = 'GW' msd_max, msd_max_bat, msd_max_hyd = msd_max / \ 1000, msd_max_bat / 1000, msd_max_hyd / 1000 battery_distribution = battery_distribution / 1000 hydrogen_distribution = hydrogen_distribution / 1000 if network.storage_units.p_nom_opt[sbatt].sum() < 1 and\ network.storage_units.p_nom_opt[shydr].sum() < 1: print("No storage unit to plot") elif network.storage_units.p_nom_opt[sbatt].sum() > 1 and\ network.storage_units.p_nom_opt[shydr].sum() < 1: network.plot(bus_sizes=battery_distribution * scaling, bus_colors='orangered', ax=ax, line_widths=0.3) elif network.storage_units.p_nom_opt[sbatt].sum() < 1 and\ network.storage_units.p_nom_opt[shydr].sum() > 1: network.plot(bus_sizes=hydrogen_distribution * scaling, bus_colors='teal', ax=ax, line_widths=0.3) else: network.plot(bus_sizes=battery_distribution * scaling, bus_colors='orangered', ax=ax, line_widths=0.3) network.plot(bus_sizes=hydrogen_distribution * scaling, bus_colors='teal', ax=ax, line_widths=0.3) if basemap and basemap_present: x = network.buses["x"] y = network.buses["y"] x1 = min(x) x2 = max(x) y1 = min(y) y2 = max(y) bmap = Basemap(resolution='l', epsg=network.srid, llcrnrlat=y1, urcrnrlat=y2, llcrnrlon=x1, urcrnrlon=x2, ax=ax) bmap.drawcountries() bmap.drawcoastlines() if msd_max_hyd !=0: plt.scatter([], [], c='teal', s=msd_max_hyd * scaling, label='= ' + str(round(msd_max_hyd, 0)) + LabelUnit + ' hydrogen storage') if msd_max_bat !=0: plt.scatter([], [], c='orangered', s=msd_max_bat * scaling, label='= ' + str(round(msd_max_bat, 0)) + LabelUnit + ' battery storage') plt.legend(scatterpoints=1, labelspacing=1, title='Storage size and technology', borderpad=1.3, loc=2) ax.set_title("Storage expansion") if filename is None: plt.show() else: plt.savefig(filename) plt.close() return
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, figure will be show directly
entailment
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 Holds topology of grid with switches including results from powerflow analysis networkB : PyPSA network container Holds topology of grid without switches 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 plot gen_size : num size of generation bubbles at the buses filename : str Specify filename If not given, figure will be show directly """ 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, ncols=n_cols) size = 4 fig.set_size_inches(size * n_cols, size * n_rows) for i, tech in enumerate(techs): i_row = i // n_cols i_col = i % n_cols ax = axes[i_row, i_col] gensA = networkA.generators[networkA.generators.carrier == tech] gensB = networkB.generators[networkB.generators.carrier == tech] gen_distribution =\ networkA.generators_t.p.mul(networkA.snapshot_weightings, axis=0)\ [gensA.index].loc[networkA.snapshots[snapshot]].groupby( networkA.generators.bus).sum().reindex( networkA.buses.index, fill_value=0.) -\ networkB.generators_t.p.mul(networkB.snapshot_weightings, axis=0)\ [gensB.index].loc[networkB.snapshots[snapshot]].groupby( networkB.generators.bus).sum().reindex( networkB.buses.index, fill_value=0.) networkA.plot( ax=ax, bus_sizes=gen_size * abs(gen_distribution), bus_colors=gen_distribution, line_widths=0.1, bus_cmap=buscmap) ax.set_title(tech) if filename is None: plt.show() else: plt.savefig(filename) plt.close()
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 Holds topology of grid with switches including results from powerflow analysis networkB : PyPSA network container Holds topology of grid without switches 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 plot gen_size : num size of generation bubbles at the buses filename : str Specify filename If not given, figure will be show directly
entailment
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 plot gen_size : num size of generation bubbles at the buses filename : str Specify filename If not given, figure will be show directly """ 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, ncols=n_cols) size = 4 fig.set_size_inches(size * n_cols, size * n_rows) for i, tech in enumerate(techs): i_row = i // n_cols i_col = i % n_cols ax = axes[i_row, i_col] gens = network.generators[network.generators.carrier == tech] gen_distribution = network.generators_t.p.mul(network. snapshot_weightings, axis=0)\ [gens.index].loc[network.snapshots[snapshot]].groupby( network.generators.bus).sum().reindex( network.buses.index, fill_value=0.) network.plot( ax=ax, bus_sizes=gen_size * gen_distribution, line_widths=0.1) ax.set_title(tech) if filename is None: plt.show() else: plt.savefig(filename) plt.close()
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 plot gen_size : num size of generation bubbles at the buses filename : str Specify filename If not given, figure will be show directly
entailment
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', difference in dispatch between network and networkB is plotted. If item is 'capacity', networkB is ignored. default None techs : None or list, Techs to plot. If None, all techs are plotted. default ['wind_onshore', 'solar'] item : str Specifies the plotted item. Options are 'energy' and 'capacity'. default 'energy' direction : str Only considered if networkB is given and item is 'energy'. Specifies the direction of change in dispatch between network and networkB. If 'positive', generation per tech which is higher in network than in networkB is plotted. If 'negative', generation per tech whcih is lower in network than in networkB is plotted. If 'absolute', total change per node is plotted. Green nodes have higher dispatch in network than in networkB. Red nodes have lower dispatch in network than in networkB. default None scaling : int Scaling to change plot sizes. default 1 filename : path to folder """ 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, network.generators.carrier]).sum() elif item == 'energy': if networkB: dispatch_network =\ network.generators_t.p[gens.index].mul( network.snapshot_weightings, axis=0).groupby( [network.generators.bus, network.generators.carrier], axis=1).sum() dispatch_networkB =\ networkB.generators_t.p[gens.index].mul( networkB.snapshot_weightings, axis=0).groupby( [networkB.generators.bus, networkB.generators.carrier], axis=1).sum() dispatch = dispatch_network - dispatch_networkB if direction == 'positive': dispatch = dispatch[dispatch > 0].fillna(0) elif direction == 'negative': dispatch = dispatch[dispatch < 0].fillna(0) elif direction == 'absolute': pass else: return('No valid direction given.') dispatch = dispatch.sum() elif networkB is None: dispatch =\ network.generators_t.p[gens.index].mul( network.snapshot_weightings, axis=0).sum().groupby( [network.generators.bus, network.generators.carrier]).sum() fig, ax = plt.subplots(1, 1) scaling = 1/(max(abs(dispatch.groupby(level=0).sum())))*scaling if direction != 'absolute': colors = coloring() subcolors = {a: colors[a] for a in techs} dispatch = dispatch.abs() + 1e-9 else: dispatch = dispatch.sum(level=0) colors = {s[0]: 'green' if s[1] > 0 else 'red' for s in dispatch.iteritems()} dispatch = dispatch.abs() subcolors = {'negative': 'red', 'positive': 'green'} network.plot( bus_sizes=dispatch * scaling, bus_colors=colors, line_widths=0.2, margin=0.01, ax=ax) fig.subplots_adjust(right=0.8) plt.subplots_adjust(wspace=0, hspace=0.001) patchList = [] for key in subcolors: data_key = mpatches.Patch(color=subcolors[key], label=key) patchList.append(data_key) ax.legend(handles=patchList, loc='upper left') ax.autoscale() if filename is None: plt.show() else: plt.savefig(filename) plt.close() return
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', difference in dispatch between network and networkB is plotted. If item is 'capacity', networkB is ignored. default None techs : None or list, Techs to plot. If None, all techs are plotted. default ['wind_onshore', 'solar'] item : str Specifies the plotted item. Options are 'energy' and 'capacity'. default 'energy' direction : str Only considered if networkB is given and item is 'energy'. Specifies the direction of change in dispatch between network and networkB. If 'positive', generation per tech which is higher in network than in networkB is plotted. If 'negative', generation per tech whcih is lower in network than in networkB is plotted. If 'absolute', total change per node is plotted. Green nodes have higher dispatch in network than in networkB. Red nodes have lower dispatch in network than in networkB. default None scaling : int Scaling to change plot sizes. default 1 filename : path to folder
entailment
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 to change plot sizes. default 0.0001 filename : path to folder """ 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] diff = (gen - load).loc[timestep] colors = {s[0]: 'green' if s[1] > 0 else 'red' for s in diff.iteritems()} subcolors = {'Net Consumer': 'red', 'Net Producer': 'green'} diff = diff.abs() network.plot( bus_sizes=diff * scaling, bus_colors=colors, line_widths=0.2, margin=0.01, ax=ax) patchList = [] for key in subcolors: data_key = mpatches.Patch(color=subcolors[key], label=key) patchList.append(data_key) ax.legend(handles=patchList, loc='upper left') ax.autoscale() if filename: plt.savefig(filename) plt.close() return
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 to change plot sizes. default 0.0001 filename : path to folder
entailment
def storage_p_soc(network, mean='1H', filename = None): """ Plots the dispatch and state of charge (SOC) of extendable storages. Parameters ---------- network : PyPSA network container Holds topology of grid including results from powerflow analysis mean : str Defines over how many snapshots the p and soc values will averaged. filename : path to folder """ 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) & (network.storage_units.capital_cost > 10) & (network.storage_units.max_hours == 168)] cap_batt = (network.storage_units.max_hours[sbatt] * network.storage_units.p_nom_opt[sbatt]).sum() cap_hydr = (network.storage_units.max_hours[shydr] * network.storage_units.p_nom_opt[shydr]).sum() fig, ax = plt.subplots(1, 1) if network.storage_units.p_nom_opt[sbatt].sum() < 1 and \ network.storage_units.p_nom_opt[shydr].sum() < 1: print("No storage unit to plot") elif network.storage_units.p_nom_opt[sbatt].sum() > 1 and \ network.storage_units.p_nom_opt[shydr].sum() < 1: (network.storage_units_t.p[sbatt].resample(mean).mean().sum(axis=1) / \ network.storage_units.p_nom_opt[sbatt].sum()).plot( ax=ax, label="Battery dispatch", color='orangered') # instantiate a second axes that shares the same x-axis ax2 = ax.twinx() ((network.storage_units_t.state_of_charge[sbatt].resample(mean).\ mean().sum(axis=1) / cap_batt)*100).plot(ax=ax2, label="Battery state of charge", color='blue') elif network.storage_units.p_nom_opt[sbatt].sum() < 1 and\ network.storage_units.p_nom_opt[shydr].sum() > 1: (network.storage_units_t.p[shydr].resample(mean).mean().sum(axis=1) /\ network.storage_units.p_nom_opt[shydr].sum()).plot( ax=ax, label="Hydrogen dispatch", color='teal') # instantiate a second axes that shares the same x-axis ax2 = ax.twinx() ((network.storage_units_t.state_of_charge[shydr].resample(mean).\ mean().sum(axis=1) / cap_hydr)*100).plot( ax=ax2, label="Hydrogen state of charge", color='green') else: (network.storage_units_t.p[sbatt].resample(mean).mean().sum(axis=1) / \ network.storage_units.p_nom_opt[sbatt].sum()).plot( ax=ax, label="Battery dispatch", color='orangered') (network.storage_units_t.p[shydr].resample(mean).mean().sum(axis=1) /\ network.storage_units.p_nom_opt[shydr].sum()).plot( ax=ax, label="Hydrogen dispatch", color='teal') # instantiate a second axes that shares the same x-axis ax2 = ax.twinx() ((network.storage_units_t.state_of_charge[shydr].resample(mean).\ mean().sum(axis=1) / cap_hydr)*100).plot( ax=ax2, label="Hydrogen state of charge", color='green') ((network.storage_units_t.state_of_charge[sbatt].resample(mean).\ mean().sum(axis=1) / cap_batt)*100).plot( ax=ax2, label="Battery state of charge", color='blue') ax.set_xlabel("") ax.set_ylabel("Storage dispatch in p.u. \n <- charge - discharge ->") ax2.set_ylabel("Storage state of charge in % ") ax2.set_ylim([0, 100]) ax.set_ylim([-1,1]) ax.legend(loc=2) ax2.legend(loc=1) ax.set_title("Storage dispatch and state of charge") if filename is None: plt.show() else: plt.savefig(filename) plt.close() return
Plots the dispatch and state of charge (SOC) of extendable storages. Parameters ---------- network : PyPSA network container Holds topology of grid including results from powerflow analysis mean : str Defines over how many snapshots the p and soc values will averaged. filename : path to folder
entailment
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 """ 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) & (network.storage_units.capital_cost>10) & (network.storage_units.max_hours==168)] cap_batt = (network.storage_units.max_hours[sbatt] * network.storage_units.p_nom_opt[sbatt]).sum() cap_hydr = (network.storage_units.max_hours[shydr] * network.storage_units.p_nom_opt[shydr]).sum() fig, ax = plt.subplots(1, 1) if network.storage_units.p_nom_opt[sbatt].sum() < 1 and \ network.storage_units.p_nom_opt[shydr].sum() < 1: print("No storage unit to plot") elif network.storage_units.p_nom_opt[sbatt].sum() > 1 and \ network.storage_units.p_nom_opt[shydr].sum() < 1: (network.storage_units_t.p[sbatt].sum(axis=1).sort_values( ascending=False).reset_index() / \ network.storage_units.p_nom_opt[sbatt].sum())[0].plot( ax=ax, label="Battery storage", color='orangered') elif network.storage_units.p_nom_opt[sbatt].sum() < 1 and \ network.storage_units.p_nom_opt[shydr].sum() > 1: (network.storage_units_t.p[shydr].sum(axis=1).sort_values( ascending=False).reset_index() / \ network.storage_units.p_nom_opt[shydr].sum())[0].plot( ax=ax, label="Hydrogen storage", color='teal') else: (network.storage_units_t.p[sbatt].sum(axis=1).sort_values( ascending=False).reset_index() / \ network.storage_units.p_nom_opt[sbatt].sum())[0].plot( ax=ax, label="Battery storage", color='orangered') (network.storage_units_t.p[shydr].sum(axis=1).sort_values( ascending=False).reset_index() / \ network.storage_units.p_nom_opt[shydr].sum())[0].plot( ax=ax, label="Hydrogen storage", color='teal') ax.set_xlabel("") ax.set_ylabel("Storage dispatch in p.u. \n <- charge - discharge ->") ax.set_ylim([-1.05,1.05]) ax.legend() ax.set_title("Sorted duration curve of storage dispatch") if filename is None: plt.show() else: plt.savefig(filename,figsize=(3,4),bbox_inches='tight') plt.close() return
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
entailment
def register(self): """ Change the state machine that is observed for new selected states to the selected state machine. :return: """ # 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 self.relieve_model(self._selected_sm_model.history) if self.model.selected_state_machine_id is not None and global_gui_config.get_config_value('HISTORY_ENABLED'): # set own selected state machine id self.__my_selected_sm_id = self.model.selected_state_machine_id # observe new models self._selected_sm_model = self.model.state_machines[self.__my_selected_sm_id] if self._selected_sm_model.history: self.observe_model(self._selected_sm_model.history) self.update(None, None, None) else: logger.warning("The history is enabled but not generated {0}. {1}" "".format(self._selected_sm_model.state_machine.state_machine_id, self._selected_sm_model.state_machine.file_system_path)) else: if self.__my_selected_sm_id is not None: self.doing_update = True self.history_tree_store.clear() self.doing_update = False self.__my_selected_sm_id = None self._selected_sm_model = None
Change the state machine that is observed for new selected states to the selected state machine. :return:
entailment
def register_actions(self, shortcut_manager): """Register callback methods for triggered actions :param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: """ shortcut_manager.add_callback_for_action("undo", self.undo) shortcut_manager.add_callback_for_action("redo", self.redo)
Register callback methods for triggered actions :param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager:
entailment
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 """ # 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 \ react_to_event(self.view, tab['controller'].get_controller('source_ctrl').view.textview, (key_value, modifier_mask)) or \ tab['controller'].get_controller('description_ctrl') is not None and \ react_to_event(self.view, tab['controller'].get_controller('description_ctrl').view.textview, (key_value, modifier_mask)): return False if self._selected_sm_model is not None: self._selected_sm_model.history.undo() return True else: logger.debug("Undo is not possible now as long as no state_machine is selected.")
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
entailment
def update(self, model, prop_name, info): """ The method updates the history (a Gtk.TreeStore) which is the model of respective TreeView. It functionality is strongly depends on a consistent history-tree hold by a ChangeHistory-Class. """ # logger.debug("History changed %s\n%s\n%s" % (model, prop_name, info)) if self.parent is not None and hasattr(self.parent, "focus_notebook_page_of_controller"): # request focus -> which has not have to be satisfied self.parent.focus_notebook_page_of_controller(self) if self._selected_sm_model is None or self._selected_sm_model.history.fake or \ info is not None and info.method_name not in ["insert_action", "undo", "redo", "reset"]: return self.doing_update = True self.history_tree_store.clear() self.list_tree_iter = {} trail_actions = [action.version_id for action in self._selected_sm_model.history.modifications.single_trail_history()] def insert_this_action(action, parent_tree_item, init_branch=False): """ The function insert a action with respective arguments (e.g. method_name, instance) into a TreeStore. - final trail or tree specific gtk-tree-levels -> 'trail' has no levels as well as 'branch' without tree - defines which element is marked as active - generate branch labels with version-id """ model = action.before_overview['model'][-1] method_name = action.before_overview['method_name'][-1] instance = action.before_overview['instance'][-1] parameters = [] tool_tip = None if action.before_overview['type'] == 'signal': if isinstance(action.before_overview['signal'][0], MetaSignalMsg): # logger.info(action.before_overview._overview_dict) parameters.append(str(action.meta)) elif isinstance(action.before_overview['signal'][-1], ActionSignalMsg): if action.action_type not in ['paste', 'cut']: parameters.append(str(action.before_overview['signal'][-1].kwargs)) else: logger.warning("no parameters defined for signal: {0}".format(action.before_overview['signal'])) # for index, signal in enumerate(action.before_overview['signal']): # print("\n", index, signal) else: for index, value in enumerate(action.before_overview['args'][-1]): if not index == 0: parameters.append(str(value)) for name, value in action.before_overview['kwargs'][-1].items(): parameters.append("{0}: {1}".format(name, value)) if hasattr(action, 'action_type') and action.action_type == "script_text" and hasattr(action, 'script_diff'): line = "" for elem in action.script_diff.split('\n'): line = elem if not line.replace(' ', '') == '' and (line.startswith('+') or line.startswith('-')): break tool_tip = action.script_diff parameters = [line] # + "\n -> [hover for source script diff in tooltip.]"] if hasattr(action, 'action_type') and action.action_type == "description" and hasattr(action, 'description_diff'): line = "" for elem in action.description_diff.split('\n'): line = elem if not line.replace(' ', '') == '' and (line.startswith('+') or line.startswith('-')): break tool_tip = action.description_diff parameters = [line] # + "\n -> [hover for source script diff in tooltip.]"] # find active actions in to be marked in view if self._mode == 'trail': active = len(self.history_tree_store) <= self._selected_sm_model.history.modifications.trail_pointer else: all_active = self._selected_sm_model.history.modifications.get_all_active_actions() active = action.version_id in all_active # generate label to mark branches version_label = action.version_id if init_branch: version_label = 'b.' + str(action.version_id) tool_tip = "The element '{0}' starts a new branch of actions.".format(version_label) tree_row_iter = self.new_change(model, str(method_name).replace('_', ' '), instance, info, version_label, active, parent_tree_item, ', '.join(parameters), tool_tip) self.list_tree_iter[action.version_id] = (tree_row_iter, parent_tree_item) return tree_row_iter def insert_all_next_actions(version_id, parent_tree_item=None): """ The function defines linkage of history-tree-elements in a gtk-tree-view to create a optimal overview. """ if len(self._selected_sm_model.history.modifications.all_time_history) == 1: return next_id = version_id while next_id is not None: # print(next_id, len(self._selected_sm_model.history.modifications.all_time_history)) version_id = next_id history_tree_elem = self._selected_sm_model.history.modifications.all_time_history[next_id] next_id = history_tree_elem.next_id prev_tree_elem = None if history_tree_elem.prev_id is not None: prev_tree_elem = self._selected_sm_model.history.modifications.all_time_history[history_tree_elem.prev_id] action = history_tree_elem.action # logger.info("prev branch #{0} <-> {1}, trail_actions are {2}".format(history_tree_elem.action.version_id, prev_tree_elem, trail_actions)) in_trail = history_tree_elem.action.version_id in trail_actions if in_trail: # in trail parent is always None if prev_tree_elem is not None and prev_tree_elem.old_next_ids: child_tree_item = insert_this_action(action, None, init_branch=True) else: child_tree_item = insert_this_action(action, None) elif prev_tree_elem is not None and prev_tree_elem.old_next_ids: # branch and not trail -> level + 1 ... child of prev_id -> parent_iter is prev_id_iter prev_id_iter = self.list_tree_iter[prev_tree_elem.action.version_id][0] child_tree_item = insert_this_action(action, prev_id_iter, init_branch=True) elif prev_tree_elem is not None and not prev_tree_elem.old_next_ids: # no branch and not trail prev_prev_tree_elem = self._selected_sm_model.history.modifications.all_time_history[prev_tree_elem.prev_id] branch_limit_for_extra_ident_level = 1 if prev_tree_elem.prev_id in trail_actions else 0 if len(prev_prev_tree_elem.old_next_ids) > branch_limit_for_extra_ident_level: # -> level + 1 as previous element, because to many branches -> so prev_id iter as parent_iter iter_of_prev_id = self.list_tree_iter[prev_tree_elem.action.version_id][0] child_tree_item = insert_this_action(action, iter_of_prev_id) else: # -> same level as previous element -> so same parent_iter as prev_id parent_iter_of_prev_id = self.list_tree_iter[prev_tree_elem.action.version_id][1] child_tree_item = insert_this_action(action, parent_iter_of_prev_id) else: logger.warning("relative level could not be found -> this should not happen") child_tree_item = insert_this_action(action, parent_tree_item) if history_tree_elem.old_next_ids and self._mode == 'branch': old_next_ids = history_tree_elem.old_next_ids for old_next_id in old_next_ids: insert_all_next_actions(old_next_id, child_tree_item) insert_all_next_actions(version_id=0) # set selection of Tree if self._selected_sm_model.history.modifications.trail_pointer is not None and len(self.history_tree_store) > 1: searched_row_version_id = self._selected_sm_model.history.modifications.single_trail_history()[self._selected_sm_model.history.modifications.trail_pointer].version_id row_number = 0 for action_entry in self.history_tree_store: # compare action.version_id if int(action_entry[1].split('.')[-1]) == searched_row_version_id: self.view['history_tree'].set_cursor(row_number) break row_number += 1 # set colors of Tree # - is state full and all element which are open to be re-done gray self.doing_update = False
The method updates the history (a Gtk.TreeStore) which is the model of respective TreeView. It functionality is strongly depends on a consistent history-tree hold by a ChangeHistory-Class.
entailment
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``. """ if self.has_error: exception_data = self._raw.get("exception", {}) return exception_data.get("message") return 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``.
entailment
async def load_tracks(self, query) -> LoadResult: """ Executes a loadtracks request. Only works on Lavalink V3. Parameters ---------- query : str Returns ------- LoadResult """ 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, "tracks": data } return LoadResult(modified_data)
Executes a loadtracks request. Only works on Lavalink V3. Parameters ---------- query : str Returns ------- LoadResult
entailment
async def get_tracks(self, query) -> Tuple[Track, ...]: """ Gets tracks from lavalink. Parameters ---------- query : str Returns ------- Tuple[Track, ...] """ 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
Gets tracks from lavalink. Parameters ---------- query : str Returns ------- Tuple[Track, ...]
entailment
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]) """ 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 = [os.path.join(rel_path, filename) for filename in os.listdir(rel_path)] return target_path, source_files
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])
entailment
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])) """ 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_root_dir): relative_directory = os.path.relpath(dir_, rel_root_dir) file_list = list() for fileName in files: rel_file_path = os.path.join(relative_directory, fileName) abs_file_path = os.path.join(rel_root_dir, rel_file_path) file_list.append(abs_file_path) if len(file_list) > 0: # this is a valid path in ~/.local folder: e.g. share/rafcon/libraries/generic/wait target_path = os.path.join(share_target_root, relative_directory) result_list.append((target_path, file_list)) return result_list
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]))
entailment
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])) """ 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 = [ get_data_files_tuple(assets_folder, 'splashscreens'), get_data_files_tuple(assets_folder, 'fonts', 'FontAwesome'), get_data_files_tuple(assets_folder, 'fonts', 'Source Sans Pro'), get_data_files_tuple(themes_folder, 'gtk-3.0', 'gtk.css', path_to_file=True), get_data_files_tuple(themes_folder, 'gtk-3.0', 'gtk-dark.css', path_to_file=True), get_data_files_tuple(themes_folder, 'assets'), get_data_files_tuple(themes_folder, 'sass'), get_data_files_tuple(themes_folder, 'gtk-sourceview'), get_data_files_tuple(themes_folder, 'colors.json', path_to_file=True), get_data_files_tuple(themes_folder, 'colors-dark.json', path_to_file=True) ] # print("gui_data_files", gui_data_files) icon_data_files = get_data_files_recursively(path.join(share_folder, 'icons'), share_target_root="icons") # print("icon_data_files", icon_data_files) locale_data_files = create_mo_files() # example tuple # locale_data_files = [('share/rafcon/locale/de/LC_MESSAGES', ['source/rafcon/locale/de/LC_MESSAGES/rafcon.mo'])] # print("locale_data_files", locale_data_files) version_data_file = [("./", ["VERSION"])] desktop_data_file = [("share/applications", [path.join('share', 'applications', 'de.dlr.rm.RAFCON.desktop')])] examples_data_files = get_data_files_recursively(examples_folder, share_target_root=path.join("rafcon", "examples")) libraries_data_files = get_data_files_recursively(libraries_folder, share_target_root=path.join("rafcon", "libraries")) generated_data_files = gui_data_files + icon_data_files + locale_data_files + version_data_file + \ desktop_data_file + examples_data_files + libraries_data_files # for elem in generated_data_files: # print(elem) return generated_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]))
entailment
def extendable(network, args, line_max): """ Function that sets selected components extendable 'network' for all lines, links and transformers 'german_network' for all lines, links and transformers located in Germany 'foreign_network' for all foreign lines, links and transformers 'transformers' for all transformers 'storages' for extendable storages 'overlay_network' for lines, links and trafos in extension scenerio(s) Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA args : dict Arguments set in appl.py Returns ------- network : :class:`pypsa.Network Overall container of PyPSA """ if 'network' in args['extendable']: network.lines.s_nom_extendable = True network.lines.s_nom_min = network.lines.s_nom if not line_max==None: network.lines.s_nom_max = line_max * network.lines.s_nom else: network.lines.s_nom_max = float("inf") if not network.transformers.empty: network.transformers.s_nom_extendable = True network.transformers.s_nom_min = network.transformers.s_nom if not line_max==None: network.transformers.s_nom_max =\ line_max * network.transformers.s_nom else: network.transformers.s_nom_max = float("inf") if not network.links.empty: network.links.p_nom_extendable = True network.links.p_nom_min = network.links.p_nom network.links.p_nom_max = float("inf") if not line_max==None: network.links.p_nom_max=\ line_max * network.links.p_nom else: network.links.p_nom_max = float("inf") network = set_line_costs(network, args) network = set_trafo_costs(network, args) if 'german_network' in args['extendable']: buses = network.buses[~network.buses.index.isin( buses_by_country(network).index)] network.lines.loc[(network.lines.bus0.isin(buses.index)) & (network.lines.bus1.isin(buses.index)), 's_nom_extendable'] = True network.lines.loc[(network.lines.bus0.isin(buses.index)) & (network.lines.bus1.isin(buses.index)), 's_nom_min'] = network.lines.s_nom network.lines.loc[(network.lines.bus0.isin(buses.index)) & (network.lines.bus1.isin(buses.index)), 's_nom_max'] = float("inf") if not line_max==None: network.lines.loc[(network.lines.bus0.isin(buses.index)) & (network.lines.bus1.isin(buses.index)), 's_nom_max'] = line_max * network.lines.s_nom else: network.lines.loc[(network.lines.bus0.isin(buses.index)) & (network.lines.bus1.isin(buses.index)), 's_nom_max'] = float("inf") if not network.transformers.empty: network.transformers.loc[network.transformers.bus0.isin( buses.index),'s_nom_extendable'] = True network.transformers.loc[network.transformers.bus0.isin( buses.index),'s_nom_min'] = network.transformers.s_nom if not line_max==None: network.transformers.loc[network.transformers.bus0.isin( buses.index),'s_nom_max'] = \ line_max * network.transformers.s_nom else: network.transformers.loc[network.transformers.bus0.isin( buses.index),'s_nom_max'] = float("inf") if not network.links.empty: network.links.loc[(network.links.bus0.isin(buses.index)) & (network.links.bus1.isin(buses.index)), 'p_nom_extendable'] = True network.links.loc[(network.links.bus0.isin(buses.index)) & (network.links.bus1.isin(buses.index)), 'p_nom_min'] = network.links.p_nom if not line_max==None: network.links.loc[(network.links.bus0.isin(buses.index)) & (network.links.bus1.isin(buses.index)), 'p_nom_max'] = line_max * network.links.p_nom else: network.links.loc[(network.links.bus0.isin(buses.index)) & (network.links.bus1.isin(buses.index)), 'p_nom_max'] = float("inf") network = set_line_costs(network, args) network = set_trafo_costs(network, args) if 'foreign_network' in args['extendable']: buses = network.buses[network.buses.index.isin( buses_by_country(network).index)] network.lines.loc[network.lines.bus0.isin(buses.index) | network.lines.bus1.isin(buses.index) , 's_nom_extendable'] = True network.lines.loc[network.lines.bus0.isin(buses.index) | network.lines.bus1.isin(buses.index), 's_nom_min'] = network.lines.s_nom if not line_max==None: network.lines.loc[network.lines.bus0.isin(buses.index) | network.lines.bus1.isin(buses.index), 's_nom_max'] = line_max * network.lines.s_nom else: network.lines.loc[network.lines.bus0.isin(buses.index) | network.lines.bus1.isin(buses.index), 's_nom_max'] = float("inf") if not network.transformers.empty: network.transformers.loc[network.transformers.bus0.isin( buses.index) | network.transformers.bus1.isin( buses.index) ,'s_nom_extendable'] = True network.transformers.loc[network.transformers.bus0.isin( buses.index) | network.transformers.bus1.isin( buses.index) ,'s_nom_min'] = network.transformers.s_nom if not line_max==None: network.transformers.loc[network.transformers.bus0.isin( buses.index) | network.transformers.bus1.isin( buses.index),'s_nom_max'] = \ line_max * network.transformers.s_nom else: network.transformers.loc[network.transformers.bus0.isin( buses.index) | network.transformers.bus1.isin( buses.index),'s_nom_max'] = float("inf") if not network.links.empty: network.links.loc[(network.links.bus0.isin(buses.index)) | (network.links.bus1.isin(buses.index)), 'p_nom_extendable'] = True network.links.loc[(network.links.bus0.isin(buses.index)) | (network.links.bus1.isin(buses.index)), 'p_nom_min'] = network.links.p_nom if not line_max==None: network.links.loc[(network.links.bus0.isin(buses.index)) | (network.links.bus1.isin(buses.index)), 'p_nom_max'] = line_max * network.links.p_nom else: network.links.loc[(network.links.bus0.isin(buses.index)) | (network.links.bus1.isin(buses.index)), 'p_nom_max'] = float("inf") network = set_line_costs(network, args) network = set_trafo_costs(network, args) if 'transformers' in args['extendable']: network.transformers.s_nom_extendable = True network.transformers.s_nom_min = network.transformers.s_nom network.transformers.s_nom_max = float("inf") network = set_trafo_costs(network) if 'storages' in args['extendable'] or 'storage' in args['extendable']: if network.storage_units.\ carrier[network. storage_units.carrier == 'extendable_storage'].any() == 'extendable_storage': network.storage_units.loc[network.storage_units.carrier == 'extendable_storage', 'p_nom_extendable'] = True if 'generators' in args['extendable']: network.generators.p_nom_extendable = True network.generators.p_nom_min = network.generators.p_nom network.generators.p_nom_max = float("inf") if 'foreign_storage' in args['extendable']: network.storage_units.p_nom_extendable[(network.storage_units.bus.isin( network.buses.index[network.buses.country_code != 'DE'])) & ( network.storage_units.carrier.isin( ['battery_storage','hydrogen_storage'] ))] = True network.storage_units.loc[ network.storage_units.p_nom_max.isnull(),'p_nom_max'] = \ network.storage_units.p_nom network.storage_units.loc[ (network.storage_units.carrier == 'battery_storage'), 'capital_cost'] = network.storage_units.loc[( network.storage_units.carrier == 'extendable_storage') & (network.storage_units.max_hours == 6),'capital_cost'].max() network.storage_units.loc[ (network.storage_units.carrier == 'hydrogen_storage'), 'capital_cost'] = network.storage_units.loc[( network.storage_units.carrier == 'extendable_storage') & (network.storage_units.max_hours == 168),'capital_cost'].max() network.storage_units.loc[ (network.storage_units.carrier == 'battery_storage'), 'marginal_cost'] = network.storage_units.loc[( network.storage_units.carrier == 'extendable_storage') & (network.storage_units.max_hours == 6),'marginal_cost'].max() network.storage_units.loc[ (network.storage_units.carrier == 'hydrogen_storage'), 'marginal_cost'] = network.storage_units.loc[( network.storage_units.carrier == 'extendable_storage') & (network.storage_units.max_hours == 168),'marginal_cost'].max() # Extension settings for extension-NEP 2035 scenarios if 'NEP Zubaunetz' in args['extendable']: for i in range(len(args['scn_extension'])): network.lines.loc[(network.lines.project != 'EnLAG') & ( network.lines.scn_name == 'extension_' + args['scn_extension'][i]), 's_nom_extendable'] = True network.transformers.loc[( network.transformers.project != 'EnLAG') & ( network.transformers.scn_name == ( 'extension_'+ args['scn_extension'][i])), 's_nom_extendable'] = True network.links.loc[network.links.scn_name == ( 'extension_' + args['scn_extension'][i] ), 'p_nom_extendable'] = True if 'overlay_network' in args['extendable']: for i in range(len(args['scn_extension'])): network.lines.loc[network.lines.scn_name == ( 'extension_' + args['scn_extension'][i] ), 's_nom_extendable'] = True network.lines.loc[network.lines.scn_name == ( 'extension_' + args['scn_extension'][i] ), 's_nom_max'] = network.lines.s_nom[network.lines.scn_name == ( 'extension_' + args['scn_extension'][i])] network.links.loc[network.links.scn_name == ( 'extension_' + args['scn_extension'][i] ), 'p_nom_extendable'] = True network.transformers.loc[network.transformers.scn_name == ( 'extension_' + args['scn_extension'][i] ), 's_nom_extendable'] = True network.lines.loc[network.lines.scn_name == ( 'extension_' + args['scn_extension'][i] ), 'capital_cost'] = network.lines.capital_cost/\ args['branch_capacity_factor']['eHV'] if 'overlay_lines' in args['extendable']: for i in range(len(args['scn_extension'])): network.lines.loc[network.lines.scn_name == ( 'extension_' + args['scn_extension'][i] ), 's_nom_extendable'] = True network.links.loc[network.links.scn_name == ( 'extension_' + args['scn_extension'][i] ), 'p_nom_extendable'] = True network.lines.loc[network.lines.scn_name == ( 'extension_' + args['scn_extension'][i]), 'capital_cost'] = network.lines.capital_cost + (2 * 14166) network.lines.s_nom_min[network.lines.s_nom_extendable == False] =\ network.lines.s_nom network.transformers.s_nom_min[network.transformers.s_nom_extendable == \ False] = network.transformers.s_nom network.lines.s_nom_max[network.lines.s_nom_extendable == False] =\ network.lines.s_nom network.transformers.s_nom_max[network.transformers.s_nom_extendable == \ False] = network.transformers.s_nom return network
Function that sets selected components extendable 'network' for all lines, links and transformers 'german_network' for all lines, links and transformers located in Germany 'foreign_network' for all foreign lines, links and transformers 'transformers' for all transformers 'storages' for extendable storages 'overlay_network' for lines, links and trafos in extension scenerio(s) Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA args : dict Arguments set in appl.py Returns ------- network : :class:`pypsa.Network Overall container of PyPSA
entailment
def extension_preselection(network, args, method, days = 3): """ Function that preselects lines which are extendend in snapshots leading to overloading to reduce nubmer of extension variables. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA args : dict Arguments set in appl.py method: str Choose method of selection: 'extreme_situations' for remarkable timsteps (e.g. minimal resiudual load) 'snapshot_clustering' for snapshot clustering with number of days days: int Number of clustered days, only used when method = 'snapshot_clustering' Returns ------- network : :class:`pypsa.Network Overall container of PyPSA """ weighting = network.snapshot_weightings if method == 'extreme_situations': snapshots = find_snapshots(network, 'residual load') snapshots = snapshots.append(find_snapshots(network, 'wind_onshore')) snapshots = snapshots.append(find_snapshots(network, 'solar')) snapshots = snapshots.drop_duplicates() snapshots = snapshots.sort_values() if method == 'snapshot_clustering': network_cluster = snapshot_clustering(network, how='daily', clusters=days) snapshots = network_cluster.snapshots network.snapshot_weightings = network_cluster.snapshot_weightings # Set all lines and trafos extendable in network network.lines.loc[:, 's_nom_extendable'] = True network.lines.loc[:, 's_nom_min'] = network.lines.s_nom network.lines.loc[:, 's_nom_max'] = np.inf network.links.loc[:, 'p_nom_extendable'] = True network.links.loc[:, 'p_nom_min'] = network.links.p_nom network.links.loc[:, 'p_nom_max'] = np.inf network.transformers.loc[:, 's_nom_extendable'] = True network.transformers.loc[:, 's_nom_min'] = network.transformers.s_nom network.transformers.loc[:, 's_nom_max'] = np.inf network = set_line_costs(network) network = set_trafo_costs(network) network = convert_capital_costs(network, 1, 1) extended_lines = network.lines.index[network.lines.s_nom_opt > network.lines.s_nom] extended_links = network.links.index[network.links.p_nom_opt > network.links.p_nom] x = time.time() for i in range(int(snapshots.value_counts().sum())): if i > 0: network.lopf(snapshots[i], solver_name=args['solver']) extended_lines = extended_lines.append( network.lines.index[network.lines.s_nom_opt > network.lines.s_nom]) extended_lines = extended_lines.drop_duplicates() extended_links = extended_links.append( network.links.index[network.links.p_nom_opt > network.links.p_nom]) extended_links = extended_links.drop_duplicates() print("Number of preselected lines: ", len(extended_lines)) network.lines.loc[~network.lines.index.isin(extended_lines), 's_nom_extendable'] = False network.lines.loc[network.lines.s_nom_extendable, 's_nom_min']\ = network.lines.s_nom network.lines.loc[network.lines.s_nom_extendable, 's_nom_max']\ = np.inf network.links.loc[~network.links.index.isin(extended_links), 'p_nom_extendable'] = False network.links.loc[network.links.p_nom_extendable, 'p_nom_min']\ = network.links.p_nom network.links.loc[network.links.p_nom_extendable, 'p_nom_max']\ = np.inf network.snapshot_weightings = weighting network = set_line_costs(network) network = set_trafo_costs(network) network = convert_capital_costs(network, args['start_snapshot'], args['end_snapshot']) y = time.time() z1st = (y - x) / 60 print("Time for first LOPF [min]:", round(z1st, 2)) return network
Function that preselects lines which are extendend in snapshots leading to overloading to reduce nubmer of extension variables. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA args : dict Arguments set in appl.py method: str Choose method of selection: 'extreme_situations' for remarkable timsteps (e.g. minimal resiudual load) 'snapshot_clustering' for snapshot clustering with number of days days: int Number of clustered days, only used when method = 'snapshot_clustering' Returns ------- network : :class:`pypsa.Network Overall container of PyPSA
entailment