idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
40,400 | def update_port_side ( self ) : from rafcon . utils . geometry import point_left_of_line p = ( self . _initial_pos . x , self . _initial_pos . y ) nw_x , nw_y , se_x , se_y = self . get_adjusted_border_positions ( ) if point_left_of_line ( p , ( nw_x , nw_y ) , ( se_x , se_y ) ) : if point_left_of_line ( p , ( nw_x , se_y ) , ( se_x , nw_y ) ) : self . _port . side = SnappedSide . TOP self . limit_pos ( p [ 0 ] , se_x , nw_x ) else : self . _port . side = SnappedSide . RIGHT self . limit_pos ( p [ 1 ] , se_y , nw_y ) else : if point_left_of_line ( p , ( nw_x , se_y ) , ( se_x , nw_y ) ) : self . _port . side = SnappedSide . LEFT self . limit_pos ( p [ 1 ] , se_y , nw_y ) else : self . _port . side = SnappedSide . BOTTOM self . limit_pos ( p [ 0 ] , se_x , nw_x ) self . set_nearest_border ( ) | Updates the initial position of the port |
40,401 | def _solve ( self ) : self . update_distance_to_border ( ) px , py = self . _point nw_x , nw_y , se_x , se_y = self . get_adjusted_border_positions ( ) if ( ( self . _initial_pos . x == nw_x and self . _initial_pos . y == nw_y ) or ( self . _initial_pos . x == se_x and self . _initial_pos . y == nw_y ) or ( self . _initial_pos . x == se_x and self . _initial_pos . y == se_y ) or ( self . _initial_pos . x == nw_x and self . _initial_pos . y == se_y ) ) : self . limit_pos ( px , se_x , nw_x ) self . limit_pos ( py , se_y , nw_y ) elif self . _initial_pos . x == nw_x : _update ( px , nw_x ) self . limit_pos ( py , se_y , nw_y ) self . _port . side = SnappedSide . LEFT elif self . _initial_pos . y == nw_y : _update ( py , nw_y ) self . limit_pos ( px , se_x , nw_x ) self . _port . side = SnappedSide . TOP elif self . _initial_pos . x == se_x : _update ( px , se_x ) self . limit_pos ( py , se_y , nw_y ) self . _port . side = SnappedSide . RIGHT elif self . _initial_pos . y == se_y : _update ( py , se_y ) self . limit_pos ( px , se_x , nw_x ) self . _port . side = SnappedSide . BOTTOM else : self . set_nearest_border ( ) _update ( self . _initial_pos . x , deepcopy ( px . value ) ) _update ( self . _initial_pos . y , deepcopy ( py . value ) ) | Calculates the correct position of the port and keeps it aligned with the binding rect |
40,402 | def set_nearest_border ( self ) : px , py = self . _point nw_x , nw_y , se_x , se_y = self . get_adjusted_border_positions ( ) if self . _port . side == SnappedSide . RIGHT : _update ( px , se_x ) elif self . _port . side == SnappedSide . BOTTOM : _update ( py , se_y ) elif self . _port . side == SnappedSide . LEFT : _update ( px , nw_x ) elif self . _port . side == SnappedSide . TOP : _update ( py , nw_y ) | Snaps the port to the correct side upon state size change |
40,403 | def remove_obsolete_folders ( states , path ) : elements_in_folder = os . listdir ( path ) state_folders_in_file_system = [ ] for folder_name in elements_in_folder : if os . path . exists ( os . path . join ( path , folder_name , FILE_NAME_CORE_DATA ) ) or os . path . exists ( os . path . join ( path , folder_name , FILE_NAME_CORE_DATA_OLD ) ) : state_folders_in_file_system . append ( folder_name ) for state in states : storage_folder_for_state = get_storage_id_for_state ( state ) if storage_folder_for_state in state_folders_in_file_system : state_folders_in_file_system . remove ( storage_folder_for_state ) for folder_name in state_folders_in_file_system : shutil . rmtree ( os . path . join ( path , folder_name ) ) | Removes obsolete state machine folders |
40,404 | def save_state_machine_to_path ( state_machine , base_path , delete_old_state_machine = False , as_copy = False ) : clean_path_from_deprecated_naming ( base_path ) state_machine . acquire_modification_lock ( ) try : root_state = state_machine . root_state if delete_old_state_machine : if os . path . exists ( base_path ) : shutil . rmtree ( base_path ) if not os . path . exists ( base_path ) : os . makedirs ( base_path ) old_update_time = state_machine . last_update state_machine . last_update = storage_utils . get_current_time_string ( ) state_machine_dict = state_machine . to_dict ( ) storage_utils . write_dict_to_json ( state_machine_dict , os . path . join ( base_path , STATEMACHINE_FILE ) ) if not as_copy : state_machine . file_system_path = copy . copy ( base_path ) else : state_machine . last_update = old_update_time remove_obsolete_folders ( [ root_state ] , base_path ) save_state_recursively ( root_state , base_path , "" , as_copy ) if state_machine . marked_dirty and not as_copy : state_machine . marked_dirty = False logger . debug ( "State machine with id {0} was saved at {1}" . format ( state_machine . state_machine_id , base_path ) ) except Exception : raise finally : state_machine . release_modification_lock ( ) | Saves a state machine recursively to the file system |
40,405 | def save_script_file_for_state_and_source_path ( state , state_path_full , as_copy = False ) : from rafcon . core . states . execution_state import ExecutionState if isinstance ( state , ExecutionState ) : source_script_file = os . path . join ( state . script . path , state . script . filename ) destination_script_file = os . path . join ( state_path_full , SCRIPT_FILE ) try : write_file ( destination_script_file , state . script_text ) except Exception : logger . exception ( "Storing of script file failed: {0} -> {1}" . format ( state . get_path ( ) , destination_script_file ) ) raise if not source_script_file == destination_script_file and not as_copy : state . script . filename = SCRIPT_FILE state . script . path = state_path_full | Saves the script file for a state to the directory of the state . |
40,406 | def save_semantic_data_for_state ( state , state_path_full ) : destination_script_file = os . path . join ( state_path_full , SEMANTIC_DATA_FILE ) try : storage_utils . write_dict_to_json ( state . semantic_data , destination_script_file ) except IOError : logger . exception ( "Storing of semantic data for state {0} failed! Destination path: {1}" . format ( state . get_path ( ) , destination_script_file ) ) raise | Saves the semantic data in a separate json file . |
40,407 | def save_state_recursively ( state , base_path , parent_path , as_copy = False ) : from rafcon . core . states . execution_state import ExecutionState from rafcon . core . states . container_state import ContainerState state_path = os . path . join ( parent_path , get_storage_id_for_state ( state ) ) state_path_full = os . path . join ( base_path , state_path ) if not os . path . exists ( state_path_full ) : os . makedirs ( state_path_full ) storage_utils . write_dict_to_json ( state , os . path . join ( state_path_full , FILE_NAME_CORE_DATA ) ) if not as_copy : state . file_system_path = state_path_full if isinstance ( state , ExecutionState ) : save_script_file_for_state_and_source_path ( state , state_path_full , as_copy ) save_semantic_data_for_state ( state , state_path_full ) if isinstance ( state , ContainerState ) : remove_obsolete_folders ( state . states . values ( ) , os . path . join ( base_path , state_path ) ) for state in state . states . values ( ) : save_state_recursively ( state , base_path , state_path , as_copy ) | Recursively saves a state to a json file |
40,408 | def load_state_recursively ( parent , state_path = None , dirty_states = [ ] ) : from rafcon . core . states . execution_state import ExecutionState from rafcon . core . states . container_state import ContainerState from rafcon . core . states . hierarchy_state import HierarchyState path_core_data = os . path . join ( state_path , FILE_NAME_CORE_DATA ) logger . debug ( "Load state recursively: {0}" . format ( str ( state_path ) ) ) if not os . path . exists ( path_core_data ) : path_core_data = os . path . join ( state_path , FILE_NAME_CORE_DATA_OLD ) try : state_info = load_data_file ( path_core_data ) except ValueError as e : logger . exception ( "Error while loading state data: {0}" . format ( e ) ) return except LibraryNotFoundException as e : logger . error ( "Library could not be loaded: {0}\n" "Skipping library and continuing loading the state machine" . format ( e ) ) state_info = storage_utils . load_objects_from_json ( path_core_data , as_dict = True ) state_id = state_info [ "state_id" ] dummy_state = HierarchyState ( LIBRARY_NOT_FOUND_DUMMY_STATE_NAME , state_id = state_id ) if isinstance ( parent , ContainerState ) : parent . add_state ( dummy_state , storage_load = True ) else : dummy_state . parent = parent return dummy_state if not isinstance ( state_info , tuple ) : state = state_info else : state = state_info [ 0 ] transitions = state_info [ 1 ] data_flows = state_info [ 2 ] if parent is not None and isinstance ( parent , ContainerState ) : parent . add_state ( state , storage_load = True ) else : state . parent = parent if isinstance ( state , ExecutionState ) : script_text = read_file ( state_path , state . script . filename ) state . script_text = script_text try : semantic_data = load_data_file ( os . path . join ( state_path , SEMANTIC_DATA_FILE ) ) state . semantic_data = semantic_data except Exception as e : pass one_of_my_child_states_not_found = False for p in os . listdir ( state_path ) : child_state_path = os . path . join ( state_path , p ) if os . path . isdir ( child_state_path ) : child_state = load_state_recursively ( state , child_state_path , dirty_states ) if child_state . name is LIBRARY_NOT_FOUND_DUMMY_STATE_NAME : one_of_my_child_states_not_found = True if one_of_my_child_states_not_found : pass else : if isinstance ( state_info , tuple ) : state . transitions = transitions state . data_flows = data_flows state . file_system_path = state_path if state . marked_dirty : dirty_states . append ( state ) return state | Recursively loads the state |
40,409 | def load_data_file ( path_of_file ) : if os . path . exists ( path_of_file ) : return storage_utils . load_objects_from_json ( path_of_file ) raise ValueError ( "Data file not found: {0}" . format ( path_of_file ) ) | Loads the content of a file by using json . load . |
40,410 | def clean_path_element ( text , max_length = None , separator = '_' ) : elements_to_replace = REPLACED_CHARACTERS_FOR_NO_OS_LIMITATION for elem , replace_with in elements_to_replace . items ( ) : text = text . replace ( elem , replace_with ) if max_length is not None : text = limit_text_max_length ( text , max_length , separator ) return text | Replace characters that conflict with a free OS choice when in a file system path . |
40,411 | def limit_text_to_be_path_element ( text , max_length = None , separator = '_' ) : elements_to_replace = { ' ' : '_' , '*' : '_' } for elem , replace_with in elements_to_replace . items ( ) : text = text . replace ( elem , replace_with ) text = re . sub ( '[^a-zA-Z0-9-_]' , '' , text ) if max_length is not None : text = limit_text_max_length ( text , max_length , separator ) return text | Replace characters that are not in the valid character set of RAFCON . |
40,412 | def get_storage_id_for_state ( state ) : if global_config . get_config_value ( 'STORAGE_PATH_WITH_STATE_NAME' ) : max_length = global_config . get_config_value ( 'MAX_LENGTH_FOR_STATE_NAME_IN_STORAGE_PATH' ) max_length_of_state_name_in_folder_name = 255 - len ( ID_NAME_DELIMITER + state . state_id ) if max_length is None or max_length == "None" or max_length > max_length_of_state_name_in_folder_name : if max_length_of_state_name_in_folder_name < len ( state . name ) : logger . info ( "The storage folder name is forced to be maximal 255 characters in length." ) max_length = max_length_of_state_name_in_folder_name return limit_text_to_be_path_element ( state . name , max_length ) + ID_NAME_DELIMITER + state . state_id else : return state . state_id | Calculates the storage id of a state . This ID can be used for generating the file path for a state . |
40,413 | def pane_position_check ( self ) : text_buffer = self . get_buffer ( ) from rafcon . gui . singleton import main_window_controller if main_window_controller is None or main_window_controller . view is None : return from rafcon . gui . runtime_config import global_runtime_config if global_runtime_config . get_config_value ( 'RIGHT_BAR_WINDOW_UNDOCKED' ) : return button_container_min_width = self . button_container_min_width width_of_all = button_container_min_width + self . tab_width text_view_width = button_container_min_width - self . line_numbers_width min_line_string_length = float ( button_container_min_width ) / float ( self . source_view_character_size ) current_pane_pos = main_window_controller . view [ 'right_h_pane' ] . get_property ( 'position' ) max_position = main_window_controller . view [ 'right_h_pane' ] . get_property ( 'max_position' ) pane_rel_pos = main_window_controller . view [ 'right_h_pane' ] . get_property ( 'max_position' ) - current_pane_pos if pane_rel_pos >= width_of_all + self . line_numbers_width : pass else : cursor_line_offset = text_buffer . get_iter_at_offset ( text_buffer . props . cursor_position ) . get_line_offset ( ) needed_rel_pos = text_view_width / min_line_string_length * cursor_line_offset + self . tab_width + self . line_numbers_width needed_rel_pos = min ( width_of_all , needed_rel_pos ) if pane_rel_pos >= needed_rel_pos : pass else : main_window_controller . view [ 'right_h_pane' ] . set_property ( 'position' , max_position - needed_rel_pos ) spacer_width = int ( width_of_all + self . line_numbers_width - needed_rel_pos ) self . spacer_frame . set_size_request ( width = spacer_width , height = - 1 ) | Update right bar pane position if needed |
40,414 | def push_call_history_item ( self , state , call_type , state_for_scoped_data , input_data = None ) : last_history_item = self . get_last_history_item ( ) from rafcon . core . states . library_state import LibraryState if isinstance ( state_for_scoped_data , LibraryState ) : state_for_scoped_data = state_for_scoped_data . state_copy return_item = CallItem ( state , last_history_item , call_type , state_for_scoped_data , input_data , state . run_id ) return self . _push_item ( last_history_item , return_item ) | Adds a new call - history - item to the history item list |
40,415 | def push_return_history_item ( self , state , call_type , state_for_scoped_data , output_data = None ) : last_history_item = self . get_last_history_item ( ) from rafcon . core . states . library_state import LibraryState if isinstance ( state_for_scoped_data , LibraryState ) : state_for_scoped_data = state_for_scoped_data . state_copy return_item = ReturnItem ( state , last_history_item , call_type , state_for_scoped_data , output_data , state . run_id ) return self . _push_item ( last_history_item , return_item ) | Adds a new return - history - item to the history item list |
40,416 | def push_concurrency_history_item ( self , state , number_concurrent_threads ) : last_history_item = self . get_last_history_item ( ) return_item = ConcurrencyItem ( state , self . get_last_history_item ( ) , number_concurrent_threads , state . run_id , self . execution_history_storage ) return self . _push_item ( last_history_item , return_item ) | Adds a new concurrency - history - item to the history item list |
40,417 | def update_hash_from_dict ( obj_hash , object_ ) : if isinstance ( object_ , Hashable ) : object_ . update_hash ( obj_hash ) elif isinstance ( object_ , ( list , set , tuple ) ) : if isinstance ( object_ , set ) : object_ = sorted ( object_ ) for element in object_ : Hashable . update_hash_from_dict ( obj_hash , element ) elif isinstance ( object_ , dict ) : for key in sorted ( object_ . keys ( ) ) : Hashable . update_hash_from_dict ( obj_hash , key ) Hashable . update_hash_from_dict ( obj_hash , object_ [ key ] ) else : obj_hash . update ( Hashable . get_object_hash_string ( object_ ) ) | Updates an existing hash object with another Hashable list set tuple dict or stringifyable object |
40,418 | def emit ( self , record ) : try : if sys . version_info >= ( 2 , 7 ) : record . __setattr__ ( "name" , record . name . replace ( "rafcon." , "" ) ) msg = self . format ( record ) fs = "%s" try : ufs = u'%s' try : entry = ufs % msg except UnicodeEncodeError : entry = fs % msg except UnicodeError : entry = fs % msg for logging_view in self . _logging_views . values ( ) : logging_view . print_message ( entry , record . levelno ) except ( KeyboardInterrupt , SystemExit ) : raise except : self . handleError ( record ) | Logs a new record |
40,419 | def get_meta_data_editor ( self , for_gaphas = True ) : meta_gaphas = self . meta [ 'gui' ] [ 'editor_gaphas' ] meta_opengl = self . meta [ 'gui' ] [ 'editor_opengl' ] assert isinstance ( meta_gaphas , Vividict ) and isinstance ( meta_opengl , Vividict ) parental_conversion_from_opengl = self . _parent and self . _parent ( ) . temp [ 'conversion_from_opengl' ] from_gaphas = len ( meta_gaphas ) > len ( meta_opengl ) or ( len ( meta_gaphas ) == len ( meta_opengl ) and for_gaphas and not parental_conversion_from_opengl ) if from_gaphas and not for_gaphas : self . meta [ 'gui' ] [ 'editor_opengl' ] = self . _meta_data_editor_gaphas2opengl ( meta_gaphas ) elif not from_gaphas and for_gaphas : self . meta [ 'gui' ] [ 'editor_gaphas' ] = self . _meta_data_editor_opengl2gaphas ( meta_opengl ) del self . meta [ 'gui' ] [ 'editor_opengl' if for_gaphas else 'editor_gaphas' ] return self . meta [ 'gui' ] [ 'editor_gaphas' ] if for_gaphas else self . meta [ 'gui' ] [ 'editor_opengl' ] | Returns the editor for the specified editor |
40,420 | def set_meta_data_editor ( self , key , meta_data , from_gaphas = True ) : self . do_convert_meta_data_if_no_data ( from_gaphas ) meta_gui = self . meta [ 'gui' ] meta_gui = meta_gui [ 'editor_gaphas' ] if from_gaphas else meta_gui [ 'editor_opengl' ] key_path = key . split ( '.' ) for key in key_path : if isinstance ( meta_gui , list ) : meta_gui [ int ( key ) ] = meta_data break if key == key_path [ - 1 ] : meta_gui [ key ] = meta_data else : meta_gui = meta_gui [ key ] return self . get_meta_data_editor ( for_gaphas = from_gaphas ) | Sets the meta data for a specific key of the desired editor |
40,421 | def meta_data_hash ( self , obj_hash = None ) : if obj_hash is None : obj_hash = hashlib . sha256 ( ) self . update_meta_data_hash ( obj_hash ) return obj_hash | Creates a hash with the meta data of the model |
40,422 | def limit_value_string_length ( value ) : if isinstance ( value , string_types ) and len ( value ) > constants . MAX_VALUE_LABEL_TEXT_LENGTH : value = value [ : constants . MAX_VALUE_LABEL_TEXT_LENGTH ] + "..." final_string = " " + value + " " elif isinstance ( value , ( dict , list ) ) and len ( str ( value ) ) > constants . MAX_VALUE_LABEL_TEXT_LENGTH : value_text = str ( value ) [ : constants . MAX_VALUE_LABEL_TEXT_LENGTH ] + "..." final_string = " " + value_text + " " else : final_string = " " + str ( value ) + " " return final_string | This method limits the string representation of the value to MAX_VALUE_LABEL_TEXT_LENGTH + 3 characters . |
40,423 | def get_col_rgba ( color , transparency = None , opacity = None ) : r , g , b = color . red , color . green , color . blue r /= 65535. g /= 65535. b /= 65535. if transparency is not None or opacity is None : transparency = 0 if transparency is None else transparency if transparency < 0 or transparency > 1 : raise ValueError ( "Transparency must be between 0 and 1" ) alpha = 1 - transparency else : if opacity < 0 or opacity > 1 : raise ValueError ( "Opacity must be between 0 and 1" ) alpha = opacity return r , g , b , alpha | This class converts a Gdk . Color into its r g b parts and adds an alpha according to needs |
40,424 | def get_side_length_of_resize_handle ( view , item ) : from rafcon . gui . mygaphas . items . state import StateView , NameView if isinstance ( item , StateView ) : return item . border_width * view . get_zoom_factor ( ) / 1.5 elif isinstance ( item , NameView ) : return item . parent . border_width * view . get_zoom_factor ( ) / 2.5 return 0 | Calculate the side length of a resize handle |
40,425 | def draw_data_value_rect ( cairo_context , color , value_size , name_size , pos , port_side ) : c = cairo_context rot_angle = .0 move_x = 0. move_y = 0. if port_side is SnappedSide . RIGHT : move_x = pos [ 0 ] + name_size [ 0 ] move_y = pos [ 1 ] c . rectangle ( move_x , move_y , value_size [ 0 ] , value_size [ 1 ] ) elif port_side is SnappedSide . BOTTOM : move_x = pos [ 0 ] - value_size [ 1 ] move_y = pos [ 1 ] + name_size [ 0 ] rot_angle = pi / 2. c . rectangle ( move_x , move_y , value_size [ 1 ] , value_size [ 0 ] ) elif port_side is SnappedSide . LEFT : move_x = pos [ 0 ] - value_size [ 0 ] move_y = pos [ 1 ] c . rectangle ( move_x , move_y , value_size [ 0 ] , value_size [ 1 ] ) elif port_side is SnappedSide . TOP : move_x = pos [ 0 ] - value_size [ 1 ] move_y = pos [ 1 ] - value_size [ 0 ] rot_angle = - pi / 2. c . rectangle ( move_x , move_y , value_size [ 1 ] , value_size [ 0 ] ) c . set_source_rgba ( * color ) c . fill_preserve ( ) c . set_source_rgb ( * gui_config . gtk_colors [ 'BLACK' ] . to_floats ( ) ) c . stroke ( ) return rot_angle , move_x , move_y | This method draws the containing rect for the data port value depending on the side and size of the label . |
40,426 | def draw_label_path ( context , width , height , arrow_height , distance_to_port , port_offset ) : c = context c . rel_move_to ( 0 , port_offset ) c . rel_line_to ( 0 , distance_to_port ) c . rel_line_to ( - width / 2. , arrow_height ) c . rel_line_to ( 0 , height - arrow_height ) c . rel_line_to ( width , 0 ) c . rel_line_to ( 0 , - ( height - arrow_height ) ) c . rel_line_to ( - width / 2. , - arrow_height ) c . close_path ( ) | Draws the path for an upright label |
40,427 | def _load_income_model ( self ) : if not self . state_copy_initialized : return self . income = None income_m = deepcopy ( self . state_copy . income ) income_m . parent = self income_m . income = income_m . income self . income = income_m | Reloads the income model directly from the state |
40,428 | def _load_outcome_models ( self ) : if not self . state_copy_initialized : return self . outcomes = [ ] for outcome_m in self . state_copy . outcomes : new_oc_m = deepcopy ( outcome_m ) new_oc_m . parent = self new_oc_m . outcome = outcome_m . outcome self . outcomes . append ( new_oc_m ) | Reloads the outcome models directly from the state |
40,429 | def model_changed ( self , model , prop_name , info ) : if self . parent is not None : self . parent . model_changed ( model , prop_name , info ) | This method notifies the parent state about changes made to the state element |
40,430 | def disable ( self ) : self . ticker_text_label . hide ( ) if self . current_observed_sm_m : self . stop_sm_m_observation ( self . current_observed_sm_m ) | Relieve all state machines that have no active execution and hide the widget |
40,431 | def on_state_execution_status_changed_after ( self , model , prop_name , info ) : from rafcon . gui . utils . notification_overview import NotificationOverview from rafcon . core . states . state import State def name_and_next_state ( state ) : assert isinstance ( state , State ) if state . is_root_state_of_library : return state . parent . parent , state . parent . name else : return state . parent , state . name def create_path ( state , n = 3 , separator = '/' ) : next_parent , name = name_and_next_state ( state ) path = separator + name n -= 1 while n > 0 and isinstance ( next_parent , State ) : next_parent , name = name_and_next_state ( next_parent ) path = separator + name + path n -= 1 if isinstance ( next_parent , State ) : path = separator + '..' + path return path if 'kwargs' in info and 'method_name' in info [ 'kwargs' ] : overview = NotificationOverview ( info ) if overview [ 'method_name' ] [ - 1 ] == 'state_execution_status' : active_state = overview [ 'model' ] [ - 1 ] . state assert isinstance ( active_state , State ) path_depth = rafcon . gui . singleton . global_gui_config . get_config_value ( "EXECUTION_TICKER_PATH_DEPTH" , 3 ) message = self . _fix_text_of_label + create_path ( active_state , path_depth ) if rafcon . gui . singleton . main_window_controller . view is not None : self . ticker_text_label . set_text ( message ) else : logger . warn ( "Not initialized yet" ) | Show current execution status in the widget |
40,432 | def execution_engine_model_changed ( self , model , prop_name , info ) : if not self . _view_initialized : return active_sm_id = rafcon . gui . singleton . state_machine_manager_model . state_machine_manager . active_state_machine_id if active_sm_id is None : self . disable ( ) else : self . check_configuration ( ) | Active observation of state machine and show and hide widget . |
40,433 | def register_observer ( self ) : self . execution_engine . add_observer ( self , "start" , notify_before_function = self . on_start ) self . execution_engine . add_observer ( self , "pause" , notify_before_function = self . on_pause ) self . execution_engine . add_observer ( self , "stop" , notify_before_function = self . on_stop ) | Register all observable which are of interest |
40,434 | def rotate_and_detach_tab_labels ( self ) : icons = { 'Libraries' : constants . SIGN_LIB , 'States Tree' : constants . ICON_TREE , 'Global Variables' : constants . ICON_GLOB , 'Modification History' : constants . ICON_HIST , 'Execution History' : constants . ICON_EHIST , 'network' : constants . ICON_NET } for notebook in self . left_bar_notebooks : for i in range ( notebook . get_n_pages ( ) ) : child = notebook . get_nth_page ( i ) tab_label = notebook . get_tab_label ( child ) tab_label_text = tab_label . get_text ( ) notebook . set_tab_label ( child , gui_helper_label . create_tab_header_label ( tab_label_text , icons ) ) notebook . set_tab_reorderable ( child , True ) notebook . set_tab_detachable ( child , True ) | Rotates tab labels of a given notebook by 90 degrees and makes them detachable . |
40,435 | def bring_tab_to_the_top ( self , tab_label ) : found = False for notebook in self . left_bar_notebooks : for i in range ( notebook . get_n_pages ( ) ) : if gui_helper_label . get_notebook_tab_title ( notebook , i ) == gui_helper_label . get_widget_title ( tab_label ) : found = True break if found : notebook . set_current_page ( i ) break | Find tab with label tab_label in list of notebooks and set it to the current page . |
40,436 | def add_transitions_from_selected_state_to_parent ( ) : task_string = "create transition" sub_task_string = "to parent state" selected_state_m , msg = get_selected_single_state_model_and_check_for_its_parent ( ) if selected_state_m is None : logger . warning ( "Can not {0} {1}: {2}" . format ( task_string , sub_task_string , msg ) ) return logger . debug ( "Check to {0} {1} ..." . format ( task_string , sub_task_string ) ) state = selected_state_m . state parent_state = state . parent from_outcomes = get_all_outcomes_except_of_abort_and_preempt ( state ) possible_oc_ids = [ oc_id for oc_id in state . parent . outcomes . keys ( ) if oc_id >= 0 ] possible_oc_ids . sort ( ) to_outcome = state . parent . outcomes [ possible_oc_ids [ 0 ] ] oc_connected_to_parent = [ oc for oc in from_outcomes if is_outcome_connect_to_state ( oc , parent_state . state_id ) ] oc_not_connected = [ oc for oc in from_outcomes if not state . parent . get_transition_for_outcome ( state , oc ) ] if all ( oc in oc_connected_to_parent for oc in from_outcomes ) : logger . info ( "Remove transition {0} because all outcomes are connected to it." . format ( sub_task_string ) ) for from_outcome in oc_connected_to_parent : transition = parent_state . get_transition_for_outcome ( state , from_outcome ) parent_state . remove ( transition ) elif oc_not_connected : logger . debug ( "Create transition {0} ... " . format ( sub_task_string ) ) for from_outcome in from_outcomes : parent_state . add_transition ( state . state_id , from_outcome . outcome_id , parent_state . state_id , to_outcome . outcome_id ) else : if remove_transitions_if_target_is_the_same ( from_outcomes ) : logger . info ( "Removed transitions origin from outcomes of selected state {0}" "because all point to the same target." . format ( sub_task_string ) ) return add_transitions_from_selected_state_to_parent ( ) logger . info ( "Will not create transition {0}: Not clear situation of connected transitions." "There will be no transitions to other states be touched." . format ( sub_task_string ) ) return True | Generates the default success transition of a state to its parent success port |
40,437 | def add_transitions_to_closest_sibling_state_from_selected_state ( ) : task_string = "create transition" sub_task_string = "to closest sibling state" selected_state_m , msg = get_selected_single_state_model_and_check_for_its_parent ( ) if selected_state_m is None : logger . warning ( "Can not {0} {1}: {2}" . format ( task_string , sub_task_string , msg ) ) return logger . debug ( "Check to {0} {1} ..." . format ( task_string , sub_task_string ) ) state = selected_state_m . state parent_state = state . parent closest_sibling_state_tuple = gui_helper_meta_data . get_closest_sibling_state ( selected_state_m , 'outcome' ) if closest_sibling_state_tuple is None : logger . info ( "Can not {0} {1}: There is no other sibling state." . format ( task_string , sub_task_string ) ) return distance , sibling_state_m = closest_sibling_state_tuple to_state = sibling_state_m . state from_outcomes = get_all_outcomes_except_of_abort_and_preempt ( state ) from_oc_not_connected = [ oc for oc in from_outcomes if not state . parent . get_transition_for_outcome ( state , oc ) ] if from_oc_not_connected : logger . debug ( "Create transition {0} ..." . format ( sub_task_string ) ) for from_outcome in from_oc_not_connected : parent_state . add_transition ( state . state_id , from_outcome . outcome_id , to_state . state_id , None ) else : target = remove_transitions_if_target_is_the_same ( from_outcomes ) if target : target_state_id , _ = target if not target_state_id == to_state . state_id : logger . info ( "Removed transitions from outcomes {0} " "because all point to the same target." . format ( sub_task_string . replace ( 'closest ' , '' ) ) ) add_transitions_to_closest_sibling_state_from_selected_state ( ) else : logger . info ( "Removed transitions from outcomes {0} " "because all point to the same target." . format ( sub_task_string ) ) return True logger . info ( "Will not {0} {1}: Not clear situation of connected transitions." "There will be no transitions to other states be touched." . format ( task_string , sub_task_string ) ) return True | Generates the outcome transitions from outcomes with positive outcome_id to the closest next state |
40,438 | def add_coordinates ( network ) : for idx , row in network . buses . iterrows ( ) : wkt_geom = to_shape ( row [ 'geom' ] ) network . buses . loc [ idx , 'x' ] = wkt_geom . x network . buses . loc [ idx , 'y' ] = wkt_geom . y return network | Add coordinates to nodes based on provided geom |
40,439 | def plot_residual_load ( network ) : renewables = network . generators [ network . generators . carrier . isin ( [ 'wind_onshore' , 'wind_offshore' , 'solar' , 'run_of_river' , 'wind' ] ) ] renewables_t = network . generators . p_nom [ renewables . index ] * network . generators_t . p_max_pu [ renewables . index ] . mul ( network . snapshot_weightings , axis = 0 ) load = network . loads_t . p_set . mul ( network . snapshot_weightings , axis = 0 ) . sum ( axis = 1 ) all_renew = renewables_t . sum ( axis = 1 ) residual_load = load - all_renew plot = residual_load . plot ( title = 'Residual load' , drawstyle = 'steps' , lw = 2 , color = 'red' , legend = False ) plot . set_ylabel ( "MW" ) sorted_residual_load = residual_load . sort_values ( ascending = False ) . reset_index ( ) plot1 = sorted_residual_load . plot ( title = 'Sorted residual load' , drawstyle = 'steps' , lw = 2 , color = 'red' , legend = False ) plot1 . set_ylabel ( "MW" ) | Plots residual load summed of all exisiting buses . |
40,440 | def plot_stacked_gen ( network , bus = None , resolution = 'GW' , filename = None ) : if resolution == 'GW' : reso_int = 1e3 elif resolution == 'MW' : reso_int = 1 elif resolution == 'KW' : reso_int = 0.001 if bus is None : p_by_carrier = pd . concat ( [ network . generators_t . p [ network . generators [ network . generators . control != 'Slack' ] . index ] , network . generators_t . p . mul ( network . snapshot_weightings , axis = 0 ) [ network . generators [ network . generators . control == 'Slack' ] . index ] . iloc [ : , 0 ] . apply ( lambda x : x if x > 0 else 0 ) ] , axis = 1 ) . groupby ( network . generators . carrier , axis = 1 ) . sum ( ) load = network . loads_t . p . sum ( axis = 1 ) if hasattr ( network , 'foreign_trade' ) : trade_sum = network . foreign_trade . sum ( axis = 1 ) p_by_carrier [ 'imports' ] = trade_sum [ trade_sum > 0 ] p_by_carrier [ 'imports' ] = p_by_carrier [ 'imports' ] . fillna ( 0 ) elif bus is not None : filtered_gens = network . generators [ network . generators [ 'bus' ] == bus ] p_by_carrier = network . generators_t . p . mul ( network . snapshot_weightings , axis = 0 ) . groupby ( filtered_gens . carrier , axis = 1 ) . abs ( ) . sum ( ) filtered_load = network . loads [ network . loads [ 'bus' ] == bus ] load = network . loads_t . p . mul ( network . snapshot_weightings , axis = 0 ) [ filtered_load . index ] colors = coloring ( ) fig , ax = plt . subplots ( 1 , 1 ) fig . set_size_inches ( 12 , 6 ) colors = [ colors [ col ] for col in p_by_carrier . columns ] if len ( colors ) == 1 : colors = colors [ 0 ] ( p_by_carrier / reso_int ) . plot ( kind = "area" , ax = ax , linewidth = 0 , color = colors ) ( load / reso_int ) . plot ( ax = ax , legend = 'load' , lw = 2 , color = 'darkgrey' , style = '--' ) ax . legend ( ncol = 4 , loc = "upper left" ) ax . set_ylabel ( resolution ) ax . set_xlabel ( "" ) matplotlib . rcParams . update ( { 'font.size' : 22 } ) if filename is None : plt . show ( ) else : plt . savefig ( filename ) plt . close ( ) | Plot stacked sum of generation grouped by carrier type |
40,441 | def plot_gen_diff ( networkA , networkB , leave_out_carriers = [ 'geothermal' , 'oil' , 'other_non_renewable' , 'reservoir' , 'waste' ] ) : def gen_by_c ( network ) : gen = pd . concat ( [ network . generators_t . p . mul ( network . snapshot_weightings , axis = 0 ) [ network . generators [ network . generators . control != 'Slack' ] . index ] , network . generators_t . p . mul ( network . snapshot_weightings , axis = 0 ) [ network . generators [ network . generators . control == 'Slack' ] . index ] . iloc [ : , 0 ] . apply ( lambda x : x if x > 0 else 0 ) ] , axis = 1 ) . groupby ( network . generators . carrier , axis = 1 ) . sum ( ) return gen gen = gen_by_c ( networkB ) gen_switches = gen_by_c ( networkA ) diff = gen_switches - gen colors = coloring ( ) diff . drop ( leave_out_carriers , axis = 1 , inplace = True ) colors = [ colors [ col ] for col in diff . columns ] plot = diff . plot ( kind = 'line' , color = colors , use_index = False ) plot . legend ( loc = 'upper left' , ncol = 5 , prop = { 'size' : 8 } ) x = [ ] for i in range ( 0 , len ( diff ) ) : x . append ( i ) plt . xticks ( x , x ) plot . set_xlabel ( 'Timesteps' ) plot . set_ylabel ( 'Difference in Generation in MW' ) plot . set_title ( 'Difference in Generation' ) plt . tight_layout ( ) | Plot difference in generation between two networks grouped by carrier type |
40,442 | def plot_voltage ( network , boundaries = [ ] ) : x = np . array ( network . buses [ 'x' ] ) y = np . array ( network . buses [ 'y' ] ) alpha = np . array ( network . buses_t . v_mag_pu . loc [ network . snapshots [ 0 ] ] ) fig , ax = plt . subplots ( 1 , 1 ) fig . set_size_inches ( 6 , 4 ) cmap = plt . cm . jet if not boundaries : plt . hexbin ( x , y , C = alpha , cmap = cmap , gridsize = 100 ) cb = plt . colorbar ( ) elif boundaries : v = np . linspace ( boundaries [ 0 ] , boundaries [ 1 ] , 101 ) norm = matplotlib . colors . BoundaryNorm ( v , cmap . N ) plt . hexbin ( x , y , C = alpha , cmap = cmap , gridsize = 100 , norm = norm ) cb = plt . colorbar ( boundaries = v , ticks = v [ 0 : 101 : 10 ] , norm = norm ) cb . set_clim ( vmin = boundaries [ 0 ] , vmax = boundaries [ 1 ] ) cb . set_label ( 'Voltage Magnitude per unit of v_nom' ) network . plot ( ax = ax , line_widths = pd . Series ( 0.5 , network . lines . index ) , bus_sizes = 0 ) plt . show ( ) | Plot voltage at buses as hexbin |
40,443 | def curtailment ( network , carrier = 'solar' , filename = None ) : p_by_carrier = network . generators_t . p . groupby ( network . generators . carrier , axis = 1 ) . sum ( ) capacity = network . generators . groupby ( "carrier" ) . sum ( ) . at [ carrier , "p_nom" ] p_available = network . generators_t . p_max_pu . multiply ( network . generators [ "p_nom" ] ) p_available_by_carrier = p_available . groupby ( network . generators . carrier , axis = 1 ) . sum ( ) p_curtailed_by_carrier = p_available_by_carrier - p_by_carrier print ( p_curtailed_by_carrier . sum ( ) ) p_df = pd . DataFrame ( { carrier + " available" : p_available_by_carrier [ carrier ] , carrier + " dispatched" : p_by_carrier [ carrier ] , carrier + " curtailed" : p_curtailed_by_carrier [ carrier ] } ) p_df [ carrier + " capacity" ] = capacity p_df [ carrier + " curtailed" ] [ p_df [ carrier + " curtailed" ] < 0. ] = 0. fig , ax = plt . subplots ( 1 , 1 ) fig . set_size_inches ( 12 , 6 ) p_df [ [ carrier + " dispatched" , carrier + " curtailed" ] ] . plot ( kind = "area" , ax = ax , linewidth = 3 ) p_df [ [ carrier + " available" , carrier + " capacity" ] ] . plot ( ax = ax , linewidth = 3 ) ax . set_xlabel ( "" ) ax . set_ylabel ( "Power [MW]" ) ax . set_ylim ( [ 0 , capacity * 1.1 ] ) ax . legend ( ) if filename is None : plt . show ( ) else : plt . savefig ( filename ) plt . close ( ) | Plot curtailment of selected carrier |
40,444 | def storage_distribution ( network , scaling = 1 , filename = None ) : stores = network . storage_units storage_distribution = network . storage_units . p_nom_opt [ stores . index ] . groupby ( network . storage_units . bus ) . sum ( ) . reindex ( network . buses . index , fill_value = 0. ) fig , ax = plt . subplots ( 1 , 1 ) fig . set_size_inches ( 6 , 6 ) msd_max = storage_distribution . max ( ) msd_median = storage_distribution [ storage_distribution != 0 ] . median ( ) msd_min = storage_distribution [ storage_distribution > 1 ] . min ( ) if msd_max != 0 : LabelVal = int ( log10 ( msd_max ) ) else : LabelVal = 0 if LabelVal < 0 : LabelUnit = 'kW' msd_max , msd_median , msd_min = msd_max * 1000 , msd_median * 1000 , msd_min * 1000 storage_distribution = storage_distribution * 1000 elif LabelVal < 3 : LabelUnit = 'MW' else : LabelUnit = 'GW' msd_max , msd_median , msd_min = msd_max / 1000 , msd_median / 1000 , msd_min / 1000 storage_distribution = storage_distribution / 1000 if sum ( storage_distribution ) == 0 : network . plot ( bus_sizes = 0 , ax = ax , title = "No storages" ) else : network . plot ( bus_sizes = storage_distribution * scaling , ax = ax , line_widths = 0.3 , title = "Storage distribution" ) for area in [ msd_max , msd_median , msd_min ] : plt . scatter ( [ ] , [ ] , c = 'white' , s = area * scaling , label = '= ' + str ( round ( area , 0 ) ) + LabelUnit + ' ' ) plt . legend ( scatterpoints = 1 , labelspacing = 1 , title = 'Storage size' ) if filename is None : plt . show ( ) else : plt . savefig ( filename ) plt . close ( ) | Plot storage distribution as circles on grid nodes |
40,445 | def undo ( self , key_value , modifier_mask ) : for key , tab in gui_singletons . main_window_controller . get_controller ( 'states_editor_ctrl' ) . tabs . items ( ) : if tab [ 'controller' ] . get_controller ( 'source_ctrl' ) is not None and react_to_event ( self . view , tab [ 'controller' ] . get_controller ( 'source_ctrl' ) . view . textview , ( key_value , modifier_mask ) ) or tab [ 'controller' ] . get_controller ( 'description_ctrl' ) is not None and react_to_event ( self . view , tab [ 'controller' ] . get_controller ( 'description_ctrl' ) . view . textview , ( key_value , modifier_mask ) ) : return False if self . _selected_sm_model is not None : self . _selected_sm_model . history . undo ( ) return True else : logger . debug ( "Undo is not possible now as long as no state_machine is selected." ) | Undo for selected state - machine if no state - source - editor is open and focused in states - editor - controller . |
40,446 | def exception_message ( self ) -> Union [ str , None ] : if self . has_error : exception_data = self . _raw . get ( "exception" , { } ) return exception_data . get ( "message" ) return None | On Lavalink V3 if there was an exception during a load or get tracks call this property will be populated with the error message . If there was no error this property will be None . |
40,447 | async def load_tracks ( self , query ) -> LoadResult : self . __check_node_ready ( ) url = self . _uri + quote ( str ( query ) ) data = await self . _get ( url ) if isinstance ( data , dict ) : return LoadResult ( data ) elif isinstance ( data , list ) : modified_data = { "loadType" : LoadType . V2_COMPAT , "tracks" : data } return LoadResult ( modified_data ) | Executes a loadtracks request . Only works on Lavalink V3 . |
40,448 | async def get_tracks ( self , query ) -> Tuple [ Track , ... ] : if not self . _warned : log . warn ( "get_tracks() is now deprecated. Please switch to using load_tracks()." ) self . _warned = True result = await self . load_tracks ( query ) return result . tracks | Gets tracks from lavalink . |
40,449 | def get_data_files_tuple ( * rel_path , ** kwargs ) : rel_path = os . path . join ( * rel_path ) target_path = os . path . join ( "share" , * rel_path . split ( os . sep ) [ 1 : ] ) if "path_to_file" in kwargs and kwargs [ "path_to_file" ] : source_files = [ rel_path ] target_path = os . path . dirname ( target_path ) else : source_files = [ os . path . join ( rel_path , filename ) for filename in os . listdir ( rel_path ) ] return target_path , source_files | Return a tuple which can be used for setup . py s data_files |
40,450 | def get_data_files_recursively ( * rel_root_path , ** kwargs ) : result_list = list ( ) rel_root_dir = os . path . join ( * rel_root_path ) share_target_root = os . path . join ( "share" , kwargs . get ( "share_target_root" , "rafcon" ) ) distutils . log . debug ( "recursively generating data files for folder '{}' ..." . format ( rel_root_dir ) ) for dir_ , _ , files in os . walk ( rel_root_dir ) : relative_directory = os . path . relpath ( dir_ , rel_root_dir ) file_list = list ( ) for fileName in files : rel_file_path = os . path . join ( relative_directory , fileName ) abs_file_path = os . path . join ( rel_root_dir , rel_file_path ) file_list . append ( abs_file_path ) if len ( file_list ) > 0 : target_path = os . path . join ( share_target_root , relative_directory ) result_list . append ( ( target_path , file_list ) ) return result_list | Adds all files of the specified path to a data_files compatible list |
40,451 | def generate_data_files ( ) : assets_folder = path . join ( 'source' , 'rafcon' , 'gui' , 'assets' ) share_folder = path . join ( assets_folder , 'share' ) themes_folder = path . join ( share_folder , 'themes' , 'RAFCON' ) examples_folder = path . join ( 'share' , 'examples' ) libraries_folder = path . join ( 'share' , 'libraries' ) gui_data_files = [ get_data_files_tuple ( assets_folder , 'splashscreens' ) , get_data_files_tuple ( assets_folder , 'fonts' , 'FontAwesome' ) , get_data_files_tuple ( assets_folder , 'fonts' , 'Source Sans Pro' ) , get_data_files_tuple ( themes_folder , 'gtk-3.0' , 'gtk.css' , path_to_file = True ) , get_data_files_tuple ( themes_folder , 'gtk-3.0' , 'gtk-dark.css' , path_to_file = True ) , get_data_files_tuple ( themes_folder , 'assets' ) , get_data_files_tuple ( themes_folder , 'sass' ) , get_data_files_tuple ( themes_folder , 'gtk-sourceview' ) , get_data_files_tuple ( themes_folder , 'colors.json' , path_to_file = True ) , get_data_files_tuple ( themes_folder , 'colors-dark.json' , path_to_file = True ) ] icon_data_files = get_data_files_recursively ( path . join ( share_folder , 'icons' ) , share_target_root = "icons" ) locale_data_files = create_mo_files ( ) version_data_file = [ ( "./" , [ "VERSION" ] ) ] desktop_data_file = [ ( "share/applications" , [ path . join ( 'share' , 'applications' , 'de.dlr.rm.RAFCON.desktop' ) ] ) ] examples_data_files = get_data_files_recursively ( examples_folder , share_target_root = path . join ( "rafcon" , "examples" ) ) libraries_data_files = get_data_files_recursively ( libraries_folder , share_target_root = path . join ( "rafcon" , "libraries" ) ) generated_data_files = gui_data_files + icon_data_files + locale_data_files + version_data_file + desktop_data_file + examples_data_files + libraries_data_files return generated_data_files | Generate the data_files list used in the setup function |
40,452 | def handle ( self , event ) : suppressed_grabbed_tool = None if event . type in ( Gdk . EventType . SCROLL , Gdk . EventType . KEY_PRESS , Gdk . EventType . KEY_RELEASE ) : suppressed_grabbed_tool = self . _grabbed_tool self . _grabbed_tool = None rt = super ( ToolChain , self ) . handle ( event ) if suppressed_grabbed_tool : self . _grabbed_tool = suppressed_grabbed_tool return rt | Handle the event by calling each tool until the event is handled or grabbed . If a tool is returning True on a button press event the motion and button release events are also passed to this |
40,453 | def on_button_release ( self , event ) : affected_models = { } for inmotion in self . _movable_items : inmotion . move ( ( event . x , event . y ) ) rel_pos = gap_helper . calc_rel_pos_to_parent ( self . view . canvas , inmotion . item , inmotion . item . handles ( ) [ NW ] ) if isinstance ( inmotion . item , StateView ) : state_v = inmotion . item state_m = state_v . model self . view . canvas . request_update ( state_v ) if state_m . get_meta_data_editor ( ) [ 'rel_pos' ] != rel_pos : state_m . set_meta_data_editor ( 'rel_pos' , rel_pos ) affected_models [ state_m ] = ( "position" , True , state_v ) elif isinstance ( inmotion . item , NameView ) : state_v = inmotion . item state_m = self . view . canvas . get_parent ( state_v ) . model self . view . canvas . request_update ( state_v ) if state_m . get_meta_data_editor ( ) [ 'name' ] [ 'rel_pos' ] != rel_pos : state_m . set_meta_data_editor ( 'name.rel_pos' , rel_pos ) affected_models [ state_m ] = ( "name_position" , False , state_v ) elif isinstance ( inmotion . item , TransitionView ) : transition_v = inmotion . item transition_m = transition_v . model self . view . canvas . request_update ( transition_v ) current_waypoints = gap_helper . get_relative_positions_of_waypoints ( transition_v ) old_waypoints = transition_m . get_meta_data_editor ( ) [ 'waypoints' ] if current_waypoints != old_waypoints : transition_m . set_meta_data_editor ( 'waypoints' , current_waypoints ) affected_models [ transition_m ] = ( "waypoints" , False , transition_v ) if len ( affected_models ) == 1 : model = next ( iter ( affected_models ) ) change , affects_children , view = affected_models [ model ] self . view . graphical_editor . emit ( 'meta_data_changed' , model , change , affects_children ) elif len ( affected_models ) > 1 : common_parents = None for change , affects_children , view in affected_models . values ( ) : parents_of_view = set ( self . view . canvas . get_ancestors ( view ) ) if common_parents is None : common_parents = parents_of_view else : common_parents = common_parents . intersection ( parents_of_view ) assert len ( common_parents ) > 0 , "The selected elements do not have common parent element" for state_v in common_parents : children_of_state_v = self . view . canvas . get_all_children ( state_v ) if any ( common_parent in children_of_state_v for common_parent in common_parents ) : continue self . view . graphical_editor . emit ( 'meta_data_changed' , state_v . model , "positions" , True ) break if not affected_models and self . _old_selection is not None : self . view . unselect_all ( ) self . view . select_item ( self . _old_selection ) self . view . handle_new_selection ( self . _item ) self . _move_name_v = False self . _old_selection = None return super ( MoveItemTool , self ) . on_button_release ( event ) | Write back changes |
40,454 | def _filter_library_state ( self , items ) : if not items : return items top_most_item = items [ 0 ] top_most_state_v = top_most_item if isinstance ( top_most_item , StateView ) else top_most_item . parent state = top_most_state_v . model . state global_gui_config = gui_helper_state_machine . global_gui_config if global_gui_config . get_config_value ( 'STATE_SELECTION_INSIDE_LIBRARY_STATE_ENABLED' ) : if state . is_root_state_of_library : new_topmost_item = self . view . canvas . get_view_for_core_element ( state . parent ) return self . dismiss_upper_items ( items , new_topmost_item ) return items else : library_root_state = state . get_uppermost_library_root_state ( ) if library_root_state : library_state = library_root_state . parent library_state_v = self . view . canvas . get_view_for_core_element ( library_state ) return self . dismiss_upper_items ( items , library_state_v ) return items | Filters out child elements of library state when they cannot be hovered |
40,455 | def _filter_hovered_items ( self , items , event ) : items = self . _filter_library_state ( items ) if not items : return items top_most_item = items [ 0 ] second_top_most_item = items [ 1 ] if len ( items ) > 1 else None first_state_v = next ( filter ( lambda item : isinstance ( item , ( NameView , StateView ) ) , items ) ) first_state_v = first_state_v . parent if isinstance ( first_state_v , NameView ) else first_state_v if first_state_v : for item in items : if isinstance ( item , ConnectionView ) : if self . view . canvas . get_parent ( top_most_item ) is not first_state_v : continue break port_beneath_cursor = False state_ports = first_state_v . get_all_ports ( ) position = self . view . get_matrix_v2i ( first_state_v ) . transform_point ( event . x , event . y ) i2v_matrix = self . view . get_matrix_i2v ( first_state_v ) for port_v in state_ports : item_distance = port_v . port . glue ( position ) [ 1 ] view_distance = i2v_matrix . transform_distance ( item_distance , 0 ) [ 0 ] if view_distance == 0 : port_beneath_cursor = True break if port_beneath_cursor : items = self . dismiss_upper_items ( items , item ) top_most_item = items [ 0 ] second_top_most_item = items [ 1 ] if len ( items ) > 1 else None if isinstance ( top_most_item , NameView ) : state_v = second_top_most_item if state_v not in self . view . selected_items and top_most_item not in self . view . selected_items : items = items [ 1 : ] return items | Filters out items that cannot be hovered |
40,456 | def on_button_release ( self , event ) : self . queue_draw ( self . view ) x0 , y0 , x1 , y1 = self . x0 , self . y0 , self . x1 , self . y1 rectangle = ( min ( x0 , x1 ) , min ( y0 , y1 ) , abs ( x1 - x0 ) , abs ( y1 - y0 ) ) selected_items = self . view . get_items_in_rectangle ( rectangle , intersect = False ) self . view . handle_new_selection ( selected_items ) return True | Select or deselect rubber banded groups of items |
40,457 | def _set_motion_handle ( self , event ) : item = self . grabbed_item handle = self . grabbed_handle pos = event . x , event . y self . motion_handle = HandleInMotion ( item , handle , self . view ) self . motion_handle . GLUE_DISTANCE = self . _parent_state_v . border_width self . motion_handle . start_move ( pos ) | Sets motion handle to currently grabbed handle |
40,458 | def _create_temporary_connection ( self ) : if self . _is_transition : self . _connection_v = TransitionPlaceholderView ( self . _parent_state_v . hierarchy_level ) else : self . _connection_v = DataFlowPlaceholderView ( self . _parent_state_v . hierarchy_level ) self . view . canvas . add ( self . _connection_v , self . _parent_state_v ) | Creates a placeholder connection view |
40,459 | def _handle_temporary_connection ( self , old_sink , new_sink , of_target = True ) : def sink_set_and_differs ( sink_a , sink_b ) : if not sink_a : return False if not sink_b : return True if sink_a . port != sink_b . port : return True return False if sink_set_and_differs ( old_sink , new_sink ) : sink_port_v = old_sink . port . port_v self . _disconnect_temporarily ( sink_port_v , target = of_target ) if sink_set_and_differs ( new_sink , old_sink ) : sink_port_v = new_sink . port . port_v self . _connect_temporarily ( sink_port_v , target = of_target ) | Connect connection to new_sink |
40,460 | def _connect_temporarily ( self , port_v , target = True ) : if target : handle = self . _connection_v . to_handle ( ) else : handle = self . _connection_v . from_handle ( ) port_v . add_connected_handle ( handle , self . _connection_v , moving = True ) port_v . tmp_connect ( handle , self . _connection_v ) self . _connection_v . set_port_for_handle ( port_v , handle ) self . _redraw_port ( port_v ) | Set a connection between the current connection and the given port |
40,461 | def _disconnect_temporarily ( self , port_v , target = True ) : if target : handle = self . _connection_v . to_handle ( ) else : handle = self . _connection_v . from_handle ( ) port_v . remove_connected_handle ( handle ) port_v . tmp_disconnect ( ) self . _connection_v . reset_port_for_handle ( handle ) self . _redraw_port ( port_v ) | Removes a connection between the current connection and the given port |
40,462 | def initialize ( self ) : logger . debug ( "Initializing LibraryManager: Loading libraries ... " ) self . _libraries = { } self . _library_root_paths = { } self . _replaced_libraries = { } self . _skipped_states = [ ] self . _skipped_library_roots = [ ] for library_root_key , library_root_path in config . global_config . get_config_value ( "LIBRARY_PATHS" ) . items ( ) : library_root_path = self . _clean_path ( library_root_path ) if os . path . exists ( library_root_path ) : logger . debug ( "Adding library root key '{0}' from path '{1}'" . format ( library_root_key , library_root_path ) ) self . _load_libraries_from_root_path ( library_root_key , library_root_path ) else : logger . warning ( "Configured path for library root key '{}' does not exist: {}" . format ( library_root_key , library_root_path ) ) library_path_env = os . environ . get ( 'RAFCON_LIBRARY_PATH' , '' ) library_paths = set ( library_path_env . split ( os . pathsep ) ) for library_root_path in library_paths : if not library_root_path : continue library_root_path = self . _clean_path ( library_root_path ) if not os . path . exists ( library_root_path ) : logger . warning ( "The library specified in RAFCON_LIBRARY_PATH does not exist: {}" . format ( library_root_path ) ) continue _ , library_root_key = os . path . split ( library_root_path ) if library_root_key in self . _libraries : if os . path . realpath ( self . _library_root_paths [ library_root_key ] ) == os . path . realpath ( library_root_path ) : logger . info ( "The library root key '{}' and root path '{}' exists multiple times in your environment" " and will be skipped." . format ( library_root_key , library_root_path ) ) else : logger . warning ( "The library '{}' is already existing and will be overridden with '{}'" . format ( library_root_key , library_root_path ) ) self . _load_libraries_from_root_path ( library_root_key , library_root_path ) else : self . _load_libraries_from_root_path ( library_root_key , library_root_path ) logger . debug ( "Adding library '{1}' from {0}" . format ( library_root_path , library_root_key ) ) self . _libraries = OrderedDict ( sorted ( self . _libraries . items ( ) ) ) logger . debug ( "Initialization of LibraryManager done" ) | Initializes the library manager |
40,463 | def _clean_path ( path ) : path = path . replace ( '"' , '' ) path = path . replace ( "'" , '' ) path = os . path . expanduser ( path ) path = os . path . expandvars ( path ) if not os . path . isabs ( path ) : path = os . path . join ( config . global_config . path , path ) path = os . path . abspath ( path ) path = os . path . realpath ( path ) return path | Create a fully fissile absolute system path with no symbolic links and environment variables |
40,464 | def _load_nested_libraries ( self , library_path , target_dict ) : for library_name in os . listdir ( library_path ) : library_folder_path , library_name = self . check_clean_path_of_library ( library_path , library_name ) full_library_path = os . path . join ( library_path , library_name ) if os . path . isdir ( full_library_path ) and library_name [ 0 ] != '.' : if os . path . exists ( os . path . join ( full_library_path , storage . STATEMACHINE_FILE ) ) or os . path . exists ( os . path . join ( full_library_path , storage . STATEMACHINE_FILE_OLD ) ) : target_dict [ library_name ] = full_library_path else : target_dict [ library_name ] = { } self . _load_nested_libraries ( full_library_path , target_dict [ library_name ] ) target_dict [ library_name ] = OrderedDict ( sorted ( target_dict [ library_name ] . items ( ) ) ) | Recursively load libraries within path |
40,465 | def _get_library_os_path_from_library_dict_tree ( self , library_path , library_name ) : if library_path is None or library_name is None : return None path_list = library_path . split ( os . sep ) target_lib_dict = self . libraries for path_element in path_list : if path_element not in target_lib_dict : target_lib_dict = None break target_lib_dict = target_lib_dict [ path_element ] return None if target_lib_dict is None or library_name not in target_lib_dict else target_lib_dict [ library_name ] | Hand verified library os path from libraries dictionary tree . |
40,466 | def _get_library_root_key_for_os_path ( self , path ) : path = os . path . realpath ( path ) library_root_key = None for library_root_key , library_root_path in self . _library_root_paths . items ( ) : rel_path = os . path . relpath ( path , library_root_path ) if rel_path . startswith ( '..' ) : library_root_key = None continue else : break return library_root_key | Return library root key if path is within library root paths |
40,467 | def get_library_path_and_name_for_os_path ( self , path ) : library_path = None library_name = None library_root_key = self . _get_library_root_key_for_os_path ( path ) if library_root_key is not None : library_root_path = self . _library_root_paths [ library_root_key ] path_elements_without_library_root = path [ len ( library_root_path ) + 1 : ] . split ( os . sep ) library_name = path_elements_without_library_root [ - 1 ] sub_library_path = '' if len ( path_elements_without_library_root [ : - 1 ] ) : sub_library_path = os . sep + os . sep . join ( path_elements_without_library_root [ : - 1 ] ) library_path = library_root_key + sub_library_path return library_path , library_name | Generate valid library_path and library_name |
40,468 | def get_library_instance ( self , library_path , library_name ) : if self . is_library_in_libraries ( library_path , library_name ) : from rafcon . core . states . library_state import LibraryState return LibraryState ( library_path , library_name , "0.1" ) else : logger . warning ( "Library manager will not create a library instance which is not in the mounted libraries." ) | Generate a Library instance from within libraries dictionary tree . |
40,469 | def get_library_state_copy_instance ( self , lib_os_path ) : if lib_os_path in self . _loaded_libraries : state_machine = self . _loaded_libraries [ lib_os_path ] state_copy = copy . deepcopy ( state_machine . root_state ) return state_machine . version , state_copy else : state_machine = storage . load_state_machine_from_path ( lib_os_path ) self . _loaded_libraries [ lib_os_path ] = state_machine if config . global_config . get_config_value ( "NO_PROGRAMMATIC_CHANGE_OF_LIBRARY_STATES_PERFORMED" , False ) : return state_machine . version , state_machine . root_state else : state_copy = copy . deepcopy ( state_machine . root_state ) return state_machine . version , state_copy | A method to get a state copy of the library specified via the lib_os_path . |
40,470 | def remove_library_from_file_system ( self , library_path , library_name ) : library_file_system_path = self . get_os_path_to_library ( library_path , library_name ) [ 0 ] shutil . rmtree ( library_file_system_path ) self . refresh_libraries ( ) | Remove library from hard disk . |
40,471 | def buses_grid_linked ( network , voltage_level ) : mask = ( ( network . buses . index . isin ( network . lines . bus0 ) | ( network . buses . index . isin ( network . lines . bus1 ) ) ) & ( network . buses . v_nom . isin ( voltage_level ) ) ) df = network . buses [ mask ] return df . index | Get bus - ids of a given voltage level connected to the grid . |
40,472 | def clip_foreign ( network ) : foreign_buses = network . buses [ network . buses . country_code != 'DE' ] network . buses = network . buses . drop ( network . buses . loc [ foreign_buses . index ] . index ) network . lines = network . lines . drop ( network . lines [ ( network . lines [ 'bus0' ] . isin ( network . buses . index ) == False ) | ( network . lines [ 'bus1' ] . isin ( network . buses . index ) == False ) ] . index ) network . links = network . links . drop ( network . links [ ( network . links [ 'bus0' ] . isin ( network . buses . index ) == False ) | ( network . links [ 'bus1' ] . isin ( network . buses . index ) == False ) ] . index ) network . transformers = network . transformers . drop ( network . transformers [ ( network . transformers [ 'bus0' ] . isin ( network . buses . index ) == False ) | ( network . transformers [ 'bus1' ] . isin ( network . buses . index ) == False ) ] . index ) network . generators = network . generators . drop ( network . generators [ ( network . generators [ 'bus' ] . isin ( network . buses . index ) == False ) ] . index ) network . loads = network . loads . drop ( network . loads [ ( network . loads [ 'bus' ] . isin ( network . buses . index ) == False ) ] . index ) network . storage_units = network . storage_units . drop ( network . storage_units [ ( network . storage_units [ 'bus' ] . isin ( network . buses . index ) == False ) ] . index ) components = [ 'loads' , 'generators' , 'lines' , 'buses' , 'transformers' , 'links' ] for g in components : h = g + '_t' nw = getattr ( network , h ) for i in nw . keys ( ) : cols = [ j for j in getattr ( nw , i ) . columns if j not in getattr ( network , g ) . index ] for k in cols : del getattr ( nw , i ) [ k ] return network | Delete all components and timelines located outside of Germany . Add transborder flows divided by country of origin as network . foreign_trade . |
40,473 | def connected_grid_lines ( network , busids ) : mask = network . lines . bus1 . isin ( busids ) | network . lines . bus0 . isin ( busids ) return network . lines [ mask ] | Get grid lines connected to given buses . |
40,474 | def connected_transformer ( network , busids ) : mask = ( network . transformers . bus0 . isin ( busids ) ) return network . transformers [ mask ] | Get transformer connected to given buses . |
40,475 | def data_manipulation_sh ( network ) : from shapely . geometry import Point , LineString , MultiLineString from geoalchemy2 . shape import from_shape , to_shape new_bus = str ( network . buses . index . astype ( np . int64 ) . max ( ) + 1 ) new_trafo = str ( network . transformers . index . astype ( np . int64 ) . max ( ) + 1 ) new_line = str ( network . lines . index . astype ( np . int64 ) . max ( ) + 1 ) network . add ( "Bus" , new_bus , carrier = 'AC' , v_nom = 220 , x = 10.760835 , y = 53.909745 ) network . add ( "Transformer" , new_trafo , bus0 = "25536" , bus1 = new_bus , x = 1.29960 , tap_ratio = 1 , s_nom = 1600 ) network . add ( "Line" , new_line , bus0 = "26387" , bus1 = new_bus , x = 0.0001 , s_nom = 1600 ) network . lines . loc [ new_line , 'cables' ] = 3.0 point_bus1 = Point ( 10.760835 , 53.909745 ) network . buses . set_value ( new_bus , 'geom' , from_shape ( point_bus1 , 4326 ) ) network . lines . set_value ( new_line , 'geom' , from_shape ( MultiLineString ( [ LineString ( [ to_shape ( network . buses . geom [ '26387' ] ) , point_bus1 ] ) ] ) , 4326 ) ) network . lines . set_value ( new_line , 'topo' , from_shape ( LineString ( [ to_shape ( network . buses . geom [ '26387' ] ) , point_bus1 ] ) , 4326 ) ) network . transformers . set_value ( new_trafo , 'geom' , from_shape ( MultiLineString ( [ LineString ( [ to_shape ( network . buses . geom [ '25536' ] ) , point_bus1 ] ) ] ) , 4326 ) ) network . transformers . set_value ( new_trafo , 'topo' , from_shape ( LineString ( [ to_shape ( network . buses . geom [ '25536' ] ) , point_bus1 ] ) , 4326 ) ) return | Adds missing components to run calculations with SH scenarios . |
40,476 | def results_to_csv ( network , args , pf_solution = None ) : path = args [ 'csv_export' ] if path == False : return None if not os . path . exists ( path ) : os . makedirs ( path , exist_ok = True ) network . export_to_csv_folder ( path ) data = pd . read_csv ( os . path . join ( path , 'network.csv' ) ) data [ 'time' ] = network . results [ 'Solver' ] . Time data = data . apply ( _enumerate_row , axis = 1 ) data . to_csv ( os . path . join ( path , 'network.csv' ) , index = False ) with open ( os . path . join ( path , 'args.json' ) , 'w' ) as fp : json . dump ( args , fp ) if not isinstance ( pf_solution , type ( None ) ) : pf_solution . to_csv ( os . path . join ( path , 'pf_solution.csv' ) , index = True ) if hasattr ( network , 'Z' ) : file = [ i for i in os . listdir ( path . strip ( '0123456789' ) ) if i == 'Z.csv' ] if file : print ( 'Z already calculated' ) else : network . Z . to_csv ( path . strip ( '0123456789' ) + '/Z.csv' , index = False ) return | Function the writes the calaculation results in csv - files in the desired directory . |
40,477 | def parallelisation ( network , args , group_size , extra_functionality = None ) : print ( "Performing linear OPF, {} snapshot(s) at a time:" . format ( group_size ) ) t = time . time ( ) for i in range ( int ( ( args [ 'end_snapshot' ] - args [ 'start_snapshot' ] + 1 ) / group_size ) ) : if i > 0 : network . storage_units . state_of_charge_initial = network . storage_units_t . state_of_charge . loc [ network . snapshots [ group_size * i - 1 ] ] network . lopf ( network . snapshots [ group_size * i : group_size * i + group_size ] , solver_name = args [ 'solver_name' ] , solver_options = args [ 'solver_options' ] , extra_functionality = extra_functionality ) network . lines . s_nom = network . lines . s_nom_opt print ( time . time ( ) - t / 60 ) return | Function that splits problem in selected number of snapshot groups and runs optimization successive for each group . Not useful for calculations with storage untis or extension . |
40,478 | def set_slack ( network ) : old_slack = network . generators . index [ network . generators . control == 'Slack' ] [ 0 ] if network . generators . p_nom [ old_slack ] > 50 and network . generators . carrier [ old_slack ] in ( 'solar' , 'wind' ) : old_control = 'PQ' elif network . generators . p_nom [ old_slack ] > 50 and network . generators . carrier [ old_slack ] not in ( 'solar' , 'wind' ) : old_control = 'PV' elif network . generators . p_nom [ old_slack ] < 50 : old_control = 'PQ' old_gens = network . generators gens_summed = network . generators_t . p . sum ( ) old_gens [ 'p_summed' ] = gens_summed max_gen_buses_index = old_gens . groupby ( [ 'bus' ] ) . agg ( { 'p_summed' : np . sum } ) . p_summed . sort_values ( ) . index for bus_iter in range ( 1 , len ( max_gen_buses_index ) - 1 ) : if old_gens [ ( network . generators [ 'bus' ] == max_gen_buses_index [ - bus_iter ] ) & ( network . generators [ 'control' ] == 'PV' ) ] . empty : continue else : new_slack_bus = max_gen_buses_index [ - bus_iter ] break network . generators = network . generators . drop ( 'p_summed' , 1 ) new_slack_gen = network . generators . p_nom [ ( network . generators [ 'bus' ] == new_slack_bus ) & ( network . generators [ 'control' ] == 'PV' ) ] . sort_values ( ) . index [ - 1 ] network . generators = network . generators . set_value ( old_slack , 'control' , old_control ) network . generators = network . generators . set_value ( new_slack_gen , 'control' , 'Slack' ) return network | Function that chosses the bus with the maximum installed power as slack |
40,479 | def ramp_limits ( network ) : carrier = [ 'coal' , 'biomass' , 'gas' , 'oil' , 'waste' , 'lignite' , 'uranium' , 'geothermal' ] data = { 'start_up_cost' : [ 77 , 57 , 42 , 57 , 57 , 77 , 50 , 57 ] , 'start_up_fuel' : [ 4.3 , 2.8 , 1.45 , 2.8 , 2.8 , 4.3 , 16.7 , 2.8 ] , 'min_up_time' : [ 5 , 2 , 3 , 2 , 2 , 5 , 12 , 2 ] , 'min_down_time' : [ 7 , 2 , 2 , 2 , 2 , 7 , 17 , 2 ] , 'p_min_pu' : [ 0.33 , 0.38 , 0.4 , 0.38 , 0.38 , 0.5 , 0.45 , 0.38 ] } df = pd . DataFrame ( data , index = carrier ) fuel_costs = network . generators . marginal_cost . groupby ( network . generators . carrier ) . mean ( ) [ carrier ] df [ 'start_up_fuel' ] = df [ 'start_up_fuel' ] * fuel_costs df [ 'start_up_cost' ] = df [ 'start_up_cost' ] + df [ 'start_up_fuel' ] df . drop ( 'start_up_fuel' , axis = 1 , inplace = True ) for tech in df . index : for limit in df . columns : network . generators . loc [ network . generators . carrier == tech , limit ] = df . loc [ tech , limit ] network . generators . start_up_cost = network . generators . start_up_cost * network . generators . p_nom network . generators . committable = True | Add ramping constraints to thermal power plants . |
40,480 | def get_args_setting ( args , jsonpath = 'scenario_setting.json' ) : if not jsonpath == None : with open ( jsonpath ) as f : args = json . load ( f ) return args | Get and open json file with scenaio settings of eTraGo args . The settings incluedes all eTraGo specific settings of arguments and parameters for a reproducible calculation . |
40,481 | def set_line_country_tags ( network ) : transborder_lines_0 = network . lines [ network . lines [ 'bus0' ] . isin ( network . buses . index [ network . buses [ 'country_code' ] != 'DE' ] ) ] . index transborder_lines_1 = network . lines [ network . lines [ 'bus1' ] . isin ( network . buses . index [ network . buses [ 'country_code' ] != 'DE' ] ) ] . index network . lines . loc [ transborder_lines_0 , 'country' ] = network . buses . loc [ network . lines . loc [ transborder_lines_0 , 'bus0' ] . values , 'country_code' ] . values network . lines . loc [ transborder_lines_1 , 'country' ] = network . buses . loc [ network . lines . loc [ transborder_lines_1 , 'bus1' ] . values , 'country_code' ] . values network . lines [ 'country' ] . fillna ( 'DE' , inplace = True ) doubles = list ( set ( transborder_lines_0 . intersection ( transborder_lines_1 ) ) ) for line in doubles : c_bus0 = network . buses . loc [ network . lines . loc [ line , 'bus0' ] , 'country' ] c_bus1 = network . buses . loc [ network . lines . loc [ line , 'bus1' ] , 'country' ] network . lines . loc [ line , 'country' ] = '{}{}' . format ( c_bus0 , c_bus1 ) transborder_links_0 = network . links [ network . links [ 'bus0' ] . isin ( network . buses . index [ network . buses [ 'country_code' ] != 'DE' ] ) ] . index transborder_links_1 = network . links [ network . links [ 'bus1' ] . isin ( network . buses . index [ network . buses [ 'country_code' ] != 'DE' ] ) ] . index network . links . loc [ transborder_links_0 , 'country' ] = network . buses . loc [ network . links . loc [ transborder_links_0 , 'bus0' ] . values , 'country_code' ] . values network . links . loc [ transborder_links_1 , 'country' ] = network . buses . loc [ network . links . loc [ transborder_links_1 , 'bus1' ] . values , 'country_code' ] . values network . links [ 'country' ] . fillna ( 'DE' , inplace = True ) doubles = list ( set ( transborder_links_0 . intersection ( transborder_links_1 ) ) ) for link in doubles : c_bus0 = network . buses . loc [ network . links . loc [ link , 'bus0' ] , 'country' ] c_bus1 = network . buses . loc [ network . links . loc [ link , 'bus1' ] , 'country' ] network . links . loc [ link , 'country' ] = '{}{}' . format ( c_bus0 , c_bus1 ) | Set country tag for AC - and DC - lines . |
40,482 | def max_line_ext ( network , snapshots , share = 1.01 ) : lines_snom = network . lines . s_nom . sum ( ) links_pnom = network . links . p_nom . sum ( ) def _rule ( m ) : lines_opt = sum ( m . passive_branch_s_nom [ index ] for index in m . passive_branch_s_nom_index ) links_opt = sum ( m . link_p_nom [ index ] for index in m . link_p_nom_index ) return ( lines_opt + links_opt ) <= ( lines_snom + links_pnom ) * share network . model . max_line_ext = Constraint ( rule = _rule ) | Sets maximal share of overall network extension as extra functionality in LOPF |
40,483 | def min_renewable_share ( network , snapshots , share = 0.72 ) : renewables = [ 'wind_onshore' , 'wind_offshore' , 'biomass' , 'solar' , 'run_of_river' ] res = list ( network . generators . index [ network . generators . carrier . isin ( renewables ) ] ) total = list ( network . generators . index ) snapshots = network . snapshots def _rule ( m ) : renewable_production = sum ( m . generator_p [ gen , sn ] for gen in res for sn in snapshots ) total_production = sum ( m . generator_p [ gen , sn ] for gen in total for sn in snapshots ) return ( renewable_production >= total_production * share ) network . model . min_renewable_share = Constraint ( rule = _rule ) | Sets minimal renewable share of generation as extra functionality in LOPF |
40,484 | def get_node ( guild_id : int , ignore_ready_status : bool = False ) -> Node : guild_count = 1e10 least_used = None for node in _nodes : guild_ids = node . player_manager . guild_ids if ignore_ready_status is False and not node . ready . is_set ( ) : continue elif len ( guild_ids ) < guild_count : guild_count = len ( guild_ids ) least_used = node if guild_id in guild_ids : return node if least_used is None : raise IndexError ( "No nodes found." ) return least_used | Gets a node based on a guild ID useful for noding separation . If the guild ID does not already have a node association the least used node is returned . Skips over nodes that are not yet ready . |
40,485 | async def join_voice ( guild_id : int , channel_id : int ) : node = get_node ( guild_id ) voice_ws = node . get_voice_ws ( guild_id ) await voice_ws . voice_state ( guild_id , channel_id ) | Joins a voice channel by ID s . |
40,486 | async def connect ( self , timeout = None ) : self . _is_shutdown = False combo_uri = "ws://{}:{}" . format ( self . host , self . rest ) uri = "ws://{}:{}" . format ( self . host , self . port ) log . debug ( "Lavalink WS connecting to %s or %s with headers %s" , combo_uri , uri , self . headers ) tasks = tuple ( { self . _multi_try_connect ( u ) for u in ( combo_uri , uri ) } ) for task in asyncio . as_completed ( tasks , timeout = timeout ) : with contextlib . suppress ( Exception ) : if await cast ( Awaitable [ Optional [ websockets . WebSocketClientProtocol ] ] , task ) : break else : raise asyncio . TimeoutError log . debug ( "Creating Lavalink WS listener." ) self . _listener_task = self . loop . create_task ( self . listener ( ) ) for data in self . _queue : await self . send ( data ) self . ready . set ( ) self . update_state ( NodeState . READY ) | Connects to the Lavalink player event websocket . |
40,487 | async def listener ( self ) : while self . _ws . open and self . _is_shutdown is False : try : data = json . loads ( await self . _ws . recv ( ) ) except websockets . ConnectionClosed : break raw_op = data . get ( "op" ) try : op = LavalinkIncomingOp ( raw_op ) except ValueError : socket_log . debug ( "Received unknown op: %s" , data ) else : socket_log . debug ( "Received known op: %s" , data ) self . loop . create_task ( self . _handle_op ( op , data ) ) self . ready . clear ( ) log . debug ( "Listener exited: ws %s SHUTDOWN %s." , self . _ws . open , self . _is_shutdown ) self . loop . create_task ( self . _reconnect ( ) ) | Listener task for receiving ops from Lavalink . |
40,488 | async def join_voice_channel ( self , guild_id , channel_id ) : voice_ws = self . get_voice_ws ( guild_id ) await voice_ws . voice_state ( guild_id , channel_id ) | Alternative way to join a voice channel if node is known . |
40,489 | async def disconnect ( self ) : self . _is_shutdown = True self . ready . clear ( ) self . update_state ( NodeState . DISCONNECTING ) await self . player_manager . disconnect ( ) if self . _ws is not None and self . _ws . open : await self . _ws . close ( ) if self . _listener_task is not None and not self . loop . is_closed ( ) : self . _listener_task . cancel ( ) self . _state_handlers = [ ] _nodes . remove ( self ) log . debug ( "Shutdown Lavalink WS." ) | Shuts down and disconnects the websocket . |
40,490 | def run ( self ) : logger . debug ( "Starting execution of {0}{1}" . format ( self , " (backwards)" if self . backward_execution else "" ) ) self . setup_run ( ) child_errors = { } final_outcomes_dict = { } decider_state = self . states [ UNIQUE_DECIDER_STATE_ID ] try : concurrency_history_item = self . setup_forward_or_backward_execution ( ) self . start_child_states ( concurrency_history_item , decider_state ) for history_index , state in enumerate ( self . states . values ( ) ) : if state is not decider_state : self . join_state ( state , history_index , concurrency_history_item ) self . add_state_execution_output_to_scoped_data ( state . output_data , state ) self . update_scoped_variables_with_output_dictionary ( state . output_data , state ) if 'error' in state . output_data : child_errors [ state . state_id ] = ( state . name , state . output_data [ 'error' ] ) final_outcomes_dict [ state . state_id ] = ( state . name , state . final_outcome ) if self . backward_execution : return self . finalize_backward_execution ( ) else : self . backward_execution = False decider_state_error = self . run_decider_state ( decider_state , child_errors , final_outcomes_dict ) transition = self . get_transition_for_outcome ( decider_state , decider_state . final_outcome ) if transition is None : transition = self . handle_no_transition ( decider_state ) decider_state . state_execution_status = StateExecutionStatus . INACTIVE if transition is None : self . output_data [ "error" ] = RuntimeError ( "state aborted" ) else : if decider_state_error : self . output_data [ "error" ] = decider_state_error self . final_outcome = self . outcomes [ transition . to_outcome ] return self . finalize_concurrency_state ( self . final_outcome ) except Exception as e : logger . error ( "{0} had an internal error: {1}\n{2}" . format ( self , str ( e ) , str ( traceback . format_exc ( ) ) ) ) self . output_data [ "error" ] = e self . state_execution_status = StateExecutionStatus . WAIT_FOR_NEXT_STATE return self . finalize ( Outcome ( - 1 , "aborted" ) ) | This defines the sequence of actions that are taken when the barrier concurrency state is executed |
40,491 | def run_decider_state ( self , decider_state , child_errors , final_outcomes_dict ) : decider_state . state_execution_status = StateExecutionStatus . ACTIVE decider_state . child_errors = child_errors decider_state . final_outcomes_dict = final_outcomes_dict decider_state . input_data = self . get_inputs_for_state ( decider_state ) decider_state . output_data = self . create_output_dictionary_for_state ( decider_state ) decider_state . start ( self . execution_history , backward_execution = False ) decider_state . join ( ) decider_state_error = None if decider_state . final_outcome . outcome_id == - 1 : if 'error' in decider_state . output_data : decider_state_error = decider_state . output_data [ 'error' ] self . add_state_execution_output_to_scoped_data ( decider_state . output_data , decider_state ) self . update_scoped_variables_with_output_dictionary ( decider_state . output_data , decider_state ) return decider_state_error | Runs the decider state of the barrier concurrency state . The decider state decides on which outcome the barrier concurrency is left . |
40,492 | def _check_transition_validity ( self , check_transition ) : valid , message = super ( BarrierConcurrencyState , self ) . _check_transition_validity ( check_transition ) if not valid : return False , message from_state_id = check_transition . from_state to_state_id = check_transition . to_state from_outcome_id = check_transition . from_outcome to_outcome_id = check_transition . to_outcome if from_state_id == UNIQUE_DECIDER_STATE_ID : if to_state_id != self . state_id : return False , "Transition from the decider state must go to the parent state" else : if to_state_id != UNIQUE_DECIDER_STATE_ID : if from_outcome_id not in [ - 2 , - 1 ] or to_outcome_id not in [ - 2 , - 1 ] : return False , "Transition from this state must go to the decider state. The only exception are " "transition from aborted/preempted to the parent aborted/preempted outcomes" return True , message | Transition of BarrierConcurrencyStates must least fulfill the condition of a ContainerState . Start transitions are forbidden in the ConcurrencyState . |
40,493 | def add_state ( self , state , storage_load = False ) : state_id = super ( BarrierConcurrencyState , self ) . add_state ( state ) if not storage_load and not self . __init_running and not state . state_id == UNIQUE_DECIDER_STATE_ID : for o_id , o in list ( state . outcomes . items ( ) ) : if not o_id == - 1 and not o_id == - 2 : self . add_transition ( state . state_id , o_id , self . states [ UNIQUE_DECIDER_STATE_ID ] . state_id , None ) return state_id | Overwrite the parent class add_state method |
40,494 | def states ( self , states ) : state_ids = list ( self . states . keys ( ) ) for state_id in state_ids : if state_id == UNIQUE_DECIDER_STATE_ID and UNIQUE_DECIDER_STATE_ID not in states : continue self . remove_state ( state_id ) if states is not None : if not isinstance ( states , dict ) : raise TypeError ( "states must be of type dict" ) decider_state = states . pop ( UNIQUE_DECIDER_STATE_ID , None ) if decider_state is not None : self . add_state ( decider_state ) for state in states . values ( ) : self . add_state ( state ) | Overwrite the setter of the container state base class as special handling for the decider state is needed . |
40,495 | def remove_state ( self , state_id , recursive = True , force = False , destroy = True ) : if state_id == UNIQUE_DECIDER_STATE_ID and force is False : raise AttributeError ( "You are not allowed to delete the decider state." ) else : return ContainerState . remove_state ( self , state_id , recursive = recursive , force = force , destroy = destroy ) | Overwrite the parent class remove state method by checking if the user tries to delete the decider state |
40,496 | def get_outcome_for_state_name ( self , name ) : return_value = None for state_id , name_outcome_tuple in self . final_outcomes_dict . items ( ) : if name_outcome_tuple [ 0 ] == name : return_value = name_outcome_tuple [ 1 ] break return return_value | Returns the final outcome of the child state specified by name . |
40,497 | def get_outcome_for_state_id ( self , state_id ) : return_value = None for s_id , name_outcome_tuple in self . final_outcomes_dict . items ( ) : if s_id == state_id : return_value = name_outcome_tuple [ 1 ] break return return_value | Returns the final outcome of the child state specified by the state_id . |
40,498 | def get_errors_for_state_name ( self , name ) : return_value = None for state_id , name_outcome_tuple in self . child_errors . items ( ) : if name_outcome_tuple [ 0 ] == name : return_value = name_outcome_tuple [ 1 ] break return return_value | Returns the error message of the child state specified by name . |
40,499 | def add_controller ( self , key , controller ) : assert isinstance ( controller , ExtendedController ) controller . parent = self self . __child_controllers [ key ] = controller if self . __shortcut_manager is not None and controller not in self . __action_registered_controllers : controller . register_actions ( self . __shortcut_manager ) self . __action_registered_controllers . append ( controller ) | Add child controller |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.