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 , s...
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 . _ini...
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 : _...
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 , FI...
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 ...
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_fil...
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} fa...
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 = ...
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 (...
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 ,...
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 ...
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 No...
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_val...
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_dat...
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_...
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...
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 , elemen...
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 ...
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 . _pare...
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 (...
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 ) ) > cons...
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 Value...
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_f...
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 ] ) e...
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_...
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 : r...
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 = sel...
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 ...
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_curr...
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_st...
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 ( t...
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 ] . mu...
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 . gen...
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 . contr...
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...
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 . m...
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 ( ...
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 ( 'sourc...
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" : ...
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 ) ...
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 '{}' ..."...
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' ,...
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...
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...
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 globa...
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 ) ) , ite...
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 ...
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...
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_si...
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 . _con...
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_...
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...
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 = o...
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_...
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...
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 = Non...
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 (...
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 l...
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_f...
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 . buse...
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 ...
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' ...
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_u...
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 a...
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 ...
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 [ '...
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 inde...
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...
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 ( g...
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 ( { se...
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...
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_...
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_o...
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 ( de...
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 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_i...
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 mu...
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...
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 ....
Add child controller