idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
16,300
def _install_nukeassist ( use_threaded_wrapper ) : import nuke if "--nukeassist" not in nuke . rawArgs : raise ImportError def threaded_wrapper ( func , * args , ** kwargs ) : return nuke . executeInMainThreadWithResult ( func , args , kwargs ) _common_setup ( "NukeAssist" , threaded_wrapper , use_threaded_wrapper )
Helper function to The Foundry NukeAssist support
16,301
def _install_hiero ( use_threaded_wrapper ) : import hiero import nuke if "--hiero" not in nuke . rawArgs : raise ImportError def threaded_wrapper ( func , * args , ** kwargs ) : return hiero . core . executeInMainThreadWithResult ( func , args , kwargs ) _common_setup ( "Hiero" , threaded_wrapper , use_threaded_wrappe...
Helper function to The Foundry Hiero support
16,302
def _install_blender ( use_threaded_wrapper ) : import bpy qml_to_blender = queue . Queue ( ) blender_to_qml = queue . Queue ( ) def threaded_wrapper ( func , * args , ** kwargs ) : qml_to_blender . put ( ( func , args , kwargs ) ) return blender_to_qml . get ( ) class PyblishQMLOperator ( bpy . types . Operator ) : bl...
Blender is a special snowflake
16,303
def install ( self , host ) : print ( "Installing.." ) if self . _state [ "installed" ] : return if self . is_headless ( ) : log . info ( "Headless host" ) return print ( "aboutToQuit.." ) self . app . aboutToQuit . connect ( self . _on_application_quit ) if host == "Maya" : print ( "Maya host.." ) window = { widget . ...
Setup common to all Qt - based hosts
16,304
def find_window ( self ) : window = self . app . activeWindow ( ) while True : parent_window = window . parent ( ) if parent_window : window = parent_window else : break return window
Get top window in host
16,305
def tab_should_insert_whitespace ( ) : b = get_app ( ) . current_buffer before_cursor = b . document . current_line_before_cursor return bool ( b . text and ( not before_cursor or before_cursor . isspace ( ) ) )
When the tab key is pressed with only whitespace character before the cursor do autocompletion . Otherwise insert indentation .
16,306
def load_sidebar_bindings ( python_input ) : bindings = KeyBindings ( ) handle = bindings . add sidebar_visible = Condition ( lambda : python_input . show_sidebar ) @ handle ( 'up' , filter = sidebar_visible ) @ handle ( 'c-p' , filter = sidebar_visible ) @ handle ( 'k' , filter = sidebar_visible ) def _ ( event ) : " ...
Load bindings for the navigation in the sidebar .
16,307
def auto_newline ( buffer ) : r insert_text = buffer . insert_text if buffer . document . current_line_after_cursor : insert_text ( '\n' ) else : current_line = buffer . document . current_line_before_cursor . rstrip ( ) insert_text ( '\n' ) unindent = current_line . rstrip ( ) . endswith ( ' pass' ) current_line2 = cu...
r Insert \ n at the cursor position . Also add necessary padding .
16,308
def _path_completer_grammar ( self ) : if self . _path_completer_grammar_cache is None : self . _path_completer_grammar_cache = self . _create_path_completer_grammar ( ) return self . _path_completer_grammar_cache
Return the grammar for matching paths inside strings inside Python code .
16,309
def get_completions ( self , document , complete_event ) : if complete_event . completion_requested or self . _complete_path_while_typing ( document ) : for c in self . _path_completer . get_completions ( document , complete_event ) : yield c if self . _path_completer_grammar . match ( document . text_before_cursor ) :...
Get Python completions .
16,310
def _inputhook_tk ( inputhook_context ) : import _tkinter from six . moves import tkinter root = tkinter . _default_root def wait_using_filehandler ( ) : stop = [ False ] def done ( * a ) : stop [ 0 ] = True root . createfilehandler ( inputhook_context . fileno ( ) , _tkinter . READABLE , done ) while root . dooneevent...
Inputhook for Tk . Run the Tk eventloop until prompt - toolkit needs to process the next input .
16,311
def run_config ( repl , config_file = '~/.ptpython/config.py' ) : assert isinstance ( repl , PythonInput ) assert isinstance ( config_file , six . text_type ) config_file = os . path . expanduser ( config_file ) def enter_to_continue ( ) : six . moves . input ( '\nPress ENTER to continue...' ) if not os . path . exists...
Execute REPL config file .
16,312
def _load_start_paths ( self ) : " Start the Read-Eval-Print Loop. " if self . _startup_paths : for path in self . _startup_paths : if os . path . exists ( path ) : with open ( path , 'rb' ) as f : code = compile ( f . read ( ) , path , 'exec' ) six . exec_ ( code , self . get_globals ( ) , self . get_locals ( ) ) else...
Start the Read - Eval - Print Loop .
16,313
def _execute ( self , line ) : output = self . app . output if '' not in sys . path : sys . path . insert ( 0 , '' ) def compile_with_flags ( code , mode ) : " Compile code with the right compiler flags. " return compile ( code , '<stdin>' , mode , flags = self . get_compiler_flags ( ) , dont_inherit = True ) if line ....
Evaluate the line and print the result .
16,314
def interactive_shell ( ) : print ( 'You should be able to read and update the "counter[0]" variable from this shell.' ) try : yield from embed ( globals = globals ( ) , return_asyncio_coroutine = True , patch_stdout = True ) except EOFError : loop . stop ( )
Coroutine that starts a Python REPL from which we can access the global counter variable .
16,315
def validate ( self , document ) : if document . text . startswith ( '\x1a' ) : return try : if self . get_compiler_flags : flags = self . get_compiler_flags ( ) else : flags = 0 compile ( document . text , '<input>' , 'exec' , flags = flags , dont_inherit = True ) except SyntaxError as e : index = document . translate...
Check input for Python syntax errors .
16,316
def main ( port = 8222 ) : loop = asyncio . get_event_loop ( ) environ = { 'hello' : 'world' } def create_server ( ) : return MySSHServer ( lambda : environ ) print ( 'Listening on :%i' % port ) print ( 'To connect, do "ssh localhost -p %i"' % port ) loop . run_until_complete ( asyncssh . create_server ( create_server ...
Example that starts the REPL through an SSH server .
16,317
def _get_size ( self ) : if self . _chan is None : return Size ( rows = 20 , columns = 79 ) else : width , height , pixwidth , pixheight = self . _chan . get_terminal_size ( ) return Size ( rows = height , columns = width )
Callable that returns the current Size required by Vt100_Output .
16,318
def connection_made ( self , chan ) : self . _chan = chan f = asyncio . ensure_future ( self . cli . run_async ( ) ) def done ( _ ) : chan . close ( ) self . _chan = None f . add_done_callback ( done )
Client connected run repl in coroutine .
16,319
def configure ( repl ) : repl . show_signature = True repl . show_docstring = False repl . show_meta_enter_message = True repl . completion_visualisation = CompletionVisualisation . POP_UP repl . completion_menu_scroll_offset = 0 repl . show_line_numbers = False repl . show_status_bar = True repl . show_sidebar_help = ...
Configuration method . This is called during the start - up of ptpython .
16,320
def has_unclosed_brackets ( text ) : stack = [ ] text = re . sub ( r , '' , text ) for c in reversed ( text ) : if c in '])}' : stack . append ( c ) elif c in '[({' : if stack : if ( ( c == '[' and stack [ - 1 ] == ']' ) or ( c == '{' and stack [ - 1 ] == '}' ) or ( c == '(' and stack [ - 1 ] == ')' ) ) : stack . pop (...
Starting at the end of the string . If we find an opening bracket for which we didn t had a closing one yet return True .
16,321
def document_is_multiline_python ( document ) : def ends_in_multiline_string ( ) : delims = _multiline_string_delims . findall ( document . text ) opening = None for delim in delims : if opening is None : opening = delim elif delim == opening : opening = None return bool ( opening ) if '\n' in document . text or ends_i...
Determine whether this is a multiline Python document .
16,322
def if_mousedown ( handler ) : def handle_if_mouse_down ( mouse_event ) : if mouse_event . event_type == MouseEventType . MOUSE_DOWN : return handler ( mouse_event ) else : return NotImplemented return handle_if_mouse_down
Decorator for mouse handlers . Only handle event when the user pressed mouse down .
16,323
def _create_popup_window ( title , body ) : assert isinstance ( title , six . text_type ) assert isinstance ( body , Container ) return Frame ( body = body , title = title )
Return the layout for a pop - up window . It consists of a title bar showing the title text and a body layout . The window is surrounded by borders .
16,324
def get_new_document ( self , cursor_pos = None ) : lines = [ ] if self . original_document . text_before_cursor : lines . append ( self . original_document . text_before_cursor ) for line_no in sorted ( self . selected_lines ) : lines . append ( self . history_lines [ line_no ] ) if self . original_document . text_aft...
Create a Document instance that contains the resulting text .
16,325
def _default_buffer_pos_changed ( self , _ ) : if self . app . current_buffer == self . default_buffer : try : line_no = self . default_buffer . document . cursor_position_row - self . history_mapping . result_line_offset if line_no < 0 : raise IndexError history_lineno = sorted ( self . history_mapping . selected_line...
When the cursor changes in the default buffer . Synchronize with history buffer .
16,326
def _history_buffer_pos_changed ( self , _ ) : if self . app . current_buffer == self . history_buffer : line_no = self . history_buffer . document . cursor_position_row if line_no in self . history_mapping . selected_lines : default_lineno = sorted ( self . history_mapping . selected_lines ) . index ( line_no ) + self...
When the cursor changes in the history buffer . Synchronize .
16,327
def python_sidebar ( python_input ) : def get_text_fragments ( ) : tokens = [ ] def append_category ( category ) : tokens . extend ( [ ( 'class:sidebar' , ' ' ) , ( 'class:sidebar.title' , ' %-36s' % category . title ) , ( 'class:sidebar' , '\n' ) , ] ) def append ( index , label , status ) : selected = index == pyt...
Create the Layout for the sidebar with the configurable options .
16,328
def python_sidebar_navigation ( python_input ) : def get_text_fragments ( ) : tokens = [ ] tokens . extend ( [ ( 'class:sidebar' , ' ' ) , ( 'class:sidebar.key' , '[Arrows]' ) , ( 'class:sidebar' , ' ' ) , ( 'class:sidebar.description' , 'Navigate' ) , ( 'class:sidebar' , ' ' ) , ( 'class:sidebar.key' , '[Enter]' ) ...
Create the Layout showing the navigation information for the sidebar .
16,329
def python_sidebar_help ( python_input ) : token = 'class:sidebar.helptext' def get_current_description ( ) : i = 0 for category in python_input . options : for option in category . options : if i == python_input . selected_option_index : return option . description i += 1 return '' def get_help_text ( ) : return [ ( t...
Create the Layout for the help text for the current item in the sidebar .
16,330
def signature_toolbar ( python_input ) : def get_text_fragments ( ) : result = [ ] append = result . append Signature = 'class:signature-toolbar' if python_input . signatures : sig = python_input . signatures [ 0 ] append ( ( Signature , ' ' ) ) try : append ( ( Signature , sig . full_name ) ) except IndexError : retur...
Return the Layout for the signature .
16,331
def status_bar ( python_input ) : TB = 'class:status-toolbar' @ if_mousedown def toggle_paste_mode ( mouse_event ) : python_input . paste_mode = not python_input . paste_mode @ if_mousedown def enter_history ( mouse_event ) : python_input . enter_history ( ) def get_text_fragments ( ) : python_buffer = python_input . d...
Create the Layout for the status bar .
16,332
def exit_confirmation ( python_input , style = 'class:exit-confirmation' ) : def get_text_fragments ( ) : return [ ( style , '\n %s ([y]/n)' % python_input . exit_message ) , ( '[SetCursorPosition]' , '' ) , ( style , ' \n' ) , ] visible = ~ is_done & Condition ( lambda : python_input . show_exit_confirmation ) return...
Create Layout for the exit message .
16,333
def meta_enter_message ( python_input ) : def get_text_fragments ( ) : return [ ( 'class:accept-message' , ' [Meta+Enter] Execute ' ) ] def extra_condition ( ) : " Only show when... " b = python_input . default_buffer return ( python_input . show_meta_enter_message and ( not b . document . is_cursor_at_the_end or pytho...
Create the Layout for the Meta + Enter message .
16,334
def activate_next ( self , _previous = False ) : current = self . get_current_value ( ) options = sorted ( self . values . keys ( ) ) try : index = options . index ( current ) except ValueError : index = 0 if _previous : index -= 1 else : index += 1 next_option = options [ index % len ( options ) ] self . values [ next...
Activate next value .
16,335
def selected_option ( self ) : " Return the currently selected option. " i = 0 for category in self . options : for o in category . options : if i == self . selected_option_index : return o else : i += 1
Return the currently selected option .
16,336
def get_compiler_flags ( self ) : flags = 0 for value in self . get_globals ( ) . values ( ) : if isinstance ( value , __future__ . _Feature ) : flags |= value . compiler_flag return flags
Give the current compiler flags by looking for _Feature instances in the globals .
16,337
def install_code_colorscheme ( self , name , style_dict ) : assert isinstance ( name , six . text_type ) assert isinstance ( style_dict , dict ) self . code_styles [ name ] = style_dict
Install a new code color scheme .
16,338
def install_ui_colorscheme ( self , name , style_dict ) : assert isinstance ( name , six . text_type ) assert isinstance ( style_dict , dict ) self . ui_styles [ name ] = style_dict
Install a new UI color scheme .
16,339
def _create_application ( self ) : return Application ( input = self . input , output = self . output , layout = self . ptpython_layout . layout , key_bindings = merge_key_bindings ( [ load_python_bindings ( self ) , load_auto_suggest_bindings ( ) , load_sidebar_bindings ( self ) , load_confirm_exit_bindings ( self ) ,...
Create an Application instance .
16,340
def _create_buffer ( self ) : python_buffer = Buffer ( name = DEFAULT_BUFFER , complete_while_typing = Condition ( lambda : self . complete_while_typing ) , enable_history_search = Condition ( lambda : self . enable_history_search ) , tempfile_suffix = '.py' , history = self . history , completer = ThreadedCompleter ( ...
Create the Buffer for the Python input .
16,341
def _on_input_timeout ( self , buff ) : assert isinstance ( buff , Buffer ) app = self . app if self . _get_signatures_thread_running : return self . _get_signatures_thread_running = True document = buff . document def run ( ) : script = get_jedi_script_from_document ( document , self . get_locals ( ) , self . get_glob...
When there is no input activity in another thread get the signature of the current code .
16,342
def enter_history ( self ) : app = get_app ( ) app . vi_state . input_mode = InputMode . NAVIGATION def done ( f ) : result = f . result ( ) if result is not None : self . default_buffer . text = result app . vi_state . input_mode = InputMode . INSERT history = History ( self , self . default_buffer . document ) future...
Display the history .
16,343
def get_all_code_styles ( ) : result = dict ( ( name , style_from_pygments_cls ( get_style_by_name ( name ) ) ) for name in get_all_styles ( ) ) result [ 'win32' ] = Style . from_dict ( win32_code_style ) return result
Return a mapping from style names to their classes .
16,344
def initialize_extensions ( shell , extensions ) : try : iter ( extensions ) except TypeError : pass else : for ext in extensions : try : shell . extension_manager . load_extension ( ext ) except : ipy_utils . warn . warn ( "Error in loading extension: %s" % ext + "\nCheck your config files in %s" % ipy_utils . path . ...
Partial copy of InteractiveShellApp . init_extensions from IPython .
16,345
def paths_for_download ( self ) : if self . _paths_for_download is None : queries = list ( ) try : for sra in self . gsm . relations [ 'SRA' ] : query = sra . split ( "=" ) [ - 1 ] if 'SRX' not in query : raise ValueError ( "Sample looks like it is not an SRA: %s" % query ) logger . info ( "Query: %s" % query ) queries...
List of URLs available for downloading .
16,346
def download ( self ) : self . downloaded_paths = list ( ) for path in self . paths_for_download : downloaded_path = list ( ) utils . mkdir_p ( os . path . abspath ( self . directory ) ) sra_run = path . split ( "/" ) [ - 1 ] logger . info ( "Analysing %s" % sra_run ) url = type ( self ) . FTP_ADDRESS_TPL . format ( ra...
Download SRA files .
16,347
def add_log_file ( path ) : logfile_handler = RotatingFileHandler ( path , maxBytes = 50000 , backupCount = 2 ) formatter = logging . Formatter ( fmt = '%(asctime)s %(levelname)s %(module)s - %(message)s' , datefmt = "%d-%b-%Y %H:%M:%S" ) logfile_handler . setFormatter ( formatter ) geoparse_logger . addHandler ( logfi...
Add log file .
16,348
def _sra_download_worker ( * args ) : gsm = args [ 0 ] [ 0 ] email = args [ 0 ] [ 1 ] dirpath = args [ 0 ] [ 2 ] kwargs = args [ 0 ] [ 3 ] return ( gsm . get_accession ( ) , gsm . download_SRA ( email , dirpath , ** kwargs ) )
A worker to download SRA files .
16,349
def _supplementary_files_download_worker ( * args ) : gsm = args [ 0 ] [ 0 ] download_sra = args [ 0 ] [ 1 ] email = args [ 0 ] [ 2 ] dirpath = args [ 0 ] [ 3 ] sra_kwargs = args [ 0 ] [ 4 ] return ( gsm . get_accession ( ) , gsm . download_supplementary_files ( directory = dirpath , download_sra = download_sra , email...
A worker to download supplementary files .
16,350
def get_metadata_attribute ( self , metaname ) : metadata_value = self . metadata . get ( metaname , None ) if metadata_value is None : raise NoMetadataException ( "No metadata attribute named %s" % metaname ) if not isinstance ( metadata_value , list ) : raise TypeError ( "Metadata is not a list and it should be." ) i...
Get the metadata attribute by the name .
16,351
def _get_metadata_as_string ( self ) : metalist = [ ] for metaname , meta in iteritems ( self . metadata ) : message = "Single value in metadata dictionary should be a list!" assert isinstance ( meta , list ) , message for data in meta : if data : metalist . append ( "!%s_%s = %s" % ( self . geotype . capitalize ( ) , ...
Get the metadata as SOFT formatted string .
16,352
def to_soft ( self , path_or_handle , as_gzip = False ) : if isinstance ( path_or_handle , str ) : if as_gzip : with gzip . open ( path_or_handle , 'wt' ) as outfile : outfile . write ( self . _get_object_as_soft ( ) ) else : with open ( path_or_handle , 'w' ) as outfile : outfile . write ( self . _get_object_as_soft (...
Save the object in a SOFT format .
16,353
def head ( self ) : summary = list ( ) summary . append ( "%s %s" % ( self . geotype , self . name ) + "\n" ) summary . append ( " - Metadata:" + "\n" ) summary . append ( "\n" . join ( self . _get_metadata_as_string ( ) . split ( "\n" ) [ : 5 ] ) + "\n" ) summary . append ( "\n" ) summary . append ( " - Columns:" + "\...
Print short description of the object .
16,354
def _get_object_as_soft ( self ) : soft = [ "^%s = %s" % ( self . geotype , self . name ) , self . _get_metadata_as_string ( ) , self . _get_columns_as_string ( ) , self . _get_table_as_string ( ) ] return "\n" . join ( soft )
Get the object as SOFT formated string .
16,355
def _get_table_as_string ( self ) : tablelist = [ ] tablelist . append ( "!%s_table_begin" % self . geotype . lower ( ) ) tablelist . append ( "\t" . join ( self . table . columns ) ) for idx , row in self . table . iterrows ( ) : tablelist . append ( "\t" . join ( map ( str , row ) ) ) tablelist . append ( "!%s_table_...
Get table as SOFT formated string .
16,356
def _get_columns_as_string ( self ) : columnslist = [ ] for rowidx , row in self . columns . iterrows ( ) : columnslist . append ( "#%s = %s" % ( rowidx , row . description ) ) return "\n" . join ( columnslist )
Returns columns as SOFT formated string .
16,357
def annotate ( self , gpl , annotation_column , gpl_on = "ID" , gsm_on = "ID_REF" , in_place = False ) : if isinstance ( gpl , GPL ) : annotation_table = gpl . table elif isinstance ( gpl , DataFrame ) : annotation_table = gpl else : raise TypeError ( "gpl should be a GPL object or a pandas.DataFrame" ) annotated = sel...
Annotate GSM with provided GPL
16,358
def annotate_and_average ( self , gpl , expression_column , group_by_column , rename = True , force = False , merge_on_column = None , gsm_on = None , gpl_on = None ) : if gpl . name != self . metadata [ 'platform_id' ] [ 0 ] and not force : raise KeyError ( "Platforms from GSM (%s) and from GPL (%s)" % ( gpl . name , ...
Annotate GSM table with provided GPL .
16,359
def download_supplementary_files ( self , directory = "./" , download_sra = True , email = None , sra_kwargs = None ) : directory_path = os . path . abspath ( os . path . join ( directory , "%s_%s_%s" % ( 'Supp' , self . get_accession ( ) , re . sub ( r'[\s\*\?\(\),\.;]' , '_' , self . metadata [ 'title' ] [ 0 ] ) ) ) ...
Download all supplementary data available for the sample .
16,360
def download_SRA ( self , email , directory = './' , ** kwargs ) : downloader = SRADownloader ( self , email , directory , ** kwargs ) return { "SRA" : downloader . download ( ) }
Download RAW data as SRA file .
16,361
def _get_object_as_soft ( self ) : soft = [ "^%s = %s" % ( self . geotype , self . name ) , self . _get_metadata_as_string ( ) ] return "\n" . join ( soft )
Get the object as SOFT formatted string .
16,362
def _get_object_as_soft ( self ) : soft = [ ] if self . database is not None : soft . append ( self . database . _get_object_as_soft ( ) ) soft += [ "^%s = %s" % ( self . geotype , self . name ) , self . _get_metadata_as_string ( ) ] for subset in self . subsets . values ( ) : soft . append ( subset . _get_object_as_so...
Return object as SOFT formatted string .
16,363
def phenotype_data ( self ) : if self . _phenotype_data is None : pheno_data = { } for gsm_name , gsm in iteritems ( self . gsms ) : tmp = { } for key , value in iteritems ( gsm . metadata ) : if len ( value ) == 0 : tmp [ key ] = np . nan elif key . startswith ( "characteristics_" ) : for i , char in enumerate ( value...
Get the phenotype data for each of the sample .
16,364
def merge_and_average ( self , platform , expression_column , group_by_column , force = False , merge_on_column = None , gsm_on = None , gpl_on = None ) : if isinstance ( platform , str ) : gpl = self . gpls [ platform ] elif isinstance ( platform , GPL ) : gpl = platform else : raise ValueError ( "Platform has to be o...
Merge and average GSE samples .
16,365
def pivot_samples ( self , values , index = "ID_REF" ) : data = [ ] for gsm in self . gsms . values ( ) : tmp_data = gsm . table . copy ( ) tmp_data [ "name" ] = gsm . name data . append ( tmp_data ) ndf = concat ( data ) . pivot ( index = index , values = values , columns = "name" ) return ndf
Pivot samples by specified column .
16,366
def pivot_and_annotate ( self , values , gpl , annotation_column , gpl_on = "ID" , gsm_on = "ID_REF" ) : if isinstance ( gpl , GPL ) : annotation_table = gpl . table elif isinstance ( gpl , DataFrame ) : annotation_table = gpl else : raise TypeError ( "gpl should be a GPL object or a pandas.DataFrame" ) pivoted_samples...
Annotate GSM with provided GPL .
16,367
def download_supplementary_files ( self , directory = 'series' , download_sra = True , email = None , sra_kwargs = None , nproc = 1 ) : if sra_kwargs is None : sra_kwargs = dict ( ) if directory == 'series' : dirpath = os . path . abspath ( self . get_accession ( ) + "_Supp" ) utils . mkdir_p ( dirpath ) else : dirpath...
Download supplementary data .
16,368
def download_SRA ( self , email , directory = 'series' , filterby = None , nproc = 1 , ** kwargs ) : if directory == 'series' : dirpath = os . path . abspath ( self . get_accession ( ) + "_SRA" ) utils . mkdir_p ( dirpath ) else : dirpath = os . path . abspath ( directory ) utils . mkdir_p ( dirpath ) if filterby is no...
Download SRA files for each GSM in series .
16,369
def _get_object_as_soft ( self ) : soft = [ ] if self . database is not None : soft . append ( self . database . _get_object_as_soft ( ) ) soft += [ "^%s = %s" % ( self . geotype , self . name ) , self . _get_metadata_as_string ( ) ] for gsm in itervalues ( self . gsms ) : soft . append ( gsm . _get_object_as_soft ( ) ...
Get object as SOFT formatted string .
16,370
def destination ( self ) : return os . path . join ( os . path . abspath ( self . outdir ) , self . filename )
Get the destination path .
16,371
def download ( self , force = False , silent = False ) : def _download ( ) : if self . url . startswith ( "http" ) : self . _download_http ( silent = silent ) elif self . url . startswith ( "ftp" ) : self . _download_ftp ( silent = silent ) else : raise ValueError ( "Invalid URL %s" % self . url ) logger . debug ( "Mov...
Download from URL .
16,372
def download_aspera ( self , user , host , silent = False ) : aspera_home = os . environ . get ( "ASPERA_HOME" , None ) if not aspera_home : raise ValueError ( "environment variable $ASPERA_HOME not set" ) if not os . path . exists ( aspera_home ) : raise ValueError ( "$ASPERA_HOME directory {} does not exist" . format...
Download file with Aspera Connect .
16,373
def md5sum ( filename , blocksize = 8192 ) : with open ( filename , 'rb' ) as fh : m = hashlib . md5 ( ) while True : data = fh . read ( blocksize ) if not data : break m . update ( data ) return m . hexdigest ( )
Get the MD5 checksum of a file .
16,374
def get_GEO ( geo = None , filepath = None , destdir = "./" , how = 'full' , annotate_gpl = False , geotype = None , include_data = False , silent = False , aspera = False , partial = None ) : if geo is None and filepath is None : raise Exception ( "You have to specify filename or GEO accession!" ) if geo is not None a...
Get the GEO entry .
16,375
def parse_metadata ( lines ) : meta = defaultdict ( list ) for line in lines : line = line . rstrip ( ) if line . startswith ( "!" ) : if "_table_begin" in line or "_table_end" in line : continue key , value = __parse_entry ( line ) meta [ key ] . append ( value ) return dict ( meta )
Parse list of lines with metadata information from SOFT file .
16,376
def parse_columns ( lines ) : data = [ ] index = [ ] for line in lines : line = line . rstrip ( ) if line . startswith ( "#" ) : tmp = __parse_entry ( line ) data . append ( tmp [ 1 ] ) index . append ( tmp [ 0 ] ) return DataFrame ( data , index = index , columns = [ 'description' ] )
Parse list of lines with columns description from SOFT file .
16,377
def parse_GDS_columns ( lines , subsets ) : data = [ ] index = [ ] for line in lines : line = line . rstrip ( ) if line . startswith ( "#" ) : tmp = __parse_entry ( line ) data . append ( tmp [ 1 ] ) index . append ( tmp [ 0 ] ) df = DataFrame ( data , index = index , columns = [ 'description' ] ) subset_ids = defaultd...
Parse list of line with columns description from SOFT file of GDS .
16,378
def parse_table_data ( lines ) : data = "\n" . join ( [ i . rstrip ( ) for i in lines if not i . startswith ( ( "^" , "!" , "#" ) ) and i . rstrip ( ) ] ) if data : return read_csv ( StringIO ( data ) , index_col = None , sep = "\t" ) else : return DataFrame ( )
Parse list of lines from SOFT file into DataFrame .
16,379
def parse_GSM ( filepath , entry_name = None ) : if isinstance ( filepath , str ) : with utils . smart_open ( filepath ) as f : soft = [ ] has_table = False for line in f : if "_table_begin" in line or ( not line . startswith ( ( "^" , "!" , "#" ) ) ) : has_table = True soft . append ( line . rstrip ( ) ) else : soft =...
Parse GSM entry from SOFT file .
16,380
def parse_GPL ( filepath , entry_name = None , partial = None ) : gsms = { } gses = { } gpl_soft = [ ] has_table = False gpl_name = entry_name database = None if isinstance ( filepath , str ) : with utils . smart_open ( filepath ) as soft : groupper = groupby ( soft , lambda x : x . startswith ( "^" ) ) for is_new_entr...
Parse GPL entry from SOFT file .
16,381
def parse_GSE ( filepath ) : gpls = { } gsms = { } series_counter = 0 database = None metadata = { } gse_name = None with utils . smart_open ( filepath ) as soft : groupper = groupby ( soft , lambda x : x . startswith ( "^" ) ) for is_new_entry , group in groupper : if is_new_entry : entry_type , entry_name = __parse_e...
Parse GSE SOFT file .
16,382
def parse_GDS ( filepath ) : dataset_lines = [ ] subsets = { } database = None dataset_name = None with utils . smart_open ( filepath ) as soft : groupper = groupby ( soft , lambda x : x . startswith ( "^" ) ) for is_new_entry , group in groupper : if is_new_entry : entry_type , entry_name = __parse_entry ( next ( grou...
Parse GDS SOFT file .
16,383
def download_from_url ( url , destination_path , force = False , aspera = False , silent = False ) : if aspera and url . startswith ( "http" ) : logger . warn ( "Aspera Connect allows only FTP servers - falling back to " "normal download" ) aspera = False try : fn = Downloader ( url , outdir = os . path . dirname ( des...
Download file from remote server .
16,384
def smart_open ( filepath ) : if filepath [ - 2 : ] == "gz" : mode = "rt" fopen = gzip . open else : mode = "r" fopen = open if sys . version_info [ 0 ] < 3 : fh = fopen ( filepath , mode ) else : fh = fopen ( filepath , mode , errors = "ignore" ) try : yield fh except IOError : fh . close ( ) finally : fh . close ( )
Open file intelligently depending on the source and python version .
16,385
def bandit ( self , choice_rewards ) : return max ( choice_rewards , key = lambda a : np . mean ( choice_rewards [ a ] ) )
Return the choice to take next using multi - armed bandit
16,386
def select ( self , choice_scores ) : choice_rewards = { } for choice , scores in choice_scores . items ( ) : if choice not in self . choices : continue choice_rewards [ choice ] = self . compute_rewards ( scores ) return self . bandit ( choice_rewards )
Select the next best choice to make
16,387
def compute_rewards ( self , scores ) : if len ( scores ) > self . k : scores = np . copy ( scores ) inds = np . argsort ( scores ) [ : - self . k ] scores [ inds ] = np . nan return list ( scores )
Retain the K best scores and replace the rest with nans
16,388
def compute_rewards ( self , scores ) : k = self . k m = max ( len ( scores ) - k , 0 ) best_scores = sorted ( scores ) [ - k - 1 : ] velocities = np . diff ( best_scores ) nans = np . full ( m , np . nan ) return list ( velocities ) + list ( nans )
Compute the velocity of the best scores
16,389
def predict ( self , X ) : if np . random . random ( ) < self . POU : return Uniform ( self . tunables ) . predict ( X ) return super ( GPEiVelocity , self ) . predict ( X )
Use the POU value we computed in fit to choose randomly between GPEi and uniform random selection .
16,390
def compute_rewards ( self , scores ) : for i in range ( len ( scores ) ) : if i >= self . k : scores [ i ] = 0. return scores
Retain the K most recent scores and replace the rest with zeros
16,391
def select ( self , choice_scores ) : min_num_scores = min ( [ len ( s ) for s in choice_scores . values ( ) ] ) if min_num_scores >= K_MIN : logger . info ( '{klass}: using Best K bandit selection' . format ( klass = type ( self ) . __name__ ) ) reward_func = self . compute_rewards else : logger . warning ( '{klass}: ...
Use the top k learner s scores for usage in rewards for the bandit calculation
16,392
def compute_rewards ( self , scores ) : recent_scores = scores [ : - self . k - 2 : - 1 ] velocities = [ recent_scores [ i ] - recent_scores [ i + 1 ] for i in range ( len ( recent_scores ) - 1 ) ] zeros = ( len ( scores ) - self . k ) * [ 0 ] return velocities + zeros
Compute the velocity of thte k + 1 most recent scores .
16,393
def select ( self , choice_scores ) : alg_scores = { } for algorithm , choices in self . by_algorithm . items ( ) : if not set ( choices ) & set ( choice_scores . keys ( ) ) : continue sublists = [ choice_scores . get ( c , [ ] ) for c in choices ] alg_scores [ algorithm ] = sum ( sublists , [ ] ) best_algorithm = self...
Groups the frozen sets by algorithm and first chooses an algorithm based on the traditional UCB1 criteria .
16,394
def _generate_grid ( self ) : grid_axes = [ ] for _ , param in self . tunables : grid_axes . append ( param . get_grid_axis ( self . grid_width ) ) return grid_axes
Get the all possible values for each of the tunables .
16,395
def _candidates_from_grid ( self , n = 1000 ) : used_vectors = set ( tuple ( v ) for v in self . X ) grid_size = self . grid_width ** len ( self . tunables ) if len ( used_vectors ) == grid_size : return None all_vectors = set ( itertools . product ( * self . _grid_axes ) ) remaining_vectors = all_vectors - used_vector...
Get unused candidates from the grid or parameters .
16,396
def _random_candidates ( self , n = 1000 ) : candidates = np . zeros ( ( n , len ( self . tunables ) ) ) for i , tunable in enumerate ( self . tunables ) : param = tunable [ 1 ] lo , hi = param . range if param . is_integer : column = np . random . randint ( lo , hi + 1 , size = n ) else : diff = hi - lo column = lo + ...
Generate a matrix of random parameters column by column .
16,397
def _create_candidates ( self , n = 1000 ) : if self . grid : return self . _candidates_from_grid ( n ) else : return self . _random_candidates ( n )
Generate random hyperparameter vectors
16,398
def propose ( self , n = 1 ) : proposed_params = [ ] for i in range ( n ) : candidate_params = self . _create_candidates ( ) if candidate_params is None : return None predictions = self . predict ( candidate_params ) idx = self . _acquire ( predictions ) params = { } for i in range ( candidate_params [ idx , : ] . shap...
Use the trained model to propose a new set of parameters .
16,399
def add ( self , X , y ) : if isinstance ( X , dict ) : X = [ X ] y = [ y ] for i in range ( len ( X ) ) : each = X [ i ] if y [ i ] > self . _best_score : self . _best_score = y [ i ] self . _best_hyperparams = X [ i ] vectorized = [ ] for tunable in self . tunables : vectorized . append ( each [ tunable [ 0 ] ] ) if ...
Add data about known tunable hyperparameter configurations and scores .