sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1 value |
|---|---|---|
def cal_dist_between_2_coord_frame_aligned_boxes(box1_pos, box1_size, box2_pos, box2_size):
""" Calculate Euclidean distance between two boxes those edges are parallel to the coordinate axis
The function decides condition based which corner to corner or edge to edge distance needs to be calculated.
:param tuple box1_pos: x and y position of box 1
:param tuple box1_size: x and y size of box 1
:param tuple box2_pos: x and y position of box 2
:param tuple box2_size: x and y size of box 2
:return:
"""
box1_x_min, box1_y_min = box1_pos
box1_x_max, box1_y_max = (box1_pos[0] + box1_size[0], box1_pos[1] + box1_size[1])
box2_x_min, box2_y_min = box2_pos
box2_x_max, box2_y_max = (box2_pos[0] + box2_size[0], box2_pos[1] + box2_size[1])
# 1|2|3 +-> x => works also for opengl - both boxes described in same coordinates
# 4|5|6 -> 5 is covered by box1 |
# 7|8|9 \/ y
# - case 1 the right lower corner of box2 is above and left to box1 upper left corner
# - case 5 is when the boxes are overlapping so the distance is 0
# - in case 1, 3, 7, 9 respective corners of box1 to box2 are the minimal distance
# - 2, 4, 6, 8 can be covered by either simply calculation via either x or y axis
if box2_x_max < box1_x_min and box2_y_max < box1_y_min: # case 1 -> box2 is fully in sector 1
distance = sqrt((box1_x_min - box2_x_max)**2 + (box1_y_min - box2_y_max)**2)
elif box2_x_min > box1_x_max and box2_y_max < box1_y_min: # case 3 -> box2 is fully in sector 3
distance = sqrt((box2_x_min - box1_x_max)**2 + (box1_y_min - box2_y_max)**2)
elif box2_x_max < box1_x_min and box2_y_min > box1_y_max: # case 7 -> box2 is fully in sector 7
distance = sqrt((box1_x_min - box2_x_max)**2 + (box2_y_min - box1_y_max)**2)
elif box2_x_min > box1_x_max and box2_y_min > box1_y_max: # case 9 -> box2 is fully in sector 9
distance = sqrt((box2_x_min - box1_x_max)**2 + (box2_y_min - box1_y_max)**2)
elif box2_y_max < box1_y_min: # case 2 -> box2 is party in sector 2 and in 1 or 3
distance = box1_y_min - box2_y_max
elif box2_x_max < box1_x_min: # case 4 -> box2 is party in sector 4 and in 1 or 7
distance = box1_x_min - box2_x_max
elif box2_x_min > box1_x_max: # case 6 -> box2 is party in sector 6 and in 3 or 9
distance = box2_x_min - box1_x_max
elif box2_y_min > box1_y_max: # case 8 -> box2 is party in sector 8 and in 7 or 9
distance = box2_y_min - box1_y_max
else: # case 5 box2 reach into area of box1
distance = 0.
return distance | Calculate Euclidean distance between two boxes those edges are parallel to the coordinate axis
The function decides condition based which corner to corner or edge to edge distance needs to be calculated.
:param tuple box1_pos: x and y position of box 1
:param tuple box1_size: x and y size of box 1
:param tuple box2_pos: x and y position of box 2
:param tuple box2_size: x and y size of box 2
:return: | entailment |
def mouse_click(self, widget, event=None):
"""Triggered when mouse click is pressed in the history tree. The method shows all scoped data for an execution
step as tooltip or fold and unfold the tree by double-click and select respective state for double clicked
element.
"""
if event.type == Gdk.EventType._2BUTTON_PRESS and event.get_button()[1] == 1:
(model, row) = self.history_tree.get_selection().get_selected()
if row is not None:
histroy_item_path = self.history_tree_store.get_path(row)
histroy_item_iter = self.history_tree_store.get_iter(histroy_item_path)
# logger.info(history_item.state_reference)
# TODO generalize double-click folding and unfolding -> also used in states tree of state machine
if histroy_item_path is not None and self.history_tree_store.iter_n_children(histroy_item_iter):
if self.history_tree.row_expanded(histroy_item_path):
self.history_tree.collapse_row(histroy_item_path)
else:
self.history_tree.expand_to_path(histroy_item_path)
sm = self.get_history_item_for_tree_iter(histroy_item_iter).state_reference.get_state_machine()
if sm:
if sm.state_machine_id != self.model.selected_state_machine_id:
self.model.selected_state_machine_id = sm.state_machine_id
else:
logger.info("No state machine could be found for selected item's state reference and "
"therefore no selection is performed.")
return
active_sm_m = self.model.get_selected_state_machine_model()
assert active_sm_m.state_machine is sm
state_path = self.get_history_item_for_tree_iter(histroy_item_iter).state_reference.get_path()
ref_state_m = active_sm_m.get_state_model_by_path(state_path)
if ref_state_m and active_sm_m:
active_sm_m.selection.set(ref_state_m)
return True
if event.type == Gdk.EventType.BUTTON_PRESS and event.get_button()[1] == 2:
x = int(event.x)
y = int(event.y)
pthinfo = self.history_tree.get_path_at_pos(x, y)
if pthinfo is not None:
path, col, cellx, celly = pthinfo
self.history_tree.grab_focus()
self.history_tree.set_cursor(path, col, 0)
self.open_selected_history_separately(None)
if event.type == Gdk.EventType.BUTTON_PRESS and event.get_button()[1] == 3:
x = int(event.x)
y = int(event.y)
time = event.time
pthinfo = self.history_tree.get_path_at_pos(x, y)
if pthinfo is not None:
path, col, cellx, celly = pthinfo
self.history_tree.grab_focus()
self.history_tree.set_cursor(path, col, 0)
popup_menu = Gtk.Menu()
model, row = self.history_tree.get_selection().get_selected()
history_item = model[row][self.HISTORY_ITEM_STORAGE_ID]
if not isinstance(history_item, ScopedDataItem) or history_item.scoped_data is None:
return
scoped_data = history_item.scoped_data
input_output_data = history_item.child_state_input_output_data
state_reference = history_item.state_reference
self.append_string_to_menu(popup_menu, "------------------------")
self.append_string_to_menu(popup_menu, "Scoped Data: ")
self.append_string_to_menu(popup_menu, "------------------------")
for key, data in scoped_data.items():
menu_item_string = " %s (%s - %s):\t%s" % (
data.name.replace("_", "__"), key, data.value_type, data.value)
self.append_string_to_menu(popup_menu, menu_item_string)
if input_output_data:
if isinstance(history_item, CallItem):
self.append_string_to_menu(popup_menu, "------------------------")
self.append_string_to_menu(popup_menu, "Input Data:")
self.append_string_to_menu(popup_menu, "------------------------")
else:
self.append_string_to_menu(popup_menu, "------------------------")
self.append_string_to_menu(popup_menu, "Output Data:")
self.append_string_to_menu(popup_menu, "------------------------")
for key, data in input_output_data.items():
menu_item_string = " %s :\t%s" % (key.replace("_", "__"), data)
self.append_string_to_menu(popup_menu, menu_item_string)
if state_reference:
if history_item.outcome:
self.append_string_to_menu(popup_menu, "------------------------")
final_outcome_menu_item_string = "Final outcome: " + str(history_item.outcome)
self.append_string_to_menu(popup_menu, final_outcome_menu_item_string)
self.append_string_to_menu(popup_menu, "------------------------")
popup_menu.show()
popup_menu.popup(None, None, None, None, event.get_button()[1], time)
return True | Triggered when mouse click is pressed in the history tree. The method shows all scoped data for an execution
step as tooltip or fold and unfold the tree by double-click and select respective state for double clicked
element. | entailment |
def get_history_item_for_tree_iter(self, child_tree_iter):
"""Hands history item for tree iter and compensate if tree item is a dummy item
:param Gtk.TreeIter child_tree_iter: Tree iter of row
:rtype rafcon.core.execution.execution_history.HistoryItem:
:return history tree item:
"""
history_item = self.history_tree_store[child_tree_iter][self.HISTORY_ITEM_STORAGE_ID]
if history_item is None: # is dummy item
if self.history_tree_store.iter_n_children(child_tree_iter) > 0:
child_iter = self.history_tree_store.iter_nth_child(child_tree_iter, 0)
history_item = self.history_tree_store[child_iter][self.HISTORY_ITEM_STORAGE_ID]
else:
logger.debug("In a dummy history should be respective real call element.")
return history_item | Hands history item for tree iter and compensate if tree item is a dummy item
:param Gtk.TreeIter child_tree_iter: Tree iter of row
:rtype rafcon.core.execution.execution_history.HistoryItem:
:return history tree item: | entailment |
def _store_expansion_state(self):
"""Iter recursively all tree items and store expansion state"""
def store_tree_expansion(child_tree_iter, expansion_state):
tree_item_path = self.history_tree_store.get_path(child_tree_iter)
history_item = self.get_history_item_for_tree_iter(child_tree_iter)
# store expansion state if tree item path is valid and expansion state was not stored already
if tree_item_path is not None:
# if first element of sub-tree has same history_item as the parent ignore it's expansion state
if history_item not in expansion_state:
expansion_state[history_item] = self.history_tree.row_expanded(tree_item_path)
for n in range(self.history_tree_store.iter_n_children(child_tree_iter)):
child_iter = self.history_tree_store.iter_nth_child(child_tree_iter, n)
store_tree_expansion(child_iter, expansion_state)
root_iter = self.history_tree_store.get_iter_first()
if not root_iter:
return
current_expansion_state = {}
# this can be the case when the execution history tree is currently being deleted
if not self.get_history_item_for_tree_iter(root_iter).state_reference:
return
state_machine = self.get_history_item_for_tree_iter(root_iter).state_reference.get_state_machine()
self._expansion_state[state_machine.state_machine_id] = current_expansion_state
while root_iter:
store_tree_expansion(root_iter, current_expansion_state)
root_iter = self.history_tree_store.iter_next(root_iter) | Iter recursively all tree items and store expansion state | entailment |
def _restore_expansion_state(self):
"""Iter recursively all tree items and restore expansion state"""
def restore_tree_expansion(child_tree_iter, expansion_state):
tree_item_path = self.history_tree_store.get_path(child_tree_iter)
history_item = self.get_history_item_for_tree_iter(child_tree_iter)
# restore expansion state if tree item path is valid and expansion state was not stored already
if tree_item_path and history_item in expansion_state:
if expansion_state[history_item]:
self.history_tree.expand_to_path(tree_item_path)
for n in range(self.history_tree_store.iter_n_children(child_tree_iter)):
child_iter = self.history_tree_store.iter_nth_child(child_tree_iter, n)
restore_tree_expansion(child_iter, expansion_state)
root_iter = self.history_tree_store.get_iter_first()
if not root_iter:
return
state_machine = self.get_history_item_for_tree_iter(root_iter).state_reference.get_state_machine()
if state_machine.state_machine_id not in self._expansion_state:
return
while root_iter:
restore_tree_expansion(root_iter, self._expansion_state[state_machine.state_machine_id])
root_iter = self.history_tree_store.iter_next(root_iter) | Iter recursively all tree items and restore expansion state | entailment |
def notification_selected_sm_changed(self, model, prop_name, info):
"""If a new state machine is selected, make sure expansion state is stored and tree updated"""
selected_state_machine_id = self.model.selected_state_machine_id
if selected_state_machine_id is None:
return
self.update() | If a new state machine is selected, make sure expansion state is stored and tree updated | entailment |
def notification_sm_changed(self, model, prop_name, info):
"""Remove references to non-existing state machines"""
for state_machine_id in list(self._expansion_state.keys()):
if state_machine_id not in self.model.state_machines:
del self._expansion_state[state_machine_id] | Remove references to non-existing state machines | entailment |
def execution_history_focus(self, model, prop_name, info):
""" Arranges to put execution-history widget page to become top page in notebook when execution starts and stops
and resets the boolean of modification_history_was_focused to False each time this notification are observed.
"""
if state_machine_execution_engine.status.execution_mode in \
[StateMachineExecutionStatus.STARTED, StateMachineExecutionStatus.STOPPED,
StateMachineExecutionStatus.FINISHED]:
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 state_machine_execution_engine.status.execution_mode is not StateMachineExecutionStatus.STARTED:
if not self.model.selected_state_machine_id == self.model.state_machine_manager.active_state_machine_id:
pass
else:
self.update() | Arranges to put execution-history widget page to become top page in notebook when execution starts and stops
and resets the boolean of modification_history_was_focused to False each time this notification are observed. | entailment |
def clean_history(self, widget, event=None):
"""Triggered when the 'Clean History' button is clicked.
Empties the execution history tree by adjusting the start index and updates tree store and view.
"""
self.history_tree_store.clear()
selected_sm_m = self.model.get_selected_state_machine_model()
if selected_sm_m:
# the core may continue running without the GUI and for this it needs its execution histories
if state_machine_execution_engine.finished_or_stopped():
selected_sm_m.state_machine.destroy_execution_histories()
self.update() | Triggered when the 'Clean History' button is clicked.
Empties the execution history tree by adjusting the start index and updates tree store and view. | entailment |
def update(self):
"""
rebuild the tree view of the history item tree store
:return:
"""
# with self._update_lock:
self._update_lock.acquire()
self._store_expansion_state()
self.history_tree_store.clear()
selected_sm_m = self.model.get_selected_state_machine_model()
if not selected_sm_m:
return
for execution_number, execution_history in enumerate(selected_sm_m.state_machine.execution_histories):
if len(execution_history) > 0:
first_history_item = execution_history[0]
# the next lines filter out the StateMachineStartItem, which is not intended to
# be displayed, but merely as convenient entry point in the saved log file
if isinstance(first_history_item, StateMachineStartItem):
if len(execution_history) > 1:
first_history_item = execution_history[1]
tree_item = self.history_tree_store.insert_after(
None,
None,
(first_history_item.state_reference.name + " - Run " + str(execution_number + 1),
first_history_item, self.TOOL_TIP_TEXT))
self.insert_execution_history(tree_item, execution_history[1:], is_root=True)
else:
pass # there was only the Start item in the history
else:
tree_item = self.history_tree_store.insert_after(
None,
None,
(first_history_item.state_reference.name + " - Run " + str(execution_number + 1),
first_history_item, self.TOOL_TIP_TEXT))
self.insert_execution_history(tree_item, execution_history, is_root=True)
self._restore_expansion_state()
self._update_lock.release() | rebuild the tree view of the history item tree store
:return: | entailment |
def insert_history_item(self, parent, history_item, description, dummy=False):
"""Enters a single history item into the tree store
:param Gtk.TreeItem parent: Parent tree item
:param HistoryItem history_item: History item to be inserted
:param str description: A description to be added to the entry
:param None dummy: Whether this is just a dummy entry (wrapper for concurrency items)
:return: Inserted tree item
:rtype: Gtk.TreeItem
"""
if not history_item.state_reference:
logger.error("This must never happen! Current history_item is {}".format(history_item))
return None
content = None
if global_gui_config.get_config_value("SHOW_PATH_NAMES_IN_EXECUTION_HISTORY", False):
content = (history_item.state_reference.name + " - " +
history_item.state_reference.get_path() + " - " +
description, None if dummy else history_item,
None if dummy else self.TOOL_TIP_TEXT)
else:
content = (history_item.state_reference.name + " - " +
description, None if dummy else history_item,
None if dummy else self.TOOL_TIP_TEXT)
tree_item = self.history_tree_store.insert_before(
parent, None, content)
return tree_item | Enters a single history item into the tree store
:param Gtk.TreeItem parent: Parent tree item
:param HistoryItem history_item: History item to be inserted
:param str description: A description to be added to the entry
:param None dummy: Whether this is just a dummy entry (wrapper for concurrency items)
:return: Inserted tree item
:rtype: Gtk.TreeItem | entailment |
def insert_execution_history(self, parent, execution_history, is_root=False):
"""Insert a list of history items into a the tree store
If there are concurrency history items, the method is called recursively.
:param Gtk.TreeItem parent: the parent to add the next history item to
:param ExecutionHistory execution_history: all history items of a certain state machine execution
:param bool is_root: Whether this is the root execution history
"""
current_parent = parent
execution_history_iterator = iter(execution_history)
for history_item in execution_history_iterator:
if isinstance(history_item, ConcurrencyItem):
self.insert_concurrent_execution_histories(current_parent, history_item.execution_histories)
elif isinstance(history_item, CallItem):
tree_item = self.insert_history_item(current_parent, history_item, "Enter" if is_root else "Call")
if not tree_item:
return
if history_item.call_type is CallType.EXECUTE:
# this is necessary that already the CallType.EXECUTE item opens a new hierarchy in the
# tree view and not the CallType.CONTAINER item
next_history_item = history_item.next
if next_history_item and next_history_item.call_type is CallType.CONTAINER:
current_parent = tree_item
self.insert_history_item(current_parent, next_history_item, "Enter")
try:
next(execution_history_iterator) # skips the next history item in the iterator
except StopIteration as e:
# the execution engine does not have another item
return
else: # history_item is ReturnItem
if current_parent is None:
# The reasons here can be: missing history items, items in the wrong order etc.
# Does not happen when using RAFCON without plugins
logger.error("Invalid execution history: current_parent is None")
return
if history_item.call_type is CallType.EXECUTE:
self.insert_history_item(current_parent, history_item, "Return")
else: # CONTAINER
self.insert_history_item(current_parent, history_item, "Exit")
current_parent = self.history_tree_store.iter_parent(current_parent)
is_root = False | Insert a list of history items into a the tree store
If there are concurrency history items, the method is called recursively.
:param Gtk.TreeItem parent: the parent to add the next history item to
:param ExecutionHistory execution_history: all history items of a certain state machine execution
:param bool is_root: Whether this is the root execution history | entailment |
def insert_concurrent_execution_histories(self, parent, concurrent_execution_histories):
"""Adds the child execution histories of a concurrency state.
:param Gtk.TreeItem parent: the parent to add the next history item to
:param list[ExecutionHistory] concurrent_execution_histories: a list of all child execution histories
:return:
"""
for execution_history in concurrent_execution_histories:
if len(execution_history) >= 1:
first_history_item = execution_history[0]
# this is just a dummy item to have an extra parent for each branch
# gives better overview in case that one of the child state is a simple execution state
tree_item = self.insert_history_item(parent, first_history_item, "Concurrency Branch", dummy=True)
self.insert_execution_history(tree_item, execution_history) | Adds the child execution histories of a concurrency state.
:param Gtk.TreeItem parent: the parent to add the next history item to
:param list[ExecutionHistory] concurrent_execution_histories: a list of all child execution histories
:return: | entailment |
def on_drag_data_get(self, widget, context, data, info, time):
"""dragged state is inserted and its state_id sent to the receiver
:param widget:
:param context:
:param data: SelectionData: contains state_id
:param info:
:param time:
"""
library_state = self._get_selected_library_state()
import rafcon.gui.helpers.state_machine as gui_helper_state_machine
gui_helper_state_machine.add_state_by_drag_and_drop(library_state, data) | dragged state is inserted and its state_id sent to the receiver
:param widget:
:param context:
:param data: SelectionData: contains state_id
:param info:
:param time: | entailment |
def select_open_state_machine_of_selected_library_element(self):
"""Select respective state machine of selected library in state machine manager if already open """
(model, row_path) = self.view.get_selection().get_selected()
if row_path:
physical_library_path = model[row_path][self.ITEM_STORAGE_ID]
smm = gui_singletons.state_machine_manager_model.state_machine_manager
sm = smm.get_open_state_machine_of_file_system_path(physical_library_path)
if sm:
gui_singletons.state_machine_manager_model.selected_state_machine_id = sm.state_machine_id | Select respective state machine of selected library in state machine manager if already open | entailment |
def menu_item_remove_libraries_or_root_clicked(self, menu_item):
"""Removes library from hard drive after request second confirmation"""
menu_item_text = self.get_menu_item_text(menu_item)
logger.info("Delete item '{0}' pressed.".format(menu_item_text))
model, path = self.view.get_selection().get_selected()
if path:
# Second confirmation to delete library
tree_m_row = self.tree_store[path]
library_os_path, library_path, library_name, item_key = self.extract_library_properties_from_selected_row()
# assert isinstance(tree_m_row[self.ITEM_STORAGE_ID], str)
library_file_system_path = library_os_path
if "root" in menu_item_text:
button_texts = [menu_item_text + "from tree and config", "Cancel"]
partial_message = "This will remove the library root from your configuration (config.yaml)."
else:
button_texts = [menu_item_text, "Cancel"]
partial_message = "This folder will be removed from hard drive! You really wanna do that?"
message_string = "You choose to {2} with " \
"\n\nlibrary tree path: {0}" \
"\n\nphysical path: {1}.\n\n\n"\
"{3}" \
"".format(os.path.join(self.convert_if_human_readable(tree_m_row[self.LIB_PATH_STORAGE_ID]),
item_key),
library_file_system_path,
menu_item_text.lower(),
partial_message)
width = 8*len("physical path: " + library_file_system_path)
dialog = RAFCONButtonDialog(message_string, button_texts, message_type=Gtk.MessageType.QUESTION,
parent=self.get_root_window(), width=min(width, 1400))
response_id = dialog.run()
dialog.destroy()
if response_id == 1:
if "root" in menu_item_text:
logger.info("Remove library root key '{0}' from config.".format(item_key))
from rafcon.gui.singleton import global_config
library_paths = global_config.get_config_value('LIBRARY_PATHS')
del library_paths[tree_m_row[self.LIB_KEY_STORAGE_ID]]
global_config.save_configuration()
self.model.library_manager.refresh_libraries()
elif "libraries" in menu_item_text:
logger.debug("Remove of all libraries in {} is triggered.".format(library_os_path))
import shutil
shutil.rmtree(library_os_path)
self.model.library_manager.refresh_libraries()
else:
logger.debug("Remove of Library {} is triggered.".format(library_os_path))
self.model.library_manager.remove_library_from_file_system(library_path,
library_name)
elif response_id in [2, -4]:
pass
else:
logger.warning("Response id: {} is not considered".format(response_id))
return True
return False | Removes library from hard drive after request second confirmation | entailment |
def extract_library_properties_from_selected_row(self):
""" Extracts properties library_os_path, library_path, library_name and tree_item_key from tree store row """
(model, row) = self.view.get_selection().get_selected()
tree_item_key = model[row][self.ID_STORAGE_ID]
library_item = model[row][self.ITEM_STORAGE_ID]
library_path = model[row][self.LIB_PATH_STORAGE_ID]
if isinstance(library_item, dict): # sub-tree
os_path = model[row][self.OS_PATH_STORAGE_ID]
return os_path, None, None, tree_item_key # relevant elements of sub-tree
assert isinstance(library_item, string_types)
library_os_path = library_item
library_name = library_os_path.split(os.path.sep)[-1]
return library_os_path, library_path, library_name, tree_item_key | Extracts properties library_os_path, library_path, library_name and tree_item_key from tree store row | entailment |
def _get_selected_library_state(self):
"""Returns the LibraryState which was selected in the LibraryTree
:return: selected state in TreeView
:rtype: LibraryState
"""
library_os_path, library_path, library_name, item_key = self.extract_library_properties_from_selected_row()
if library_path is None:
return None
logger.debug("Link library state '{0}' (with library tree path: {2} and file system path: {1}) into state "
"machine.".format(str(item_key), library_os_path,
self.convert_if_human_readable(str(library_path)) + "/" + str(item_key)))
library_name = library_os_path.split(os.path.sep)[-1]
return LibraryState(library_path, library_name, "0.1", format_folder_name_human_readable(library_name)) | Returns the LibraryState which was selected in the LibraryTree
:return: selected state in TreeView
:rtype: LibraryState | entailment |
def start(self, execution_history, backward_execution=False, generate_run_id=True):
""" Starts the execution of the state in a new thread.
:return:
"""
self.execution_history = execution_history
if generate_run_id:
self._run_id = run_id_generator()
self.backward_execution = copy.copy(backward_execution)
self.thread = threading.Thread(target=self.run)
self.thread.start() | Starts the execution of the state in a new thread.
:return: | entailment |
def join(self):
""" Waits until the state finished execution.
"""
if self.thread:
self.thread.join()
self.thread = None
else:
logger.debug("Cannot join {0}, as the state hasn't been started, yet or is already finished!".format(self)) | Waits until the state finished execution. | entailment |
def setup_run(self):
""" Executes a generic set of actions that has to be called in the run methods of each derived state class.
:raises exceptions.TypeError: if the input or output data are not of type dict
"""
self.state_execution_status = StateExecutionStatus.ACTIVE
self.preempted = False
if not isinstance(self.input_data, dict):
raise TypeError("input_data must be of type dict")
if not isinstance(self.output_data, dict):
raise TypeError("output_data must be of type dict")
self.check_input_data_type() | Executes a generic set of actions that has to be called in the run methods of each derived state class.
:raises exceptions.TypeError: if the input or output data are not of type dict | entailment |
def recursively_preempt_states(self):
"""Preempt the state
"""
self.preempted = True
self.paused = False
self.started = False | Preempt the state | entailment |
def get_default_input_values_for_state(self, state):
""" Computes the default input values for a state
:param State state: the state to get the default input values for
"""
from rafcon.core.states.library_state import LibraryState
result_dict = {}
for input_port_key, value in state.input_data_ports.items():
if isinstance(state, LibraryState):
if state.use_runtime_value_input_data_ports[input_port_key]:
default = state.input_data_port_runtime_values[input_port_key]
else:
default = value.default_value
else:
default = value.default_value
# if the user sets the default value to a string starting with $, try to retrieve the value
# from the global variable manager
if isinstance(default, string_types) and len(default) > 0 and default[0] == '$':
from rafcon.core.singleton import global_variable_manager as gvm
var_name = default[1:]
if not gvm.variable_exist(var_name):
logger.error("The global variable '{0}' does not exist".format(var_name))
global_value = None
else:
global_value = gvm.get_variable(var_name)
result_dict[value.name] = global_value
else:
# set input to its default value
result_dict[value.name] = copy.copy(default)
return result_dict | Computes the default input values for a state
:param State state: the state to get the default input values for | entailment |
def create_output_dictionary_for_state(state):
"""Return empty output dictionary for a state
:param state: the state of which the output data is determined
:return: the output data of the target state
"""
from rafcon.core.states.library_state import LibraryState
result_dict = {}
for key, data_port in state.output_data_ports.items():
if isinstance(state, LibraryState) and state.use_runtime_value_output_data_ports[key]:
result_dict[data_port.name] = copy.copy(state.output_data_port_runtime_values[key])
else:
result_dict[data_port.name] = copy.copy(data_port.default_value)
return result_dict | Return empty output dictionary for a state
:param state: the state of which the output data is determined
:return: the output data of the target state | entailment |
def add_input_data_port(self, name, data_type=None, default_value=None, data_port_id=None):
"""Add a new input data port to the state.
:param str name: the name of the new input data port
:param data_type: the type of the new output data port considered of class :class:`type` or
:class:`str` which has to be convertible to :class:`type`
:param default_value: the default value of the data port
:param int data_port_id: the data_port_id of the new data port
:return: data_port_id of new input data port
:rtype: int
:raises exceptions.ValueError: if name of the input port is not unique
"""
if data_port_id is None:
# All data port ids have to passed to the id generation as the data port id has to be unique inside a state
data_port_id = generate_data_port_id(self.get_data_port_ids())
self._input_data_ports[data_port_id] = InputDataPort(name, data_type, default_value, data_port_id, self)
# Check for name uniqueness
valid, message = self._check_data_port_name(self._input_data_ports[data_port_id])
if not valid:
self._input_data_ports[data_port_id].parent = None
del self._input_data_ports[data_port_id]
raise ValueError(message)
return data_port_id | Add a new input data port to the state.
:param str name: the name of the new input data port
:param data_type: the type of the new output data port considered of class :class:`type` or
:class:`str` which has to be convertible to :class:`type`
:param default_value: the default value of the data port
:param int data_port_id: the data_port_id of the new data port
:return: data_port_id of new input data port
:rtype: int
:raises exceptions.ValueError: if name of the input port is not unique | entailment |
def remove_input_data_port(self, data_port_id, force=False, destroy=True):
"""Remove an input data port from the state
:param int data_port_id: the id or the output data port to remove
:param bool force: if the removal should be forced without checking constraints
:raises exceptions.AttributeError: if the specified input data port does not exist
"""
if data_port_id in self._input_data_ports:
if destroy:
self.remove_data_flows_with_data_port_id(data_port_id)
self._input_data_ports[data_port_id].parent = None
return self._input_data_ports.pop(data_port_id)
else:
raise AttributeError("input data port with name %s does not exit", data_port_id) | Remove an input data port from the state
:param int data_port_id: the id or the output data port to remove
:param bool force: if the removal should be forced without checking constraints
:raises exceptions.AttributeError: if the specified input data port does not exist | entailment |
def remove_data_flows_with_data_port_id(self, data_port_id):
"""Remove all data flows whose from_key or to_key equals the passed data_port_id
:param data_port_id: the id of a data_port of which all data_flows should be removed, the id can be a input or
output data port id
"""
if not self.is_root_state:
# delete all data flows in parent related to data_port_id and self.state_id
data_flow_ids_to_remove = []
for data_flow_id, data_flow in self.parent.data_flows.items():
if data_flow.from_state == self.state_id and data_flow.from_key == data_port_id or \
data_flow.to_state == self.state_id and data_flow.to_key == data_port_id:
data_flow_ids_to_remove.append(data_flow_id)
for data_flow_id in data_flow_ids_to_remove:
self.parent.remove_data_flow(data_flow_id) | Remove all data flows whose from_key or to_key equals the passed data_port_id
:param data_port_id: the id of a data_port of which all data_flows should be removed, the id can be a input or
output data port id | entailment |
def add_output_data_port(self, name, data_type, default_value=None, data_port_id=None):
"""Add a new output data port to the state
:param str name: the name of the new output data port
:param data_type: the type of the new output data port considered of class :class:`type` or
:class:`str` which has to be convertible to :class:`type`
:param default_value: the default value of the data port
:param int data_port_id: the data_port_id of the new data port
:return: data_port_id of new output data port
:rtype: int
:raises exceptions.ValueError: if name of the output port is not unique
"""
if data_port_id is None:
# All data port ids have to passed to the id generation as the data port id has to be unique inside a state
data_port_id = generate_data_port_id(self.get_data_port_ids())
self._output_data_ports[data_port_id] = OutputDataPort(name, data_type, default_value, data_port_id, self)
# Check for name uniqueness
valid, message = self._check_data_port_name(self._output_data_ports[data_port_id])
if not valid:
self._output_data_ports[data_port_id].parent = None
del self._output_data_ports[data_port_id]
raise ValueError(message)
return data_port_id | Add a new output data port to the state
:param str name: the name of the new output data port
:param data_type: the type of the new output data port considered of class :class:`type` or
:class:`str` which has to be convertible to :class:`type`
:param default_value: the default value of the data port
:param int data_port_id: the data_port_id of the new data port
:return: data_port_id of new output data port
:rtype: int
:raises exceptions.ValueError: if name of the output port is not unique | entailment |
def remove_output_data_port(self, data_port_id, force=False, destroy=True):
"""Remove an output data port from the state
:param int data_port_id: the id of the output data port to remove
:raises exceptions.AttributeError: if the specified input data port does not exist
"""
if data_port_id in self._output_data_ports:
if destroy:
self.remove_data_flows_with_data_port_id(data_port_id)
self._output_data_ports[data_port_id].parent = None
return self._output_data_ports.pop(data_port_id)
else:
raise AttributeError("output data port with name %s does not exit", data_port_id) | Remove an output data port from the state
:param int data_port_id: the id of the output data port to remove
:raises exceptions.AttributeError: if the specified input data port does not exist | entailment |
def get_io_data_port_id_from_name_and_type(self, name, data_port_type):
"""Returns the data_port_id of a data_port with a certain name and data port type
:param name: the name of the target data_port
:param data_port_type: the data port type of the target data port
:return: the data port specified by the name and the type
:raises exceptions.AttributeError: if the specified data port does not exist in the input or output data ports
"""
if data_port_type is InputDataPort:
for ip_id, output_port in self.input_data_ports.items():
if output_port.name == name:
return ip_id
raise AttributeError("Name '{0}' is not in input_data_ports".format(name))
elif data_port_type is OutputDataPort:
for op_id, output_port in self.output_data_ports.items():
if output_port.name == name:
return op_id
# 'error' is an automatically generated output port in case of errors and exception and doesn't have an id
if name == "error":
return
raise AttributeError("Name '{0}' is not in output_data_ports".format(name)) | Returns the data_port_id of a data_port with a certain name and data port type
:param name: the name of the target data_port
:param data_port_type: the data port type of the target data port
:return: the data port specified by the name and the type
:raises exceptions.AttributeError: if the specified data port does not exist in the input or output data ports | entailment |
def get_data_port_by_id(self, data_port_id):
"""Search for the given data port id in the data ports of the state
The method tries to find a data port in the input and output data ports.
:param int data_port_id: the unique id of the data port
:return: the data port with the searched id or None if it is not found
"""
if data_port_id in self.input_data_ports:
return self.input_data_ports[data_port_id]
elif data_port_id in self.output_data_ports:
return self.output_data_ports[data_port_id]
return None | Search for the given data port id in the data ports of the state
The method tries to find a data port in the input and output data ports.
:param int data_port_id: the unique id of the data port
:return: the data port with the searched id or None if it is not found | entailment |
def get_path(self, appendix=None, by_name=False):
""" Recursively create the path of the state.
The path is generated in bottom up method i.e. from the nested child states to the root state. The method
concatenates either State.state_id (always unique) or State.name (maybe not unique but human readable) as
state identifier for the path.
:param str appendix: the part of the path that was already calculated by previous function calls
:param bool by_name: The boolean enables name usage to generate the path
:rtype: str
:return: the full path to the root state
"""
if by_name:
state_identifier = self.name
else:
state_identifier = self.state_id
if not self.is_root_state:
if appendix is None:
return self.parent.get_path(state_identifier, by_name)
else:
return self.parent.get_path(state_identifier + PATH_SEPARATOR + appendix, by_name)
else:
if appendix is None:
return state_identifier
else:
return state_identifier + PATH_SEPARATOR + appendix | Recursively create the path of the state.
The path is generated in bottom up method i.e. from the nested child states to the root state. The method
concatenates either State.state_id (always unique) or State.name (maybe not unique but human readable) as
state identifier for the path.
:param str appendix: the part of the path that was already calculated by previous function calls
:param bool by_name: The boolean enables name usage to generate the path
:rtype: str
:return: the full path to the root state | entailment |
def get_storage_path(self, appendix=None):
""" Recursively create the storage path of the state.
The path is generated in bottom up method i.e. from the nested child states to the root state. The method
concatenates the concatenation of (State.name and State.state_id) as state identifier for the path.
:param str appendix: the part of the path that was already calculated by previous function calls
:rtype: str
:return: the full path to the root state
"""
state_identifier = storage.get_storage_id_for_state(self)
if not self.is_root_state:
if appendix is None:
return self.parent.get_storage_path(state_identifier)
else:
return self.parent.get_storage_path(state_identifier + PATH_SEPARATOR + appendix)
else:
if appendix is None:
return state_identifier
else:
return state_identifier + PATH_SEPARATOR + appendix | Recursively create the storage path of the state.
The path is generated in bottom up method i.e. from the nested child states to the root state. The method
concatenates the concatenation of (State.name and State.state_id) as state identifier for the path.
:param str appendix: the part of the path that was already calculated by previous function calls
:rtype: str
:return: the full path to the root state | entailment |
def get_state_machine(self):
"""Get a reference of the state_machine the state belongs to
:rtype rafcon.core.state_machine.StateMachine
:return: respective state machine
"""
if self.parent:
if self.is_root_state:
return self.parent
else:
return self.parent.get_state_machine()
return None | Get a reference of the state_machine the state belongs to
:rtype rafcon.core.state_machine.StateMachine
:return: respective state machine | entailment |
def file_system_path(self, file_system_path):
"""Setter for file_system_path attribute of state
:param str file_system_path:
:return:
"""
if not isinstance(file_system_path, string_types):
raise TypeError("file_system_path must be a string")
self._file_system_path = file_system_path | Setter for file_system_path attribute of state
:param str file_system_path:
:return: | entailment |
def add_outcome(self, name, outcome_id=None):
"""Add a new outcome to the state
:param str name: the name of the outcome to add
:param int outcome_id: the optional outcome_id of the new outcome
:return: outcome_id: the outcome if of the generated state
:rtype: int
"""
if outcome_id is None:
outcome_id = generate_outcome_id(list(self.outcomes.keys()))
if name in self._outcomes:
logger.error("Two outcomes cannot have the same names")
return
if outcome_id in self.outcomes:
logger.error("Two outcomes cannot have the same outcome_ids")
return
outcome = Outcome(outcome_id, name, self)
self._outcomes[outcome_id] = outcome
return outcome_id | Add a new outcome to the state
:param str name: the name of the outcome to add
:param int outcome_id: the optional outcome_id of the new outcome
:return: outcome_id: the outcome if of the generated state
:rtype: int | entailment |
def remove(self, state_element, recursive=True, force=False, destroy=True):
"""Remove item from state
:param StateElement state_element: State element to be removed
:param bool recursive: Only applies to removal of state and decides whether the removal should be called
recursively on all child states
:param bool force: if the removal should be forced without checking constraints
:param bool destroy: a flag that signals that the state element will be fully removed and disassembled
"""
if isinstance(state_element, Income):
self.remove_income(force, destroy=destroy)
if isinstance(state_element, Outcome):
return self.remove_outcome(state_element.outcome_id, force=force, destroy=destroy)
elif isinstance(state_element, InputDataPort):
return self.remove_input_data_port(state_element.data_port_id, force, destroy=destroy)
elif isinstance(state_element, OutputDataPort):
return self.remove_output_data_port(state_element.data_port_id, force, destroy=destroy)
else:
raise ValueError("Cannot remove state_element with invalid type") | Remove item from state
:param StateElement state_element: State element to be removed
:param bool recursive: Only applies to removal of state and decides whether the removal should be called
recursively on all child states
:param bool force: if the removal should be forced without checking constraints
:param bool destroy: a flag that signals that the state element will be fully removed and disassembled | entailment |
def remove_outcome(self, outcome_id, force=False, destroy=True):
"""Remove an outcome from the state
:param int outcome_id: the id of the outcome to remove
:raises exceptions.AttributeError: if the specified outcome does not exist or
equals the aborted or preempted outcome
"""
if outcome_id not in self.outcomes:
raise AttributeError("There is no outcome_id %s" % str(outcome_id))
if not force:
if outcome_id == -1 or outcome_id == -2:
raise AttributeError("You cannot remove the outcomes with id -1 or -2 as a state must always be able"
"to return aborted or preempted")
# Remove internal transitions to this outcome
self.remove_outcome_hook(outcome_id)
# delete possible transition connected to this outcome
if destroy and not self.is_root_state:
for transition_id, transition in self.parent.transitions.items():
if transition.from_outcome == outcome_id and transition.from_state == self.state_id:
self.parent.remove_transition(transition_id)
break # found the one outgoing transition
# delete outcome it self
self._outcomes[outcome_id].parent = None
return self._outcomes.pop(outcome_id) | Remove an outcome from the state
:param int outcome_id: the id of the outcome to remove
:raises exceptions.AttributeError: if the specified outcome does not exist or
equals the aborted or preempted outcome | entailment |
def check_child_validity(self, child):
"""Check validity of passed child object
The method is called by state child objects (outcomes, data ports) when these are initialized or changed. The
method checks the type of the child and then checks its validity in the context of the state.
:param object child: The child of the state that is to be tested
:return bool validity, str message: validity is True, when the child is valid, False else. message gives more
information especially if the child is not valid
"""
# Check type of child and call appropriate validity test
if isinstance(child, Income):
return self._check_income_validity(child)
if isinstance(child, Outcome):
return self._check_outcome_validity(child)
if isinstance(child, DataPort):
return self._check_data_port_validity(child)
if isinstance(child, ScopedData):
return self._check_scoped_data_validity(child)
return False, "Invalid state element for state of type {}".format(self.__class__.__name__) | Check validity of passed child object
The method is called by state child objects (outcomes, data ports) when these are initialized or changed. The
method checks the type of the child and then checks its validity in the context of the state.
:param object child: The child of the state that is to be tested
:return bool validity, str message: validity is True, when the child is valid, False else. message gives more
information especially if the child is not valid | entailment |
def _check_outcome_validity(self, check_outcome):
"""Checks the validity of an outcome
Checks whether the id or the name of the outcome is already used by another outcome within the state.
:param rafcon.core.logical_port.Outcome check_outcome: The outcome to be checked
:return bool validity, str message: validity is True, when the outcome is valid, False else. message gives more
information especially if the outcome is not valid
"""
for outcome_id, outcome in self.outcomes.items():
# Do not compare outcome with itself when checking for existing name/id
if check_outcome is not outcome:
if check_outcome.outcome_id == outcome_id:
return False, "outcome id '{0}' existing in state".format(check_outcome.outcome_id)
if check_outcome.name == outcome.name:
return False, "outcome name '{0}' existing in state".format(check_outcome.name)
return True, "valid" | Checks the validity of an outcome
Checks whether the id or the name of the outcome is already used by another outcome within the state.
:param rafcon.core.logical_port.Outcome check_outcome: The outcome to be checked
:return bool validity, str message: validity is True, when the outcome is valid, False else. message gives more
information especially if the outcome is not valid | entailment |
def _check_data_port_validity(self, check_data_port):
"""Checks the validity of a data port
Checks whether the data flows connected to the port do not conflict with the data types.
:param rafcon.core.data_port.DataPort check_data_port: The data port to be checked
:return bool validity, str message: validity is True, when the data port is valid, False else. message gives
more information especially if the data port is not valid
"""
valid, message = self._check_data_port_id(check_data_port)
if not valid:
return False, message
valid, message = self._check_data_port_name(check_data_port)
if not valid:
return False, message
# Check whether the type matches any connected data port type
# Only relevant, if there is a parent state, otherwise the port cannot be connected to data flows
# TODO: check of internal connections
if not self.is_root_state:
# Call the check in the parent state, where the data flows are stored
return self.parent.check_data_port_connection(check_data_port)
else:
from rafcon.core.states.container_state import ContainerState
if isinstance(self, ContainerState):
return self.check_data_port_connection(check_data_port)
return True, "valid" | Checks the validity of a data port
Checks whether the data flows connected to the port do not conflict with the data types.
:param rafcon.core.data_port.DataPort check_data_port: The data port to be checked
:return bool validity, str message: validity is True, when the data port is valid, False else. message gives
more information especially if the data port is not valid | entailment |
def _check_data_port_id(self, data_port):
"""Checks the validity of a data port id
Checks whether the id of the given data port is already used by anther data port (input, output) within the
state.
:param rafcon.core.data_port.DataPort data_port: The data port to be checked
:return bool validity, str message: validity is True, when the data port is valid, False else. message gives
more information especially if the data port is not valid
"""
for input_data_port_id, input_data_port in self.input_data_ports.items():
if data_port.data_port_id == input_data_port_id and data_port is not input_data_port:
return False, "data port id already existing in state"
for output_data_port_id, output_data_port in self.output_data_ports.items():
if data_port.data_port_id == output_data_port_id and data_port is not output_data_port:
return False, "data port id already existing in state"
return True, "valid" | Checks the validity of a data port id
Checks whether the id of the given data port is already used by anther data port (input, output) within the
state.
:param rafcon.core.data_port.DataPort data_port: The data port to be checked
:return bool validity, str message: validity is True, when the data port is valid, False else. message gives
more information especially if the data port is not valid | entailment |
def _check_data_port_name(self, data_port):
"""Checks the validity of a data port name
Checks whether the name of the given data port is already used by anther data port within the state. Names
must be unique with input data ports and output data ports.
:param rafcon.core.data_port.DataPort data_port: The data port to be checked
:return bool validity, str message: validity is True, when the data port is valid, False else. message gives
more information especially if the data port is not valid
"""
if data_port.data_port_id in self.input_data_ports:
for input_data_port in self.input_data_ports.values():
if data_port.name == input_data_port.name and data_port is not input_data_port:
return False, "data port name already existing in state's input data ports"
elif data_port.data_port_id in self.output_data_ports:
for output_data_port in self.output_data_ports.values():
if data_port.name == output_data_port.name and data_port is not output_data_port:
return False, "data port name already existing in state's output data ports"
return True, "valid" | Checks the validity of a data port name
Checks whether the name of the given data port is already used by anther data port within the state. Names
must be unique with input data ports and output data ports.
:param rafcon.core.data_port.DataPort data_port: The data port to be checked
:return bool validity, str message: validity is True, when the data port is valid, False else. message gives
more information especially if the data port is not valid | entailment |
def check_input_data_type(self):
"""Check the input data types of the state
Checks all input data ports if the handed data is not of the specified type and generate an error logger message
with details of the found type conflict.
"""
for data_port in self.input_data_ports.values():
if data_port.name in self.input_data and self.input_data[data_port.name] is not None:
#check for class
if not isinstance(self.input_data[data_port.name], data_port.data_type):
logger.error("{0} had an data port error: Input of execute function must be of type '{1}' not '{2}'"
" as current value '{3}'".format(self, data_port.data_type.__name__,
type(self.input_data[data_port.name]).__name__,
self.input_data[data_port.name])) | Check the input data types of the state
Checks all input data ports if the handed data is not of the specified type and generate an error logger message
with details of the found type conflict. | entailment |
def check_output_data_type(self):
"""Check the output data types of the state
Checks all output data ports if the handed data is not of the specified type and generate an error logger
message with details of the found type conflict.
"""
for data_port in self.output_data_ports.values():
if data_port.name in self.output_data and self.output_data[data_port.name] is not None:
# check for class
if not isinstance(self.output_data[data_port.name], data_port.data_type):
logger.error("{0} had an data port error: Output of execute function must be of type '{1}' not "
"'{2}' as current value {3}".format(self, data_port.data_type.__name__,
type(self.output_data[data_port.name]).__name__,
self.output_data[data_port.name])) | Check the output data types of the state
Checks all output data ports if the handed data is not of the specified type and generate an error logger
message with details of the found type conflict. | entailment |
def change_state_id(self, state_id=None):
"""Changes the id of the state to a new id
If no state_id is passed as parameter, a new state id is generated.
:param str state_id: The new state id of the state
:return:
"""
if state_id is None:
state_id = state_id_generator(used_state_ids=[self.state_id])
if not self.is_root_state and not self.is_root_state_of_library:
used_ids = list(self.parent.states.keys()) + [self.parent.state_id, self.state_id]
if state_id in used_ids:
state_id = state_id_generator(used_state_ids=used_ids)
self._state_id = state_id | Changes the id of the state to a new id
If no state_id is passed as parameter, a new state id is generated.
:param str state_id: The new state id of the state
:return: | entailment |
def get_semantic_data(self, path_as_list):
""" Retrieves an entry of the semantic data.
:param list path_as_list: The path in the vividict to retrieve the value from
:return:
"""
target_dict = self.semantic_data
for path_element in path_as_list:
if path_element in target_dict:
target_dict = target_dict[path_element]
else:
raise KeyError("The state with name {1} and id {2} holds no semantic data with path {0}."
"".format(path_as_list[:path_as_list.index(path_element) + 1], self.name, self.state_id))
return target_dict | Retrieves an entry of the semantic data.
:param list path_as_list: The path in the vividict to retrieve the value from
:return: | entailment |
def add_semantic_data(self, path_as_list, value, key):
""" Adds a semantic data entry.
:param list path_as_list: The path in the vividict to enter the value
:param value: The value of the new entry.
:param key: The key of the new entry.
:return:
"""
assert isinstance(key, string_types)
target_dict = self.get_semantic_data(path_as_list)
target_dict[key] = value
return path_as_list + [key] | Adds a semantic data entry.
:param list path_as_list: The path in the vividict to enter the value
:param value: The value of the new entry.
:param key: The key of the new entry.
:return: | entailment |
def remove_semantic_data(self, path_as_list):
""" Removes a entry from the semantic data vividict.
:param list path_as_list: The path of the vividict to delete.
:return: removed value or dict
"""
if len(path_as_list) == 0:
raise AttributeError("The argument path_as_list is empty but but the method remove_semantic_data needs a "
"valid path to remove a vividict item.")
target_dict = self.get_semantic_data(path_as_list[0:-1])
removed_element = target_dict[path_as_list[-1]]
del target_dict[path_as_list[-1]]
return removed_element | Removes a entry from the semantic data vividict.
:param list path_as_list: The path of the vividict to delete.
:return: removed value or dict | entailment |
def destroy(self, recursive):
""" Removes all the state elements.
:param recursive: Flag wether to destroy all state elements which are removed
"""
for in_key in list(self.input_data_ports.keys()):
self.remove_input_data_port(in_key, force=True, destroy=recursive)
for out_key in list(self.output_data_ports.keys()):
self.remove_output_data_port(out_key, force=True, destroy=recursive)
if self._income:
self.remove_income(force=True, destroy=recursive)
for outcome_key in list(self.outcomes.keys()):
self.remove_outcome(outcome_key, force=True, destroy=recursive) | Removes all the state elements.
:param recursive: Flag wether to destroy all state elements which are removed | entailment |
def input_data_ports(self, input_data_ports):
"""Property for the _input_data_ports field
See Property.
:param dict input_data_ports: Dictionary that maps :class:`int` data_port_ids onto values of type
:class:`rafcon.core.state_elements.data_port.InputDataPort`
:raises exceptions.TypeError: if the input_data_ports parameter has the wrong type
:raises exceptions.AttributeError: if the key of the input dictionary and the id of the data port do not match
"""
if not isinstance(input_data_ports, dict):
raise TypeError("input_data_ports must be of type dict")
if [port_id for port_id, port in input_data_ports.items() if not port_id == port.data_port_id]:
raise AttributeError("The key of the input dictionary and the id of the data port do not match")
# This is a fix for older state machines, which didn't distinguish between input and output ports
for port_id, port in input_data_ports.items():
if not isinstance(port, InputDataPort):
if isinstance(port, DataPort):
port = InputDataPort(port.name, port.data_type, port.default_value, port.data_port_id)
input_data_ports[port_id] = port
else:
raise TypeError("Elements of input_data_ports must be of type InputDataPort, given: {0}".format(
type(port).__name__))
old_input_data_ports = self._input_data_ports
self._input_data_ports = input_data_ports
for port_id, port in input_data_ports.items():
try:
port.parent = self
except ValueError:
self._input_data_ports = old_input_data_ports
raise
# check that all old_input_data_ports are no more referencing self as there parent
for old_input_data_port in old_input_data_ports.values():
if old_input_data_port not in self._input_data_ports.values() and old_input_data_port.parent is self:
old_input_data_port.parent = None | Property for the _input_data_ports field
See Property.
:param dict input_data_ports: Dictionary that maps :class:`int` data_port_ids onto values of type
:class:`rafcon.core.state_elements.data_port.InputDataPort`
:raises exceptions.TypeError: if the input_data_ports parameter has the wrong type
:raises exceptions.AttributeError: if the key of the input dictionary and the id of the data port do not match | entailment |
def output_data_ports(self, output_data_ports):
""" Setter for _output_data_ports field
See property
:param dict output_data_ports: Dictionary that maps :class:`int` data_port_ids onto values of type
:class:`rafcon.core.state_elements.data_port.OutputDataPort`
:raises exceptions.TypeError: if the output_data_ports parameter has the wrong type
:raises exceptions.AttributeError: if the key of the output dictionary and the id of the data port do not match
"""
if not isinstance(output_data_ports, dict):
raise TypeError("output_data_ports must be of type dict")
if [port_id for port_id, port in output_data_ports.items() if not port_id == port.data_port_id]:
raise AttributeError("The key of the output dictionary and the id of the data port do not match")
# This is a fix for older state machines, which didn't distinguish between input and output ports
for port_id, port in output_data_ports.items():
if not isinstance(port, OutputDataPort):
if isinstance(port, DataPort):
port = OutputDataPort(port.name, port.data_type, port.default_value, port.data_port_id)
output_data_ports[port_id] = port
else:
raise TypeError("Elements of output_data_ports must be of type OutputDataPort, given: {0}".format(
type(port).__name__))
old_output_data_ports = self._output_data_ports
self._output_data_ports = output_data_ports
for port_id, port in output_data_ports.items():
try:
port.parent = self
except ValueError:
self._output_data_ports = old_output_data_ports
raise
# check that all old_output_data_ports are no more referencing self as there parent
for old_output_data_port in old_output_data_ports.values():
if old_output_data_port not in self._output_data_ports.values() and old_output_data_port.parent is self:
old_output_data_port.parent = None | Setter for _output_data_ports field
See property
:param dict output_data_ports: Dictionary that maps :class:`int` data_port_ids onto values of type
:class:`rafcon.core.state_elements.data_port.OutputDataPort`
:raises exceptions.TypeError: if the output_data_ports parameter has the wrong type
:raises exceptions.AttributeError: if the key of the output dictionary and the id of the data port do not match | entailment |
def income(self, income):
"""Setter for the state's income"""
if not isinstance(income, Income):
raise ValueError("income must be of type Income")
old_income = self.income
self._income = income
try:
income.parent = self
except ValueError:
self._income = old_income
raise | Setter for the state's income | entailment |
def outcomes(self, outcomes):
""" Setter for _outcomes field
See property.
:param dict outcomes: Dictionary outcomes[outcome_id] that maps :class:`int` outcome_ids onto values of type
:class:`rafcon.core.state_elements.logical_port.Outcome`
:raises exceptions.TypeError: if outcomes parameter has the wrong type
:raises exceptions.AttributeError: if the key of the outcome dictionary and the id of the outcome do not match
"""
if not isinstance(outcomes, dict):
raise TypeError("outcomes must be of type dict")
if [outcome_id for outcome_id, outcome in outcomes.items() if not isinstance(outcome, Outcome)]:
raise TypeError("element of outcomes must be of type Outcome")
if [outcome_id for outcome_id, outcome in outcomes.items() if not outcome_id == outcome.outcome_id]:
raise AttributeError("The key of the outcomes dictionary and the id of the outcome do not match")
old_outcomes = self.outcomes
self._outcomes = outcomes
for outcome_id, outcome in outcomes.items():
try:
outcome.parent = self
except ValueError:
self._outcomes = old_outcomes
raise
# aborted and preempted must always exist
if -1 not in outcomes:
self._outcomes[-1] = Outcome(outcome_id=-1, name="aborted", parent=self)
if -2 not in outcomes:
self._outcomes[-2] = Outcome(outcome_id=-2, name="preempted", parent=self)
# check that all old_outcomes are no more referencing self as there parent
for old_outcome in old_outcomes.values():
if old_outcome not in iter(list(self._outcomes.values())) and old_outcome.parent is self:
old_outcome.parent = None | Setter for _outcomes field
See property.
:param dict outcomes: Dictionary outcomes[outcome_id] that maps :class:`int` outcome_ids onto values of type
:class:`rafcon.core.state_elements.logical_port.Outcome`
:raises exceptions.TypeError: if outcomes parameter has the wrong type
:raises exceptions.AttributeError: if the key of the outcome dictionary and the id of the outcome do not match | entailment |
def is_root_state_of_library(self):
""" If self is the attribute LibraryState.state_copy of a LibraryState its the library root state and its parent
is a LibraryState
:return True or False
:rtype bool
"""
from rafcon.core.states.library_state import LibraryState
return isinstance(self.parent, LibraryState) | If self is the attribute LibraryState.state_copy of a LibraryState its the library root state and its parent
is a LibraryState
:return True or False
:rtype bool | entailment |
def get_next_upper_library_root_state(self):
""" Get next upper library root state
The method recursively checks state parent states till finding a StateMachine as parent or a library root state.
If self is a LibraryState the next upper library root state is searched and it is not handed self.state_copy.
:return library root state (Execution or ContainerState) or None if self is not a library root state or
inside of such
:rtype rafcon.core.states.library_state.State:
"""
from rafcon.core.state_machine import StateMachine
if self.is_root_state_of_library:
return self
state = self
while state.parent is not None and not isinstance(state.parent, StateMachine):
if state.parent.is_root_state_of_library:
return state.parent
state = state.parent
return None | Get next upper library root state
The method recursively checks state parent states till finding a StateMachine as parent or a library root state.
If self is a LibraryState the next upper library root state is searched and it is not handed self.state_copy.
:return library root state (Execution or ContainerState) or None if self is not a library root state or
inside of such
:rtype rafcon.core.states.library_state.State: | entailment |
def get_uppermost_library_root_state(self):
"""Find state_copy of uppermost LibraryState
Method checks if there is a parent library root state and assigns it to be the current library root state till
there is no further parent library root state.
"""
library_root_state = self.get_next_upper_library_root_state()
parent_library_root_state = library_root_state
# initial a library root state has to be found and if there is no further parent root state
# parent_library_root_state and library_root_state are no more identical
while parent_library_root_state and library_root_state is parent_library_root_state:
if library_root_state:
parent_library_root_state = library_root_state.parent.get_next_upper_library_root_state()
if parent_library_root_state:
library_root_state = parent_library_root_state
return library_root_state | Find state_copy of uppermost LibraryState
Method checks if there is a parent library root state and assigns it to be the current library root state till
there is no further parent library root state. | entailment |
def finalize(self, outcome=None):
"""Finalize state
This method is called when the run method finishes
:param rafcon.core.logical_port.Outcome outcome: final outcome of the state
:return: Nothing for the moment
"""
# Set the final outcome of the state
if outcome is not None:
self.final_outcome = outcome
# If we are within a concurrency state, we have to notify it about our finalization
if self.concurrency_queue:
self.concurrency_queue.put(self.state_id)
logger.debug("Finished execution of {0}: {1}".format(self, self.final_outcome))
return None | Finalize state
This method is called when the run method finishes
:param rafcon.core.logical_port.Outcome outcome: final outcome of the state
:return: Nothing for the moment | entailment |
def cluster_on_extra_high_voltage(network, busmap, with_time=True):
""" Main function of the EHV-Clustering approach. Creates a new clustered
pypsa.Network given a busmap mapping all bus_ids to other bus_ids of the
same network.
Parameters
----------
network : pypsa.Network
Container for all network components.
busmap : dict
Maps old bus_ids to new bus_ids.
with_time : bool
If true time-varying data will also be aggregated.
Returns
-------
network : pypsa.Network
Container for all network components of the clustered network.
"""
network_c = Network()
buses = aggregatebuses(
network, busmap, {
'x': _leading(
busmap, network.buses), 'y': _leading(
busmap, network.buses)})
# keep attached lines
lines = network.lines.copy()
mask = lines.bus0.isin(buses.index)
lines = lines.loc[mask, :]
# keep attached links
links = network.links.copy()
mask = links.bus0.isin(buses.index)
links = links.loc[mask, :]
# keep attached transformer
transformers = network.transformers.copy()
mask = transformers.bus0.isin(buses.index)
transformers = transformers.loc[mask, :]
io.import_components_from_dataframe(network_c, buses, "Bus")
io.import_components_from_dataframe(network_c, lines, "Line")
io.import_components_from_dataframe(network_c, links, "Link")
io.import_components_from_dataframe(network_c, transformers, "Transformer")
if with_time:
network_c.snapshots = network.snapshots
network_c.set_snapshots(network.snapshots)
network_c.snapshot_weightings = network.snapshot_weightings.copy()
# dealing with generators
network.generators.control = "PV"
network.generators['weight'] = 1
new_df, new_pnl = aggregategenerators(network, busmap, with_time)
io.import_components_from_dataframe(network_c, new_df, 'Generator')
for attr, df in iteritems(new_pnl):
io.import_series_from_dataframe(network_c, df, 'Generator', attr)
# dealing with all other components
aggregate_one_ports = components.one_port_components.copy()
aggregate_one_ports.discard('Generator')
for one_port in aggregate_one_ports:
new_df, new_pnl = aggregateoneport(
network, busmap, component=one_port, with_time=with_time)
io.import_components_from_dataframe(network_c, new_df, one_port)
for attr, df in iteritems(new_pnl):
io.import_series_from_dataframe(network_c, df, one_port, attr)
network_c.determine_network_topology()
return network_c | Main function of the EHV-Clustering approach. Creates a new clustered
pypsa.Network given a busmap mapping all bus_ids to other bus_ids of the
same network.
Parameters
----------
network : pypsa.Network
Container for all network components.
busmap : dict
Maps old bus_ids to new bus_ids.
with_time : bool
If true time-varying data will also be aggregated.
Returns
-------
network : pypsa.Network
Container for all network components of the clustered network. | entailment |
def graph_from_edges(edges):
""" Constructs an undirected multigraph from a list containing data on
weighted edges.
Parameters
----------
edges : list
List of tuples each containing first node, second node, weight, key.
Returns
-------
M : :class:`networkx.classes.multigraph.MultiGraph
"""
M = nx.MultiGraph()
for e in edges:
n0, n1, weight, key = e
M.add_edge(n0, n1, weight=weight, key=key)
return M | Constructs an undirected multigraph from a list containing data on
weighted edges.
Parameters
----------
edges : list
List of tuples each containing first node, second node, weight, key.
Returns
-------
M : :class:`networkx.classes.multigraph.MultiGraph | entailment |
def gen(nodes, n, graph):
# TODO There could be a more convenient way of doing this. This generators
# single purpose is to prepare data for multiprocessing's starmap function.
""" Generator for applying multiprocessing.
Parameters
----------
nodes : list
List of nodes in the system.
n : int
Number of desired multiprocessing units.
graph : :class:`networkx.classes.multigraph.MultiGraph
Graph representation of an electrical grid.
Returns
-------
None
"""
g = graph.copy()
for i in range(0, len(nodes), n):
yield (nodes[i:i + n], g) | Generator for applying multiprocessing.
Parameters
----------
nodes : list
List of nodes in the system.
n : int
Number of desired multiprocessing units.
graph : :class:`networkx.classes.multigraph.MultiGraph
Graph representation of an electrical grid.
Returns
-------
None | entailment |
def busmap_from_psql(network, session, scn_name):
""" Retrieves busmap from `model_draft.ego_grid_pf_hv_busmap` on the
<OpenEnergyPlatform>[www.openenergy-platform.org] by a given scenario
name. If this busmap does not exist, it is created with default values.
Parameters
----------
network : pypsa.Network object
Container for all network components.
session : sqlalchemy.orm.session.Session object
Establishes interactions with the database.
scn_name : str
Name of the scenario.
Returns
-------
busmap : dict
Maps old bus_ids to new bus_ids.
"""
def fetch():
query = session.query(EgoGridPfHvBusmap.bus0, EgoGridPfHvBusmap.bus1).\
filter(EgoGridPfHvBusmap.scn_name == scn_name)
return dict(query.all())
busmap = fetch()
# TODO: Or better try/except/finally
if not busmap:
print('Busmap does not exist and will be created.\n')
cpu_cores = input('cpu_cores (default 4): ') or '4'
busmap_by_shortest_path(network, session, scn_name,
fromlvl=[110], tolvl=[220, 380, 400, 450],
cpu_cores=int(cpu_cores))
busmap = fetch()
return busmap | Retrieves busmap from `model_draft.ego_grid_pf_hv_busmap` on the
<OpenEnergyPlatform>[www.openenergy-platform.org] by a given scenario
name. If this busmap does not exist, it is created with default values.
Parameters
----------
network : pypsa.Network object
Container for all network components.
session : sqlalchemy.orm.session.Session object
Establishes interactions with the database.
scn_name : str
Name of the scenario.
Returns
-------
busmap : dict
Maps old bus_ids to new bus_ids. | entailment |
def kmean_clustering(network, n_clusters=10, load_cluster=False,
line_length_factor=1.25,
remove_stubs=False, use_reduced_coordinates=False,
bus_weight_tocsv=None, bus_weight_fromcsv=None,
n_init=10, max_iter=300, tol=1e-4,
n_jobs=1):
""" Main function of the k-mean clustering approach. Maps an original
network to a new one with adjustable number of nodes and new coordinates.
Parameters
----------
network : :class:`pypsa.Network
Container for all network components.
n_clusters : int
Desired number of clusters.
load_cluster : boolean
Loads cluster coordinates from a former calculation.
line_length_factor : float
Factor to multiply the crow-flies distance between new buses in order
to get new line lengths.
remove_stubs: boolean
Removes stubs and stubby trees (i.e. sequentially reducing dead-ends).
use_reduced_coordinates: boolean
If True, do not average cluster coordinates, but take from busmap.
bus_weight_tocsv : str
Creates a bus weighting based on conventional generation and load
and save it to a csv file.
bus_weight_fromcsv : str
Loads a bus weighting from a csv file to apply it to the clustering
algorithm.
Returns
-------
network : pypsa.Network object
Container for all network components.
"""
def weighting_for_scenario(x, save=None):
"""
"""
b_i = x.index
g = normed(gen.reindex(b_i, fill_value=0))
l = normed(load.reindex(b_i, fill_value=0))
w = g + l
weight = ((w * (100000. / w.max())).astype(int)
).reindex(network.buses.index, fill_value=1)
if save:
weight.to_csv(save)
return weight
def normed(x):
return (x / x.sum()).fillna(0.)
print('start k-mean clustering')
# prepare k-mean
# k-means clustering (first try)
network.generators.control = "PV"
network.storage_units.control[network.storage_units.carrier == \
'extendable_storage'] = "PV"
network.buses['v_nom'] = 380.
# problem our lines have no v_nom. this is implicitly defined by the
# connected buses:
network.lines["v_nom"] = network.lines.bus0.map(network.buses.v_nom)
# adjust the x of the lines which are not 380.
lines_v_nom_b = network.lines.v_nom != 380
network.lines.loc[lines_v_nom_b, 'x'] *= \
(380. / network.lines.loc[lines_v_nom_b, 'v_nom'])**2
network.lines.loc[lines_v_nom_b, 'v_nom'] = 380.
trafo_index = network.transformers.index
transformer_voltages = \
pd.concat([network.transformers.bus0.map(network.buses.v_nom),
network.transformers.bus1.map(network.buses.v_nom)], axis=1)
network.import_components_from_dataframe(
network.transformers.loc[:, [
'bus0', 'bus1', 'x', 's_nom', 'capital_cost', 'sub_network', 's_nom_total']]
.assign(x=network.transformers.x * (380. /
transformer_voltages.max(axis=1))**2, length = 1)
.set_index('T' + trafo_index),
'Line')
network.transformers.drop(trafo_index, inplace=True)
for attr in network.transformers_t:
network.transformers_t[attr] = network.transformers_t[attr]\
.reindex(columns=[])
# remove stubs
if remove_stubs:
network.determine_network_topology()
busmap = busmap_by_stubs(network)
network.generators['weight'] = network.generators['p_nom']
aggregate_one_ports = components.one_port_components.copy()
aggregate_one_ports.discard('Generator')
# reset coordinates to the new reduced guys, rather than taking an
# average (copied from pypsa.networkclustering)
if use_reduced_coordinates:
# TODO : FIX THIS HACK THAT HAS UNEXPECTED SIDE-EFFECTS,
# i.e. network is changed in place!!
network.buses.loc[busmap.index, ['x', 'y']
] = network.buses.loc[busmap, ['x', 'y']].values
clustering = get_clustering_from_busmap(
network,
busmap,
aggregate_generators_weighted=True,
aggregate_one_ports=aggregate_one_ports,
line_length_factor=line_length_factor)
network = clustering.network
# define weighting based on conventional 'old' generator spatial
# distribution
non_conv_types = {
'biomass',
'wind_onshore',
'wind_offshore',
'solar',
'geothermal',
'load shedding',
'extendable_storage'}
# Attention: network.generators.carrier.unique()
gen = (network.generators.loc[(network.generators.carrier
.isin(non_conv_types) == False)]
.groupby('bus').p_nom.sum()
.reindex(network.buses.index, fill_value=0.) +
network.storage_units
.loc[(network.storage_units.carrier
.isin(non_conv_types) == False)]
.groupby('bus').p_nom.sum()
.reindex(network.buses.index, fill_value=0.))
load = network.loads_t.p_set.mean().groupby(network.loads.bus).sum()
# k-mean clustering
# busmap = busmap_by_kmeans(network, bus_weightings=pd.Series(np.repeat(1,
# len(network.buses)), index=network.buses.index) , n_clusters= 10)
# State whether to create a bus weighting and save it, create or not save
# it, or use a bus weighting from a csv file
if bus_weight_tocsv is not None:
weight = weighting_for_scenario(x=network.buses, save=bus_weight_tocsv)
elif bus_weight_fromcsv is not None:
weight = pd.Series.from_csv(bus_weight_fromcsv)
weight.index = weight.index.astype(str)
else:
weight = weighting_for_scenario(x=network.buses, save=False)
busmap = busmap_by_kmeans(
network,
bus_weightings=pd.Series(weight),
n_clusters=n_clusters,
load_cluster=load_cluster,
n_init=n_init,
max_iter=max_iter,
tol=tol,
n_jobs=n_jobs)
# ToDo change function in order to use bus_strategies or similar
network.generators['weight'] = network.generators['p_nom']
aggregate_one_ports = components.one_port_components.copy()
aggregate_one_ports.discard('Generator')
clustering = get_clustering_from_busmap(
network,
busmap,
aggregate_generators_weighted=True,
aggregate_one_ports=aggregate_one_ports)
return clustering | Main function of the k-mean clustering approach. Maps an original
network to a new one with adjustable number of nodes and new coordinates.
Parameters
----------
network : :class:`pypsa.Network
Container for all network components.
n_clusters : int
Desired number of clusters.
load_cluster : boolean
Loads cluster coordinates from a former calculation.
line_length_factor : float
Factor to multiply the crow-flies distance between new buses in order
to get new line lengths.
remove_stubs: boolean
Removes stubs and stubby trees (i.e. sequentially reducing dead-ends).
use_reduced_coordinates: boolean
If True, do not average cluster coordinates, but take from busmap.
bus_weight_tocsv : str
Creates a bus weighting based on conventional generation and load
and save it to a csv file.
bus_weight_fromcsv : str
Loads a bus weighting from a csv file to apply it to the clustering
algorithm.
Returns
-------
network : pypsa.Network object
Container for all network components. | entailment |
def register_actions(self, shortcut_manager):
"""Register callback methods for triggered actions
:param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings
between shortcuts and actions.
"""
super(DescriptionEditorController, self).register_actions(shortcut_manager)
shortcut_manager.add_callback_for_action("abort", self._abort) | Register callback methods for triggered actions
:param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings
between shortcuts and actions. | entailment |
def register_view(self, view):
"""Called when the View was registered"""
super(GraphicalEditorController, self).register_view(view)
self.view.connect('meta_data_changed', self._meta_data_changed)
self.focus_changed_handler_id = self.view.editor.connect('focus-changed', self._move_focused_item_into_viewport)
self.view.editor.connect("drag-data-received", self.on_drag_data_received)
self.drag_motion_handler_id = self.view.editor.connect("drag-motion", self.on_drag_motion)
self.setup_canvas() | Called when the View was registered | entailment |
def register_actions(self, shortcut_manager):
"""Register callback methods for triggered actions
:param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings
between shortcuts and actions.
"""
shortcut_manager.add_callback_for_action("add", partial(self._add_new_state, state_type=StateType.EXECUTION))
shortcut_manager.add_callback_for_action("add_execution_state", partial(self._add_new_state,
state_type=StateType.EXECUTION))
shortcut_manager.add_callback_for_action("add_hierarchy_state", partial(self._add_new_state,
state_type=StateType.HIERARCHY))
shortcut_manager.add_callback_for_action("add_barrier_state", partial(self._add_new_state,
state_type=StateType.BARRIER_CONCURRENCY))
shortcut_manager.add_callback_for_action("add_preemptive_state", partial(self._add_new_state,
state_type=StateType.PREEMPTION_CONCURRENCY))
shortcut_manager.add_callback_for_action("add_output", partial(self._add_data_port_to_selected_state,
data_port_type='OUTPUT'))
shortcut_manager.add_callback_for_action("add_input", partial(self._add_data_port_to_selected_state,
data_port_type='INPUT'))
shortcut_manager.add_callback_for_action("add_scoped_variable", self._add_scoped_variable_to_selected_state)
shortcut_manager.add_callback_for_action("add_outcome", self._add_outcome_to_selected_state)
shortcut_manager.add_callback_for_action("delete", self._remove_selected_elements)
shortcut_manager.add_callback_for_action("copy", self._copy_selection)
shortcut_manager.add_callback_for_action("paste", self._paste_clipboard)
shortcut_manager.add_callback_for_action("cut", self._cut_selection)
shortcut_manager.add_callback_for_action('show_data_flows', self.update_view)
shortcut_manager.add_callback_for_action('show_data_values', self.update_view)
shortcut_manager.add_callback_for_action('data_flow_mode', self.data_flow_mode)
shortcut_manager.add_callback_for_action('show_aborted_preempted', self.update_view) | Register callback methods for triggered actions
:param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings
between shortcuts and actions. | 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]
# config_value = info['args'][2]
if config_key in ["ENABLE_CACHING", "SHOW_ABORTED_PREEMPTED", "SHOW_DATA_FLOWS",
"SHOW_DATA_FLOW_VALUE_LABELS", "SHOW_NAMES_ON_DATA_FLOWS", "ROTATE_NAMES_ON_CONNECTION"]:
self.update_view() | 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 on_drag_data_received(self, widget, context, x, y, data, info, time):
"""Receives state_id from LibraryTree and moves the state to the position of the mouse
:param widget:
:param context:
:param x: Integer: x-position of mouse
:param y: Integer: y-position of mouse
:param data: SelectionData: contains state_id
:param info:
:param time:
"""
state_id_insert = data.get_text()
parent_m = self.model.selection.get_selected_state()
if not isinstance(parent_m, ContainerStateModel):
return
state_v = self.canvas.get_view_for_model(parent_m.states[state_id_insert])
pos_start = state_v.model.get_meta_data_editor()['rel_pos']
motion = InMotion(state_v, self.view.editor)
motion.start_move(self.view.editor.get_matrix_i2v(state_v).transform_point(pos_start[0], pos_start[1]))
motion.move((x, y))
motion.stop_move()
state_v.model.set_meta_data_editor('rel_pos', motion.item.position)
self.canvas.wait_for_update(trigger_update=True)
self._meta_data_changed(None, state_v.model, 'append_to_last_change', True) | Receives state_id from LibraryTree and moves the state to the position of the mouse
:param widget:
:param context:
:param x: Integer: x-position of mouse
:param y: Integer: y-position of mouse
:param data: SelectionData: contains state_id
:param info:
:param time: | entailment |
def on_drag_motion(self, widget, context, x, y, time):
"""Changes the selection on mouse over during drag motion
:param widget:
:param context:
:param x: Integer: x-position of mouse
:param y: Integer: y-position of mouse
:param time:
"""
hovered_item = ItemFinder(self.view.editor).get_item_at_point((x, y))
if isinstance(hovered_item, NameView):
hovered_item = hovered_item.parent
if hovered_item is None:
self.view.editor.unselect_all()
elif isinstance(hovered_item.model, ContainerStateModel):
if len(self.view.editor.selected_items) == 1 and hovered_item in self.view.editor.selected_items:
return
if len(self.view.editor.selected_items) > 0:
self.view.editor.unselect_all()
if not rafcon.gui.singleton.global_gui_config.get_config_value('DRAG_N_DROP_WITH_FOCUS'):
self.view.editor.handler_block(self.focus_changed_handler_id)
self.view.editor.focused_item = hovered_item
if not rafcon.gui.singleton.global_gui_config.get_config_value('DRAG_N_DROP_WITH_FOCUS'):
self.view.editor.handler_unblock(self.focus_changed_handler_id) | Changes the selection on mouse over during drag motion
:param widget:
:param context:
:param x: Integer: x-position of mouse
:param y: Integer: y-position of mouse
:param time: | entailment |
def _add_new_state(self, *event, **kwargs):
"""Triggered when shortcut keys for adding a new state are pressed, or Menu Bar "Edit, Add State" is clicked.
Adds a new state only if the graphical editor is in focus.
"""
if react_to_event(self.view, self.view.editor, event):
state_type = StateType.EXECUTION if 'state_type' not in kwargs else kwargs['state_type']
return gui_helper_state_machine.add_new_state(self.model, state_type) | Triggered when shortcut keys for adding a new state are pressed, or Menu Bar "Edit, Add State" is clicked.
Adds a new state only if the graphical editor is in focus. | entailment |
def _copy_selection(self, *event):
"""Copies the current selection to the clipboard.
"""
if react_to_event(self.view, self.view.editor, event):
logger.debug("copy selection")
global_clipboard.copy(self.model.selection)
return True | Copies the current selection to the clipboard. | entailment |
def _cut_selection(self, *event):
"""Cuts the current selection and copys it to the clipboard.
"""
if react_to_event(self.view, self.view.editor, event):
logger.debug("cut selection")
global_clipboard.cut(self.model.selection)
return True | Cuts the current selection and copys it to the clipboard. | entailment |
def _paste_clipboard(self, *event):
"""Paste the current clipboard into the current selection if the current selection is a container state.
"""
if react_to_event(self.view, self.view.editor, event):
logger.debug("Paste")
gui_helper_state_machine.paste_into_selected_state(self.model)
return True | Paste the current clipboard into the current selection if the current selection is a container state. | entailment |
def _move_focused_item_into_viewport(self, view, focused_item):
"""Called when an item is focused, moves the item into the viewport
:param view:
:param StateView | ConnectionView | PortView focused_item: The focused item
"""
self.view.editor.handler_block(self.drag_motion_handler_id)
self.move_item_into_viewport(focused_item)
self.view.editor.handler_unblock(self.drag_motion_handler_id) | Called when an item is focused, moves the item into the viewport
:param view:
:param StateView | ConnectionView | PortView focused_item: The focused item | entailment |
def move_item_into_viewport(self, item):
"""Causes the `item` to be moved into the viewport
The zoom factor and the position of the viewport are updated to move the `item` into the viewport. If `item`
is not a `StateView`, the parental `StateView` is moved into the viewport.
:param StateView | ConnectionView | PortView item: The item to be moved into the viewport
"""
if not item:
return
HORIZONTAL = 0
VERTICAL = 1
if not isinstance(item, Item):
state_v = item.parent
elif not isinstance(item, StateView):
state_v = self.canvas.get_parent(item)
else:
state_v = item
viewport_size = self.view.editor.get_allocation().width, self.view.editor.get_allocation().height
state_size = self.view.editor.get_matrix_i2v(state_v).transform_distance(state_v.width, state_v.height)
min_relative_size = min(viewport_size[i] / state_size[i] for i in [HORIZONTAL, VERTICAL])
if min_relative_size != 1:
# Allow margin around state
margin_relative = 1. / gui_constants.BORDER_WIDTH_STATE_SIZE_FACTOR
zoom_factor = min_relative_size * (1 - margin_relative)
if zoom_factor > 1:
zoom_base = 4
zoom_factor = max(1, math.log(zoom_factor*zoom_base, zoom_base))
self.view.editor.zoom(zoom_factor)
# The zoom operation must be performed before the pan operation to work on updated GtkAdjustments (scroll
# bars)
self.canvas.wait_for_update()
state_pos = self.view.editor.get_matrix_i2v(state_v).transform_point(0, 0)
state_size = self.view.editor.get_matrix_i2v(state_v).transform_distance(state_v.width, state_v.height)
viewport_size = self.view.editor.get_allocation().width, self.view.editor.get_allocation().height
# Calculate offset around state so that the state is centered in the viewport
padding_offset_horizontal = (viewport_size[HORIZONTAL] - state_size[HORIZONTAL]) / 2.
padding_offset_vertical = (viewport_size[VERTICAL] - state_size[VERTICAL]) / 2.
self.view.editor.hadjustment.set_value(state_pos[HORIZONTAL] - padding_offset_horizontal)
self.view.editor.vadjustment.set_value(state_pos[VERTICAL] - padding_offset_vertical) | Causes the `item` to be moved into the viewport
The zoom factor and the position of the viewport are updated to move the `item` into the viewport. If `item`
is not a `StateView`, the parental `StateView` is moved into the viewport.
:param StateView | ConnectionView | PortView item: The item to be moved into the viewport | entailment |
def state_machine_destruction(self, model, prop_name, info):
""" Clean up when state machine is being destructed """
if self.model is model: # only used for the state machine destruction case
self.canvas.get_view_for_model(self.root_state_m).remove() | Clean up when state machine is being destructed | entailment |
def meta_changed_notify_after(self, state_machine_m, _, info):
"""Handle notification about the change of a state's meta data
The meta data of the affected state(s) are read and the view updated accordingly.
:param StateMachineModel state_machine_m: Always the state machine model belonging to this editor
:param str _: Always "state_meta_signal"
:param dict info: Information about the change, contains the MetaSignalMessage in the 'arg' key value
"""
meta_signal_message = info['arg']
if meta_signal_message.origin == "graphical_editor_gaphas": # Ignore changes caused by ourself
return
if meta_signal_message.origin == "load_meta_data": # Meta data can't be applied, as the view has not yet
return # been created
notification = meta_signal_message.notification
if not notification: # For changes applied to the root state, there are always two notifications
return # Ignore the one with less information
if self.model.ongoing_complex_actions:
return
model = notification.model
view = self.canvas.get_view_for_model(model)
if meta_signal_message.change == 'show_content':
library_state_m = model
library_state_v = view
if library_state_m.meta['gui']['show_content'] is not library_state_m.show_content():
logger.warning("The content of the LibraryState won't be shown, because "
"MAX_VISIBLE_LIBRARY_HIERARCHY is 1.")
if library_state_m.show_content():
if not library_state_m.state_copy_initialized:
logger.warning("Show library content without initialized state copy does not work {0}"
"".format(library_state_m))
logger.debug("Show content of {}".format(library_state_m.state))
gui_helper_meta_data.scale_library_content(library_state_m)
self.add_state_view_for_model(library_state_m.state_copy, view,
hierarchy_level=library_state_v.hierarchy_level + 1)
else:
logger.debug("Hide content of {}".format(library_state_m.state))
state_copy_v = self.canvas.get_view_for_model(library_state_m.state_copy)
if state_copy_v:
state_copy_v.remove()
else:
if isinstance(view, StateView):
view.apply_meta_data(recursive=meta_signal_message.affects_children)
else:
view.apply_meta_data()
self.canvas.request_update(view, matrix=True)
self.canvas.wait_for_update() | Handle notification about the change of a state's meta data
The meta data of the affected state(s) are read and the view updated accordingly.
:param StateMachineModel state_machine_m: Always the state machine model belonging to this editor
:param str _: Always "state_meta_signal"
:param dict info: Information about the change, contains the MetaSignalMessage in the 'arg' key value | entailment |
def state_machine_change_after(self, model, prop_name, info):
"""Called on any change within th state machine
This method is called, when any state, transition, data flow, etc. within the state machine changes. This
then typically requires a redraw of the graphical editor, to display these changes immediately.
:param rafcon.gui.models.state_machine.StateMachineModel model: The state machine model
:param str prop_name: The property that was changed
:param dict info: Information about the change
"""
if 'method_name' in info and info['method_name'] == 'root_state_change':
method_name, model, result, arguments, instance = self._extract_info_data(info['kwargs'])
if self.model.ongoing_complex_actions:
return
# The method causing the change raised an exception, thus nothing was changed
if (isinstance(result, string_types) and "CRASH" in result) or isinstance(result, Exception):
return
# avoid to remove views of elements of states which parent state is destroyed recursively
if 'remove' in method_name:
# for remove the model is always a state and in case of remove_state it is the container_state
# that performs the operation therefore if is_about_to_be_destroyed_recursively is False
# the child state can be removed and for True ignored because its parent will create a notification
if model.is_about_to_be_destroyed_recursively:
return
# only react to the notification if the model is a model, which has to be drawn
# if it is a model inside a library state, this is eventually not the case
if isinstance(model, AbstractStateModel):
library_root_state = model.state.get_next_upper_library_root_state()
if library_root_state:
parent_library_root_state_m = self.model.get_state_model_by_path(library_root_state.get_path())
if not parent_library_root_state_m.parent.show_content():
return
if method_name == 'state_execution_status':
state_v = self.canvas.get_view_for_model(model)
if state_v: # Children of LibraryStates are not modeled, yet
self.canvas.request_update(state_v, matrix=False)
elif method_name == 'add_state':
new_state = arguments[1]
new_state_m = model.states[new_state.state_id]
self.add_state_view_with_meta_data_for_model(new_state_m, model)
if not self.perform_drag_and_drop:
self.canvas.wait_for_update()
elif method_name == 'remove_state':
state_v = self.canvas.get_view_for_core_element(result)
if state_v:
parent_v = self.canvas.get_parent(state_v)
state_v.remove()
if parent_v:
self.canvas.request_update(parent_v)
self.canvas.wait_for_update()
# ----------------------------------
# TRANSITIONS
# ----------------------------------
elif method_name == 'add_transition':
transitions_models = model.transitions
transition_id = result
for transition_m in transitions_models:
if transition_m.transition.transition_id == transition_id:
self.add_transition_view_for_model(transition_m, model)
self.canvas.wait_for_update()
break
elif method_name == 'remove_transition':
transition_v = self.canvas.get_view_for_core_element(result)
if transition_v:
state_m = model
state_v = self.canvas.get_view_for_model(state_m)
transition_v.remove()
self.canvas.request_update(state_v, matrix=False)
self.canvas.wait_for_update()
elif method_name == 'transition_change':
transition_m = model
transition_v = self.canvas.get_view_for_model(transition_m)
self._reconnect_transition(transition_v, transition_m, transition_m.parent)
self.canvas.wait_for_update()
# ----------------------------------
# DATA FLOW
# ----------------------------------
elif method_name == 'add_data_flow':
data_flow_models = model.data_flows
data_flow_id = result
for data_flow_m in data_flow_models:
if data_flow_m.data_flow.data_flow_id == data_flow_id:
self.add_data_flow_view_for_model(data_flow_m, model)
self.canvas.wait_for_update()
break
elif method_name == 'remove_data_flow':
data_flow_v = self.canvas.get_view_for_core_element(result)
if data_flow_v:
state_m = model
state_v = self.canvas.get_view_for_model(state_m)
self.canvas.request_update(state_v, matrix=False)
data_flow_v.remove()
self.canvas.wait_for_update()
elif method_name == 'data_flow_change':
data_flow_m = model
data_flow_v = self.canvas.get_view_for_model(data_flow_m)
self._reconnect_data_flow(data_flow_v, data_flow_m, data_flow_m.parent)
self.canvas.wait_for_update()
# ----------------------------------
# OUTCOMES
# ----------------------------------
elif method_name == 'add_outcome':
state_m = model
state_v = self.canvas.get_view_for_model(state_m)
for outcome_m in state_m.outcomes:
if outcome_m.outcome.outcome_id == result:
state_v.add_outcome(outcome_m)
self.canvas.request_update(state_v, matrix=False)
self.canvas.wait_for_update()
break
elif method_name == 'remove_outcome':
state_m = model
state_v = self.canvas.get_view_for_model(state_m)
if state_v is None:
logger.debug("no state_v found for method_name '{}'".format(method_name))
else:
outcome_v = self.canvas.get_view_for_core_element(result)
if outcome_v:
state_v.remove_outcome(outcome_v)
self.canvas.request_update(state_v, matrix=False)
self.canvas.wait_for_update()
# ----------------------------------
# DATA PORTS
# ----------------------------------
elif method_name == 'add_input_data_port':
state_m = model
state_v = self.canvas.get_view_for_model(state_m)
for input_data_port_m in state_m.input_data_ports:
if input_data_port_m.data_port.data_port_id == result:
state_v.add_input_port(input_data_port_m)
self.canvas.request_update(state_v, matrix=False)
self.canvas.wait_for_update()
break
elif method_name == 'add_output_data_port':
state_m = model
state_v = self.canvas.get_view_for_model(state_m)
for output_data_port_m in state_m.output_data_ports:
if output_data_port_m.data_port.data_port_id == result:
state_v.add_output_port(output_data_port_m)
self.canvas.request_update(state_v, matrix=False)
self.canvas.wait_for_update()
break
elif method_name == 'remove_input_data_port':
state_m = model
state_v = self.canvas.get_view_for_model(state_m)
if state_v is None:
logger.debug("no state_v found for method_name '{}'".format(method_name))
else:
input_port_v = self.canvas.get_view_for_core_element(result)
if input_port_v:
state_v.remove_input_port(input_port_v)
self.canvas.request_update(state_v, matrix=False)
self.canvas.wait_for_update()
elif method_name == 'remove_output_data_port':
state_m = model
state_v = self.canvas.get_view_for_model(state_m)
if state_v is None:
logger.debug("no state_v found for method_name '{}'".format(method_name))
else:
output_port_v = self.canvas.get_view_for_core_element(result)
if output_port_v:
state_v.remove_output_port(output_port_v)
self.canvas.request_update(state_v, matrix=False)
self.canvas.wait_for_update()
elif method_name in ['data_type', 'change_data_type']:
pass
elif method_name == 'default_value':
pass
# ----------------------------------
# SCOPED VARIABLES
# ----------------------------------
elif method_name == 'add_scoped_variable':
state_m = model
state_v = self.canvas.get_view_for_model(state_m)
for scoped_variable_m in state_m.scoped_variables:
if scoped_variable_m.scoped_variable.data_port_id == result:
state_v.add_scoped_variable(scoped_variable_m)
self.canvas.request_update(state_v, matrix=False)
self.canvas.wait_for_update()
break
elif method_name == 'remove_scoped_variable':
state_m = model
state_v = self.canvas.get_view_for_model(state_m)
if state_v is None:
logger.debug("no state_v found for method_name '{}'".format(method_name))
else:
scoped_variable_v = self.canvas.get_view_for_core_element(result)
if scoped_variable_v:
state_v.remove_scoped_variable(scoped_variable_v)
self.canvas.request_update(state_v, matrix=False)
self.canvas.wait_for_update()
# ----------------------------------
# STATE MISCELLANEOUS
# ----------------------------------
elif method_name == 'name':
# The name of a state was changed
if not isinstance(model, AbstractStateModel):
parent_model = model.parent
# The name of a port (input, output, scoped var, outcome) was changed
else:
parent_model = model
state_v = self.canvas.get_view_for_model(parent_model)
if parent_model is model:
state_v.name_view.name = arguments[1]
self.canvas.request_update(state_v.name_view, matrix=False)
else:
self.canvas.request_update(state_v, matrix=False)
self.canvas.wait_for_update()
elif method_name == 'parent':
pass
elif method_name == 'description':
pass
elif method_name == 'script_text':
pass
# TODO handle the following method calls -> for now those are explicit (in the past implicit) ignored
# TODO -> correct the complex actions which are used in some test (by test calls or by adapting the model)
elif method_name in ['input_data_ports', 'output_data_ports', 'outcomes',
'change_root_state_type', 'change_state_type',
'group_states', 'ungroup_state', 'substitute_state']:
pass
else:
known_ignore_list = ['set_input_runtime_value', 'set_use_input_runtime_value', # from library State
'set_output_runtime_value', 'set_use_output_runtime_value',
'input_data_port_runtime_values', 'use_runtime_value_input_data_ports',
'output_data_port_runtime_values', 'use_runtime_value_output_data_ports',
'semantic_data', 'add_semantic_data', 'remove_semantic_data',
'remove_income']
if method_name not in known_ignore_list:
logger.warning("Method {0} not caught in GraphicalViewer, details: {1}".format(method_name, info))
if method_name in ['add_state', 'add_transition', 'add_data_flow', 'add_outcome', 'add_input_data_port',
'add_output_data_port', 'add_scoped_variable', 'data_flow_change', 'transition_change']:
try:
self._meta_data_changed(None, model, 'append_to_last_change', True)
except Exception as e:
logger.exception('Error while trying to emit meta data signal {0} {1}'.format(e, model)) | Called on any change within th state machine
This method is called, when any state, transition, data flow, etc. within the state machine changes. This
then typically requires a redraw of the graphical editor, to display these changes immediately.
:param rafcon.gui.models.state_machine.StateMachineModel model: The state machine model
:param str prop_name: The property that was changed
:param dict info: Information about the change | entailment |
def set_focus_to_state_model(self, state_m, ratio_requested=0.8):
""" Focus a state view of respective state model
:param rafcon.gui.model.state state_m: Respective state model of state view to be focused
:param ratio_requested: Minimum ratio of the screen which is requested, so can be more
:return:
"""
state_machine_m = self.model
state_v = self.canvas.get_view_for_model(state_m)
if state_v is None:
logger.warning('There is no view for state model {0}'.format(state_m))
self.move_item_into_viewport(state_v)
# check_relative size in view and call it again if the state is still very small
state_v = self.canvas.get_view_for_model(state_machine_m.root_state)
state_size = self.view.editor.get_matrix_i2v(state_v).transform_distance(state_v.width, state_v.height)
viewport_size = self.view.editor.get_allocation().width, self.view.editor.get_allocation().height
if state_size[0] < ratio_requested*viewport_size[0] and state_size[1] < ratio_requested*viewport_size[1]:
self.set_focus_to_state_model(state_m, ratio_requested) | Focus a state view of respective state model
:param rafcon.gui.model.state state_m: Respective state model of state view to be focused
:param ratio_requested: Minimum ratio of the screen which is requested, so can be more
:return: | entailment |
def add_state_view_for_model(self, state_m, parent_v=None, rel_pos=(0, 0), size=(100, 100), hierarchy_level=1):
"""Creates a `StateView` (recursively) and adds it to the canvas
The method uses the `StateModel` `state_m` to create the according `StateView`. For all content within
`state_m`, such as connections, states and ports, the views are also created. All views are added to the canvas.
:param rafcon.gui.models.state.StateModel state_m: The state to be drawn
:param rafcon.gui.mygaphas.items.state.StateView parent_v: The parent state view of new state view `state_m`
:param tuple rel_pos: The default relative position (x, y) if there is no relative position stored
:param tuple size: The default size (width, height) if there is no size stored
:param float hierarchy_level: The hierarchy level of the state
:return: The created `StateView`
:rtype: StateView
"""
assert isinstance(state_m, AbstractStateModel)
state_meta = state_m.get_meta_data_editor()
# Use default values if no size information is stored
if not gui_helper_meta_data.contains_geometric_info(state_meta['size']):
state_meta = state_m.set_meta_data_editor('size', size)
size = state_meta['size']
# Use default values if no position information is stored
if not gui_helper_meta_data.contains_geometric_info(state_meta['rel_pos']):
state_meta = state_m.set_meta_data_editor('rel_pos', rel_pos)
rel_pos = state_meta['rel_pos']
if isinstance(state_m, LibraryStateModel):
if not state_m.meta_data_was_scaled:
gui_helper_meta_data.scale_library_ports_meta_data(state_m, gaphas_editor=True)
state_v = StateView(state_m, size, hierarchy_level)
# Draw state above data flows and NameView but beneath transitions
num_data_flows = len(state_m.state.parent.data_flows) if isinstance(state_m.parent, ContainerStateModel) else 0
index = 1 if not parent_v else num_data_flows + 1
# if self.model.root_state is state_m:
# print("init root_state", state_m, state_v)
# else:
# print("init state", state_m, state_v)
# print([hash(elem) for elem in state_m.state.outcomes.values()])
self.canvas.add(state_v, parent_v, index=index)
state_v.matrix.translate(*rel_pos)
state_v.add_income(state_m.income)
for outcome_m in state_m.outcomes:
state_v.add_outcome(outcome_m)
for input_port_m in state_m.input_data_ports:
state_v.add_input_port(input_port_m)
for output_port_m in state_m.output_data_ports:
state_v.add_output_port(output_port_m)
if parent_v is not None:
# Keep state within parent
pass
if isinstance(state_m, LibraryStateModel) and state_m.show_content() and state_m.state_copy_initialized:
gui_helper_meta_data.scale_library_content(state_m)
self.add_state_view_for_model(state_m.state_copy, state_v, hierarchy_level=hierarchy_level + 1)
elif isinstance(state_m, ContainerStateModel):
num_child_state = 0
for scoped_variable_m in state_m.scoped_variables:
state_v.add_scoped_variable(scoped_variable_m)
for child_state_m in state_m.states.values():
# generate optional meta data for child state - not used if valid meta data already in child state model
child_rel_pos, child_size = gui_helper_meta_data.generate_default_state_meta_data(state_m, self.canvas,
num_child_state)
num_child_state += 1
self.add_state_view_for_model(child_state_m, state_v, child_rel_pos, child_size, hierarchy_level + 1)
for transition_m in state_m.transitions:
self.add_transition_view_for_model(transition_m, state_m)
for data_flow_m in state_m.data_flows:
self.add_data_flow_view_for_model(data_flow_m, state_m)
return state_v | Creates a `StateView` (recursively) and adds it to the canvas
The method uses the `StateModel` `state_m` to create the according `StateView`. For all content within
`state_m`, such as connections, states and ports, the views are also created. All views are added to the canvas.
:param rafcon.gui.models.state.StateModel state_m: The state to be drawn
:param rafcon.gui.mygaphas.items.state.StateView parent_v: The parent state view of new state view `state_m`
:param tuple rel_pos: The default relative position (x, y) if there is no relative position stored
:param tuple size: The default size (width, height) if there is no size stored
:param float hierarchy_level: The hierarchy level of the state
:return: The created `StateView`
:rtype: StateView | entailment |
def add_transition_view_for_model(self, transition_m, parent_state_m):
"""Creates a `TransitionView` and adds it to the canvas
The method creates a`TransitionView` from the given `TransitionModel `transition_m` and adds it to the canvas.
:param TransitionModel transition_m: The transition for which a view is to be created
:param ContainerStateModel parent_state_m: The parental `StateModel` of the transition
"""
parent_state_v = self.canvas.get_view_for_model(parent_state_m)
hierarchy_level = parent_state_v.hierarchy_level
transition_v = TransitionView(transition_m, hierarchy_level)
# Draw transition above all other state elements
self.canvas.add(transition_v, parent_state_v, index=None)
self._connect_transition_to_ports(transition_m, transition_v, parent_state_m, parent_state_v)
return transition_v | Creates a `TransitionView` and adds it to the canvas
The method creates a`TransitionView` from the given `TransitionModel `transition_m` and adds it to the canvas.
:param TransitionModel transition_m: The transition for which a view is to be created
:param ContainerStateModel parent_state_m: The parental `StateModel` of the transition | entailment |
def add_data_flow_view_for_model(self, data_flow_m, parent_state_m):
"""Creates a `DataFlowView` and adds it to the canvas
The method creates a`DataFlowView` from the given `DataFlowModel `data_flow_m` and adds it to the canvas.
:param DataFlowModel data_flow_m: The data flow for which a view is to be created
:param ContainerStateModel parent_state_m: The parental `StateModel` of the data flow
"""
parent_state_v = self.canvas.get_view_for_model(parent_state_m)
hierarchy_level = parent_state_v.hierarchy_level
data_flow_v = DataFlowView(data_flow_m, hierarchy_level)
# Draw data flow above NameView but beneath all other state elements
self.canvas.add(data_flow_v, parent_state_v, index=1)
self._connect_data_flow_to_ports(data_flow_m, data_flow_v, parent_state_m) | Creates a `DataFlowView` and adds it to the canvas
The method creates a`DataFlowView` from the given `DataFlowModel `data_flow_m` and adds it to the canvas.
:param DataFlowModel data_flow_m: The data flow for which a view is to be created
:param ContainerStateModel parent_state_m: The parental `StateModel` of the data flow | entailment |
def react_to_event(self, event):
"""Check whether the given event should be handled
Checks, whether the editor widget has the focus and whether the selected state machine corresponds to the
state machine of this editor.
:param event: GTK event object
:return: True if the event should be handled, else False
:rtype: bool
"""
if not react_to_event(self.view, self.view.editor, event):
return False
if not rafcon.gui.singleton.state_machine_manager_model.selected_state_machine_id == \
self.model.state_machine.state_machine_id:
return False
return True | Check whether the given event should be handled
Checks, whether the editor widget has the focus and whether the selected state machine corresponds to the
state machine of this editor.
:param event: GTK event object
:return: True if the event should be handled, else False
:rtype: bool | entailment |
async def initialize(bot: Bot, host, password, rest_port, ws_port, timeout=30):
"""
Initializes the websocket connection to the lavalink player.
.. important::
This function must only be called AFTER the bot has received its
"on_ready" event!
Parameters
----------
bot : Bot
An instance of a discord.py `Bot` object.
host : str
The hostname or IP address of the Lavalink node.
password : str
The password of the Lavalink node.
rest_port : int
The port of the REST API on the Lavalink node.
ws_port : int
The websocket port on the Lavalink Node.
timeout : int
Amount of time to allow retries to occur, ``None`` is considered forever.
"""
global _loop
_loop = bot.loop
player_manager.user_id = bot.user.id
player_manager.channel_finder_func = bot.get_channel
register_event_listener(_handle_event)
register_update_listener(_handle_update)
lavalink_node = node.Node(
_loop,
dispatch,
bot._connection._get_websocket,
host,
password,
port=ws_port,
rest=rest_port,
user_id=player_manager.user_id,
num_shards=bot.shard_count if bot.shard_count is not None else 1,
)
await lavalink_node.connect(timeout=timeout)
bot.add_listener(node.on_socket_response)
bot.add_listener(_on_guild_remove, name="on_guild_remove")
return lavalink_node | Initializes the websocket connection to the lavalink player.
.. important::
This function must only be called AFTER the bot has received its
"on_ready" event!
Parameters
----------
bot : Bot
An instance of a discord.py `Bot` object.
host : str
The hostname or IP address of the Lavalink node.
password : str
The password of the Lavalink node.
rest_port : int
The port of the REST API on the Lavalink node.
ws_port : int
The websocket port on the Lavalink Node.
timeout : int
Amount of time to allow retries to occur, ``None`` is considered forever. | entailment |
async def connect(channel: discord.VoiceChannel):
"""
Connects to a discord voice channel.
This is the publicly exposed way to connect to a discord voice channel.
The :py:func:`initialize` function must be called first!
Parameters
----------
channel
Returns
-------
Player
The created Player object.
Raises
------
IndexError
If there are no available lavalink nodes ready to connect to discord.
"""
node_ = node.get_node(channel.guild.id)
p = await node_.player_manager.create_player(channel)
return p | Connects to a discord voice channel.
This is the publicly exposed way to connect to a discord voice channel.
The :py:func:`initialize` function must be called first!
Parameters
----------
channel
Returns
-------
Player
The created Player object.
Raises
------
IndexError
If there are no available lavalink nodes ready to connect to discord. | entailment |
def register_event_listener(coro):
"""
Registers a coroutine to receive lavalink event information.
This coroutine will accept three arguments: :py:class:`Player`,
:py:class:`LavalinkEvents`, and possibly an extra. The value of the extra depends
on the value of the second argument.
If the second argument is :py:attr:`LavalinkEvents.TRACK_END`, the extra will
be a :py:class:`TrackEndReason`.
If the second argument is :py:attr:`LavalinkEvents.TRACK_EXCEPTION`, the extra
will be an error string.
If the second argument is :py:attr:`LavalinkEvents.TRACK_STUCK`, the extra will
be the threshold milliseconds that the track has been stuck for.
If the second argument is :py:attr:`LavalinkEvents.TRACK_START`, the extra will be
a :py:class:`Track` object.
If the second argument is any other value, the third argument will not exist.
Parameters
----------
coro
A coroutine function that accepts the arguments listed above.
Raises
------
TypeError
If ``coro`` is not a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("Function is not a coroutine.")
if coro not in _event_listeners:
_event_listeners.append(coro) | Registers a coroutine to receive lavalink event information.
This coroutine will accept three arguments: :py:class:`Player`,
:py:class:`LavalinkEvents`, and possibly an extra. The value of the extra depends
on the value of the second argument.
If the second argument is :py:attr:`LavalinkEvents.TRACK_END`, the extra will
be a :py:class:`TrackEndReason`.
If the second argument is :py:attr:`LavalinkEvents.TRACK_EXCEPTION`, the extra
will be an error string.
If the second argument is :py:attr:`LavalinkEvents.TRACK_STUCK`, the extra will
be the threshold milliseconds that the track has been stuck for.
If the second argument is :py:attr:`LavalinkEvents.TRACK_START`, the extra will be
a :py:class:`Track` object.
If the second argument is any other value, the third argument will not exist.
Parameters
----------
coro
A coroutine function that accepts the arguments listed above.
Raises
------
TypeError
If ``coro`` is not a coroutine. | entailment |
def register_update_listener(coro):
"""
Registers a coroutine to receive lavalink player update information.
This coroutine will accept a two arguments: an instance of :py:class:`Player`
and an instance of :py:class:`PlayerState`.
Parameters
----------
coro
Raises
------
TypeError
If ``coro`` is not a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("Function is not a coroutine.")
if coro not in _update_listeners:
_update_listeners.append(coro) | Registers a coroutine to receive lavalink player update information.
This coroutine will accept a two arguments: an instance of :py:class:`Player`
and an instance of :py:class:`PlayerState`.
Parameters
----------
coro
Raises
------
TypeError
If ``coro`` is not a coroutine. | entailment |
def register_stats_listener(coro):
"""
Registers a coroutine to receive lavalink server stats information.
This coroutine will accept a single argument which will be an instance
of :py:class:`Stats`.
Parameters
----------
coro
Raises
------
TypeError
If ``coro`` is not a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("Function is not a coroutine.")
if coro not in _stats_listeners:
_stats_listeners.append(coro) | Registers a coroutine to receive lavalink server stats information.
This coroutine will accept a single argument which will be an instance
of :py:class:`Stats`.
Parameters
----------
coro
Raises
------
TypeError
If ``coro`` is not a coroutine. | entailment |
def prepare_destruction(self):
"""Get rid of circular references"""
self._tool = None
self._painter = None
self.relieve_model(self._selection)
self._selection = None
# clear observer class attributes, also see ExtendenController.destroy()
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() | Get rid of circular references | entailment |
def get_port_at_point(self, vpos, distance=10, exclude=None, exclude_port_fun=None):
"""
Find item with port closest to specified position.
List of items to be ignored can be specified with `exclude`
parameter.
Tuple is returned
- found item
- closest, connectable port
- closest point on found port (in view coordinates)
:Parameters:
vpos
Position specified in view coordinates.
distance
Max distance from point to a port (default 10)
exclude
Set of items to ignore.
"""
# Method had to be inherited, as the base method has a bug:
# It misses the statement max_dist = d
v2i = self.get_matrix_v2i
vx, vy = vpos
max_dist = distance
port = None
glue_pos = None
item = None
rect = (vx - distance, vy - distance, distance * 2, distance * 2)
items = self.get_items_in_rectangle(rect, reverse=True)
for i in items:
if exclude and i in exclude:
continue
for p in i.ports():
if not p.connectable:
continue
if exclude_port_fun and exclude_port_fun(p):
continue
ix, iy = v2i(i).transform_point(vx, vy)
pg, d = p.glue((ix, iy))
if d > max_dist:
continue
max_dist = d
item = i
port = p
# transform coordinates from connectable item space to view
# space
i2v = self.get_matrix_i2v(i).transform_point
glue_pos = i2v(*pg)
return item, port, glue_pos | Find item with port closest to specified position.
List of items to be ignored can be specified with `exclude`
parameter.
Tuple is returned
- found item
- closest, connectable port
- closest point on found port (in view coordinates)
:Parameters:
vpos
Position specified in view coordinates.
distance
Max distance from point to a port (default 10)
exclude
Set of items to ignore. | entailment |
def get_item_at_point_exclude(self, pos, selected=True, exclude=None):
"""
Return the topmost item located at ``pos`` (x, y).
Parameters:
- selected: if False returns first non-selected item
- exclude: if specified don't check for these items
"""
items = self._qtree.find_intersect((pos[0], pos[1], 1, 1))
for item in self._canvas.sort(items, reverse=True):
if not selected and item in self.selected_items:
continue # skip selected items
if item in exclude:
continue
v2i = self.get_matrix_v2i(item)
ix, iy = v2i.transform_point(*pos)
if item.point((ix, iy)) < 0.5:
return item
return None | Return the topmost item located at ``pos`` (x, y).
Parameters:
- selected: if False returns first non-selected item
- exclude: if specified don't check for these items | entailment |
def queue_draw_item(self, *items):
"""Extends the base class method to allow Ports to be passed as item
:param items: Items that are to be redrawn
"""
gaphas_items = []
for item in items:
if isinstance(item, Element):
gaphas_items.append(item)
else:
try:
gaphas_items.append(item.parent)
except AttributeError:
pass
super(ExtendedGtkView, self).queue_draw_item(*gaphas_items) | Extends the base class method to allow Ports to be passed as item
:param items: Items that are to be redrawn | entailment |
def get_items_at_point(self, pos, selected=True, distance=0):
""" Return the items located at ``pos`` (x, y).
:param bool selected: if False returns first non-selected item
:param float distance: Maximum distance to be considered as "at point" (in viewport pixel)
"""
items = self._qtree.find_intersect((pos[0] - distance, pos[1] - distance, 2 * distance, 2 * distance))
filtered_items = []
for item in self._canvas.sort(items, reverse=True):
if not selected and item in self.selected_items:
continue # skip selected items
v2i = self.get_matrix_v2i(item)
i2v = self.get_matrix_i2v(item)
ix, iy = v2i.transform_point(*pos)
distance_i = item.point((ix, iy))
distance_v = i2v.transform_distance(distance_i, 0)[0]
if distance_v <= distance:
filtered_items.append(item)
return filtered_items | Return the items located at ``pos`` (x, y).
:param bool selected: if False returns first non-selected item
:param float distance: Maximum distance to be considered as "at point" (in viewport pixel) | entailment |
def select_item(self, items):
""" Select an items. This adds `items` to the set of selected items. """
if not items:
return
elif not hasattr(items, "__iter__"):
items = (items,)
selection_changed = False
with self._suppress_selection_events():
for item in items:
self.queue_draw_item(item)
if item is not None and item.model not in self._selection:
self._selection.add(item.model)
selection_changed = True
if selection_changed:
self.emit('selection-changed', self._get_selected_items()) | Select an items. This adds `items` to the set of selected items. | entailment |
def unselect_item(self, item):
""" Unselect an item. """
self.queue_draw_item(item)
if item.model in self._selection:
with self._suppress_selection_events():
self._selection.remove(item.model)
self.emit('selection-changed', self._get_selected_items()) | Unselect an item. | entailment |
def unselect_all(self):
""" Clearing the selected_item also clears the focused_item. """
items = self._get_selected_items()
with self._suppress_selection_events():
self._selection.clear()
self.queue_draw_item(*items)
self.emit('selection-changed', self._get_selected_items()) | Clearing the selected_item also clears the focused_item. | entailment |
def _get_selected_items(self):
""" Return an Item (e.g. StateView) for each model (e.g. StateModel) in the current selection """
return set(self.canvas.get_view_for_model(model) for model in self._selection) | Return an Item (e.g. StateView) for each model (e.g. StateModel) in the current selection | entailment |
def handle_new_selection(self, items):
""" Determines the selection
The selection is based on the previous selection, the currently pressed keys and the passes newly selected items
:param items: The newly selected item(s)
"""
if items is None:
items = ()
elif not hasattr(items, "__iter__"):
items = (items,)
models = set(item.model for item in items)
self._selection.handle_new_selection(models) | Determines the selection
The selection is based on the previous selection, the currently pressed keys and the passes newly selected items
:param items: The newly selected item(s) | entailment |
def _get_focused_item(self):
""" Returns the currently focused item """
focused_model = self._selection.focus
if not focused_model:
return None
return self.canvas.get_view_for_model(focused_model) | Returns the currently focused item | entailment |
def _set_focused_item(self, item):
""" Sets the focus to the passed item"""
if not item:
return self._del_focused_item()
if item.model is not self._selection.focus:
self.queue_draw_item(self._focused_item, item)
self._selection.focus = item.model
self.emit('focus-changed', item) | Sets the focus to the passed item | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.