code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
output = self.app.output # WORKAROUND: Due to a bug in Jedi, the current directory is removed # from sys.path. See: https://github.com/davidhalter/jedi/issues/1148 if '' not in sys.path: sys.path.insert(0, '') def compile_with_flags(code, mode): ...
def _execute(self, line)
Evaluate the line and print the result.
4.202765
4.16693
1.0086
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: # Stop the loop when quitting the repl. (Ctrl-D press.) loop.stop()
def interactive_shell()
Coroutine that starts a Python REPL from which we can access the global counter variable.
15.154915
11.96568
1.266532
# When the input starts with Ctrl-Z, always accept. This means EOF in a # Python REPL. if document.text.startswith('\x1a'): return try: if self.get_compiler_flags: flags = self.get_compiler_flags() else: flags ...
def validate(self, document)
Check input for Python syntax errors.
5.947856
5.72693
1.038577
loop = asyncio.get_event_loop() # Namespace exposed in the REPL. environ = {'hello': 'world'} # Start SSH server. def create_server(): return MySSHServer(lambda: environ) print('Listening on :%i' % port) print('To connect, do "ssh localhost -p %i"' % port) loop.run_until...
def main(port=8222)
Example that starts the REPL through an SSH server.
4.664809
4.336269
1.075765
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)
def _get_size(self)
Callable that returns the current `Size`, required by Vt100_Output.
5.576731
4.731663
1.178599
self._chan = chan # Run REPL interface. f = asyncio.ensure_future(self.cli.run_async()) # Close channel when done. def done(_): chan.close() self._chan = None f.add_done_callback(done)
def connection_made(self, chan)
Client connected, run repl in coroutine.
5.430538
4.29355
1.264813
# Pop keyword-only arguments. (We cannot use the syntax from the # signature. Otherwise, Python2 will give a syntax error message when # installing.) sep = kw.pop('sep', ' ') end = kw.pop('end', '\n') _ = kw.pop('file', None) assert not kw, 'Too many keyw...
def _print(self, *data, **kw)
_print(self, *data, sep=' ', end='\n', file=None) Alternative 'print' function that prints back into the SSH channel.
6.632292
5.913162
1.121615
# Show function signature (bool). repl.show_signature = True # Show docstring (bool). repl.show_docstring = False # Show the "[Meta+Enter] Execute" message when pressing [Enter] only # inserts a newline instead of executing the code. repl.show_meta_enter_message = True # Show com...
def configure(repl)
Configuration method. This is called during the start-up of ptpython. :param repl: `PythonRepl` instance.
6.052944
6.022914
1.004986
stack = [] # Ignore braces inside strings text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.! for c in reversed(text): if c in '])}': stack.append(c) elif c in '[({': if stack: if ((c == '[' and stack[-1] == ']...
def has_unclosed_brackets(text)
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.
4.092711
3.548954
1.153216
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(ope...
def document_is_multiline_python(document)
Determine whether this is a multiline Python document.
4.572184
4.534418
1.008329
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
def if_mousedown(handler)
Decorator for mouse handlers. Only handle event when the user pressed mouse down. (When applied to a token list. Scroll events will bubble up and are handled by the Window.)
3.120546
3.180227
0.981234
assert isinstance(title, six.text_type) assert isinstance(body, Container) return Frame(body=body, title=title)
def _create_popup_window(title, body)
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.
5.557076
4.882661
1.138124
" Display/hide help. " help_buffer_control = history.history_layout.help_buffer_control if history.app.layout.current_control == help_buffer_control: history.app.layout.focus_previous() else: history.app.layout.current_control = help_buffer_control
def _toggle_help(history)
Display/hide help.
5.04454
4.760245
1.059723
" Toggle focus between left/right window. " current_buffer = history.app.current_buffer layout = history.history_layout.layout if current_buffer == history.history_buffer: layout.current_control = history.history_layout.default_buffer_control elif current_buffer == history.default_buffer: ...
def _select_other_window(history)
Toggle focus between left/right window.
5.216813
4.164633
1.252646
bindings = KeyBindings() handle = bindings.add @handle(' ', filter=has_focus(history.history_buffer)) def _(event): b = event.current_buffer line_no = b.document.cursor_position_row if not history_mapping.history_lines: # If we've no history, then noth...
def create_key_bindings(history, python_input, history_mapping)
Key bindings.
2.570587
2.564332
1.002439
lines = [] # Original text, before cursor. if self.original_document.text_before_cursor: lines.append(self.original_document.text_before_cursor) # Selected entries from the history. for line_no in sorted(self.selected_lines): lines.append(self.h...
def get_new_document(self, cursor_pos=None)
Create a `Document` instance that contains the resulting text.
2.692167
2.522369
1.067317
# Only when this buffer has the focus. 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: # When the curs...
def _default_buffer_pos_changed(self, _)
When the cursor changes in the default buffer. Synchronize with history buffer.
4.555064
3.908192
1.165517
# Only when this buffer has the focus. 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_...
def _history_buffer_pos_changed(self, _)
When the cursor changes in the history buffer. Synchronize.
3.982614
3.653438
1.0901
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, lab...
def python_sidebar(python_input)
Create the `Layout` for the sidebar with the configurable options.
3.159056
3.148055
1.003495
def get_text_fragments(): tokens = [] # Show navigation info. tokens.extend([ ('class:sidebar', ' '), ('class:sidebar.key', '[Arrows]'), ('class:sidebar', ' '), ('class:sidebar.description', 'Navigate'), ('class:sidebar', '...
def python_sidebar_navigation(python_input)
Create the `Layout` showing the navigation information for the sidebar.
4.056671
3.963181
1.02359
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 ...
def python_sidebar_help(python_input)
Create the `Layout` for the help text for the current item in the sidebar.
5.206222
4.947896
1.052209
def get_text_fragments(): result = [] append = result.append Signature = 'class:signature-toolbar' if python_input.signatures: sig = python_input.signatures[0] # Always take the first one. append((Signature, ' ')) try: appen...
def signature_toolbar(python_input)
Return the `Layout` for the signature.
4.974069
4.952023
1.004452
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.de...
def status_bar(python_input)
Create the `Layout` for the status bar.
4.249987
4.18198
1.016262
app = get_app() @if_mousedown def toggle_vi_mode(mouse_event): python_input.vi_mode = not python_input.vi_mode token = 'class:status-toolbar' input_mode_t = 'class:status-toolbar.input-mode' mode = app.vi_state.input_mode result = [] append = result.append append((inp...
def get_inputmode_fragments(python_input)
Return current input mode as a list of (token, text) tuples for use in a toolbar.
2.918093
2.873632
1.015472
@if_mousedown def toggle_sidebar(mouse_event): " Click handler for the menu. " python_input.show_sidebar = not python_input.show_sidebar version = sys.version_info tokens = [ ('class:status-toolbar.key', '[F2]', toggle_sidebar), ('class:status-toolbar', ' Menu', tog...
def show_sidebar_button_info(python_input)
Create `Layout` for the information in the right-bottom corner. (The right part of the status bar.)
5.213252
5.188269
1.004815
def get_text_fragments(): # Show "Do you really want to exit?" return [ (style, '\n %s ([y]/n)' % python_input.exit_message), ('[SetCursorPosition]', ''), (style, ' \n'), ] visible = ~is_done & Condition(lambda: python_input.show_exit_confirmati...
def exit_confirmation(python_input, style='class:exit-confirmation')
Create `Layout` for the exit message.
8.420066
8.057019
1.04506
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...
def meta_enter_message(python_input)
Create the `Layout` for the 'Meta+Enter` message.
9.058618
8.223422
1.101563
current = self.get_current_value() options = sorted(self.values.keys()) # Get current index. try: index = options.index(current) except ValueError: index = 0 # Go to previous/next index. if _previous: index -= 1 ...
def activate_next(self, _previous=False)
Activate next value.
3.178459
2.914822
1.090447
" 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
def selected_option(self)
Return the currently selected option.
4.326099
4.526778
0.955669
flags = 0 for value in self.get_globals().values(): if isinstance(value, __future__._Feature): flags |= value.compiler_flag return flags
def get_compiler_flags(self)
Give the current compiler flags by looking for _Feature instances in the globals.
7.489508
5.058901
1.480461
def add_binding_decorator(*k, **kw): return self.extra_key_bindings.add(*k, **kw) return add_binding_decorator
def add_key_binding(self)
Shortcut for adding new key bindings. (Mostly useful for a .ptpython/config.py file, that receives a PythonInput/Repl instance as input.) :: @python_input.add_key_binding(Keys.ControlX, filter=...) def handler(event): ...
7.010359
7.47083
0.938364
assert isinstance(name, six.text_type) assert isinstance(style_dict, dict) self.code_styles[name] = style_dict
def install_code_colorscheme(self, name, style_dict)
Install a new code color scheme.
3.151906
3.216078
0.980046
assert name in self.code_styles self._current_code_style_name = name self._current_style = self._generate_style()
def use_code_colorscheme(self, name)
Apply new colorscheme. (By name.)
6.113595
6.137313
0.996136
assert isinstance(name, six.text_type) assert isinstance(style_dict, dict) self.ui_styles[name] = style_dict
def install_ui_colorscheme(self, name, style_dict)
Install a new UI color scheme.
3.189935
3.261793
0.97797
assert name in self.ui_styles self._current_ui_style_name = name self._current_style = self._generate_style()
def use_ui_colorscheme(self, name)
Apply new colorscheme. (By name.)
5.893028
6.069781
0.97088
return generate_style(self.code_styles[self._current_code_style_name], self.ui_styles[self._current_ui_style_name])
def _generate_style(self)
Create new Style instance. (We don't want to do this on every key press, because each time the renderer receives a new style class, he will redraw everything.)
5.829769
4.462026
1.30653
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...
def _create_application(self)
Create an `Application` instance.
3.975734
3.904855
1.018151
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, com...
def _create_buffer(self)
Create the `Buffer` for the Python input.
4.072925
3.63158
1.12153
assert isinstance(buff, Buffer) app = self.app # Never run multiple get-signature threads. if self._get_signatures_thread_running: return self._get_signatures_thread_running = True document = buff.document def run(): script = ge...
def _on_input_timeout(self, buff)
When there is no input activity, in another thread, get the signature of the current code.
4.94421
4.828297
1.024007
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...
def enter_history(self)
Display the history.
4.699324
4.509868
1.042009
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
def get_all_code_styles()
Return a mapping from style names to their classes.
4.14311
3.731405
1.110335
try: iter(extensions) except TypeError: pass # no extensions found else: for ext in extensions: try: shell.extension_manager.load_extension(ext) except: ipy_utils.warn.warn( "Error in loading extension:...
def initialize_extensions(shell, extensions)
Partial copy of `InteractiveShellApp.init_extensions` from IPython.
4.448858
4.269228
1.042076
config = kwargs.get('config') header = kwargs.pop('header', u'') compile_flags = kwargs.pop('compile_flags', None) if config is None: config = load_default_config() config.InteractiveShellEmbed = config.TerminalInteractiveShell kwargs['config'] = config shell = Interacti...
def embed(**kwargs)
Copied from `IPython/terminal/embed.py`, but using our `InteractiveShellEmbed` instead.
4.696779
3.607455
1.301965
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( "Sampl...
def paths_for_download(self)
List of URLs available for downloading.
2.999347
2.959448
1.013482
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_ADDRE...
def download(self)
Download SRA files. Returns: :obj:`list` of :obj:`str`: List of downloaded files.
2.827763
2.80528
1.008014
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(logfile_handle...
def add_log_file(path)
Add log file. Args: path (:obj:`str`): Path to the log file.
2.3139
2.705752
0.855178
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))
def _sra_download_worker(*args)
A worker to download SRA files. To be used with multiprocessing.
3.725698
3.830533
0.972632
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=email, **sra_kwargs))
def _supplementary_files_download_worker(*args)
A worker to download supplementary files. To be used with multiprocessing.
3.357725
3.536678
0.949401
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...
def get_metadata_attribute(self, metaname)
Get the metadata attribute by the name. Args: metaname (:obj:`str`): Name of the attribute Returns: :obj:`list` or :obj:`str`: Value(s) of the requested metadata attribute Raises: NoMetadataException: Attribute error TypeError: M...
2.659908
2.535741
1.048967
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"...
def _get_metadata_as_string(self)
Get the metadata as SOFT formatted string.
5.864539
5.510955
1.06416
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....
def to_soft(self, path_or_handle, as_gzip=False)
Save the object in a SOFT format. Args: path_or_handle (:obj:`str` or :obj:`file`): Path or handle to output file as_gzip (:obj:`bool`): Save as gzip
1.791382
1.762982
1.016109
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:" + "\n...
def head(self)
Print short description of the object.
2.260587
2.217591
1.019389
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)
def _get_object_as_soft(self)
Get the object as SOFT formated string.
5.486907
4.408001
1.244761
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_end" % self.geotype.lower()...
def _get_table_as_string(self)
Get table as SOFT formated string.
2.942852
2.778403
1.059188
columnslist = [] for rowidx, row in self.columns.iterrows(): columnslist.append("#%s = %s" % (rowidx, row.description)) return "\n".join(columnslist)
def _get_columns_as_string(self)
Returns columns as SOFT formated string.
5.105977
4.380479
1.165621
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") # annotate by merging annotated = self.table.merge...
def annotate(self, gpl, annotation_column, gpl_on="ID", gsm_on="ID_REF", in_place=False)
Annotate GSM with provided GPL Args: gpl (:obj:`pandas.DataFrame`): A Platform or DataFrame to annotate with annotation_column (str`): Column in a table for annotation gpl_on (:obj:`str`): Use this column in GSM to merge. Defaults to "ID". gsm_on (:obj:`str`): Us...
2.822875
2.765684
1.020678
if gpl.name != self.metadata['platform_id'][0] and not force: raise KeyError("Platforms from GSM (%s) and from GPL (%s)" % ( gpl.name, self.metadata['platform_id']) + " are incompatible. Use force=True to use this GPL.") if merge_on_column ...
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)
Annotate GSM table with provided GPL. Args: gpl (:obj:`GEOTypes.GPL`): Platform for annotations expression_column (:obj:`str`): Column name which "expressions" are represented group_by_column (:obj:`str`): The data will be grouped and averaged ...
2.635067
2.443905
1.07822
directory_path = os.path.abspath( os.path.join(directory, "%s_%s_%s" % ( 'Supp', self.get_accession(), # the directory name cannot contain many of the signs re.sub(r'[\s\*\?\(\),\.;]', '_', self.metadata['title'][0])))) ...
def download_supplementary_files(self, directory="./", download_sra=True, email=None, sra_kwargs=None)
Download all supplementary data available for the sample. Args: directory (:obj:`str`): Directory to download the data (in this directory function will create new directory with the files). Defaults to "./". download_sra (:obj:`bool`): Indicates whether t...
3.413989
3.449824
0.989612
downloader = SRADownloader(self, email, directory, **kwargs) return {"SRA": downloader.download()}
def download_SRA(self, email, directory='./', **kwargs)
Download RAW data as SRA file. The files will be downloaded to the sample directory created ad hoc or the directory specified by the parameter. The sample has to come from sequencing eg. mRNA-seq, CLIP etc. An important parameter is a filetype. By default an SRA is accessed by ...
6.598111
6.647816
0.992523
soft = ["^%s = %s" % (self.geotype, self.name), self._get_metadata_as_string()] return "\n".join(soft)
def _get_object_as_soft(self)
Get the object as SOFT formatted string.
9.519135
6.826758
1.394386
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_...
def _get_object_as_soft(self)
Return object as SOFT formatted string.
3.141946
2.886523
1.088488
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 e...
def phenotype_data(self)
Get the phenotype data for each of the sample.
2.88013
2.789845
1.032362
if isinstance(platform, str): gpl = self.gpls[platform] elif isinstance(platform, GPL): gpl = platform else: raise ValueError("Platform has to be of type GPL or string with " "key for platform in GSE") data = [] ...
def merge_and_average(self, platform, expression_column, group_by_column, force=False, merge_on_column=None, gsm_on=None, gpl_on=None)
Merge and average GSE samples. For given platform prepare the DataFrame with all the samples present in the GSE annotated with given column from platform and averaged over the column. Args: platform (:obj:`str` or :obj:`GEOparse.GPL`): GPL platform to use. expre...
2.80128
2.667797
1.050035
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
def pivot_samples(self, values, index="ID_REF")
Pivot samples by specified column. Construct a table in which columns (names) are the samples, index is a specified column eg. ID_REF and values in the columns are of one specified type. Args: values (:obj:`str`): Column name present in all GSMs. index (:obj:`st...
4.411945
4.071116
1.083719
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 = self.pivot_samples(values=values, index=g...
def pivot_and_annotate(self, values, gpl, annotation_column, gpl_on="ID", gsm_on="ID_REF")
Annotate GSM with provided GPL. Args: values (:obj:`str`): Column to use as values eg. "VALUES" gpl (:obj:`pandas.DataFrame` or :obj:`GEOparse.GPL`): A Platform or DataFrame to annotate with. annotation_column (:obj:`str`): Column in table for annotation. ...
2.958264
3.06879
0.963984
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 = os.path.abspath(directory) utils.mkdir_p(dirpath) dow...
def download_supplementary_files(self, directory='series', download_sra=True, email=None, sra_kwargs=None, nproc=1)
Download supplementary data. .. warning:: Do not use parallel option (nproc > 1) in the interactive shell. For more details see `this issue <https://stackoverflow.com/questions/23641475/multiprocessing-working-in-python-but-not-in-ipython/23641560#23641560>`_ on SO. ...
3.004734
3.02878
0.992061
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 not None: gsms_to_use = [gsm for gsm in ...
def download_SRA(self, email, directory='series', filterby=None, nproc=1, **kwargs)
Download SRA files for each GSM in series. .. warning:: Do not use parallel option (nproc > 1) in the interactive shell. For more details see `this issue <https://stackoverflow.com/questions/23641475/multiprocessing-working-in-python-but-not-in-ipython/23641560#23641560>`_ ...
2.932184
2.809166
1.043792
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_sof...
def _get_object_as_soft(self)
Get object as SOFT formatted string.
3.46682
3.185658
1.088259
return os.path.join(os.path.abspath(self.outdir), self.filename)
def destination(self)
Get the destination path. This is the property should be calculated every time it is used because a user could change the outdir and filename dynamically.
6.092973
3.808283
1.599926
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) logg...
def download(self, force=False, silent=False)
Download from URL.
2.176144
2.151978
1.01123
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(aspera_home...
def download_aspera(self, user, host, silent=False)
Download file with Aspera Connect. For details see the documentation ov Aspera Connect Args: user (:obj:`str`): FTP user. host (:obj:`str`): FTP host. Defaults to "ftp-trace.ncbi.nlm.nih.gov".
2.246228
2.237122
1.00407
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()
def md5sum(filename, blocksize=8192)
Get the MD5 checksum of a file.
1.677135
1.67253
1.002754
if geo is None and filepath is None: raise Exception("You have to specify filename or GEO accession!") if geo is not None and filepath is not None: raise Exception("You can specify filename or GEO accession - not both!") if silent: logger.setLevel(100) # More than critical ...
def get_GEO(geo=None, filepath=None, destdir="./", how='full', annotate_gpl=False, geotype=None, include_data=False, silent=False, aspera=False, partial=None)
Get the GEO entry. The GEO entry is taken directly from the GEO database or read it from SOFT file. Args: geo (:obj:`str`): GEO database identifier. filepath (:obj:`str`): Path to local SOFT file. Defaults to None. destdir (:obj:`str`, optional): Directory to download data. Default...
2.439892
2.427423
1.005136
if entry_line.startswith("!"): entry_line = sub(r"!\w*?_", '', entry_line) else: entry_line = entry_line.strip()[1:] try: entry_type, entry_name = [i.strip() for i in entry_line.split("=", 1)] except ValueError: entry_type = [i.strip() for i in entry_line.split("=", ...
def __parse_entry(entry_line)
Parse the SOFT file entry name line that starts with '^', '!' or '#'. Args: entry_line (:obj:`str`): Line from SOFT to be parsed. Returns: :obj:`2-tuple`: Type of entry, value of entry.
2.814725
2.682767
1.049187
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)
def parse_metadata(lines)
Parse list of lines with metadata information from SOFT file. Args: lines (:obj:`Iterable`): Iterator over the lines. Returns: :obj:`dict`: Metadata from SOFT file.
3.703981
4.147071
0.893156
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'])
def parse_columns(lines)
Parse list of lines with columns description from SOFT file. Args: lines (:obj:`Iterable`): Iterator over the lines. Returns: :obj:`pandas.DataFrame`: Columns description.
3.726921
3.770213
0.988517
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 = defaultdict(dict)...
def parse_GDS_columns(lines, subsets)
Parse list of line with columns description from SOFT file of GDS. Args: lines (:obj:`Iterable`): Iterator over the lines. subsets (:obj:`dict` of :obj:`GEOparse.GDSSubset`): Subsets to use. Returns: :obj:`pandas.DataFrame`: Columns description.
3.908511
3.932899
0.993799
# filter lines that do not start with symbols 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()
def parse_table_data(lines)
Parse list of lines from SOFT file into DataFrame. Args: lines (:obj:`Iterable`): Iterator over the lines. Returns: :obj:`pandas.DataFrame`: Table data.
5.49668
6.076267
0.904615
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.r...
def parse_GSM(filepath, entry_name=None)
Parse GSM entry from SOFT file. Args: filepath (:obj:`str` or :obj:`Iterable`): Path to file with 1 GSM entry or list of lines representing GSM from GSE file. entry_name (:obj:`str`, optional): Name of the entry. By default it is inferred from the data. Returns: ...
2.913631
2.871658
1.014616
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_entry, group in groupper: ...
def parse_GPL(filepath, entry_name=None, partial=None)
Parse GPL entry from SOFT file. Args: filepath (:obj:`str` or :obj:`Iterable`): Path to file with 1 GPL entry or list of lines representing GPL from GSE file. entry_name (:obj:`str`, optional): Name of the entry. By default it is inferred from the data. partial (:obj...
2.928581
2.86898
1.020774
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_typ...
def parse_GSE(filepath)
Parse GSE SOFT file. Args: filepath (:obj:`str`): Path to GSE SOFT file. Returns: :obj:`GEOparse.GSE`: A GSE object.
2.929906
2.877392
1.018251
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_e...
def parse_GDS(filepath)
Parse GDS SOFT file. Args: filepath (:obj:`str`): Path to GDS SOFT file. Returns: :obj:`GEOparse.GDS`: A GDS object.
2.876534
2.798678
1.027819
try: os.makedirs(path_to_dir) except OSError as e: # Python >2.5 if e.errno == EEXIST and os.path.isdir(path_to_dir): logger.debug( "Directory %s already exists. Skipping." % path_to_dir) else: raise e
def mkdir_p(path_to_dir)
Make directory(ies). This function behaves like mkdir -p. Args: path_to_dir (:obj:`str`): Path to the directory to make.
1.999316
2.217337
0.901674
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(destination_path)) if aspera: ...
def download_from_url(url, destination_path, force=False, aspera=False, silent=False)
Download file from remote server. If the file is already downloaded and ``force`` flag is on the file will be removed. Args: url (:obj:`str`): Path to the file on remote server (including file name) destination_path (:obj:`str`): Path to the file on local machine (...
4.766472
4.780221
0.997124
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.clo...
def smart_open(filepath)
Open file intelligently depending on the source and python version. Args: filepath (:obj:`str`): Path to the file. Yields: Context manager for file handle.
2.163002
2.460742
0.879004
print("Tuning with GP tuner for %s iterations" % TUNING_BUDGET_PER_ITER) for i in range(TUNING_BUDGET_PER_ITER): params = tuner.propose() # create model using proposed hyperparams from tuner model = generate_model(params) model.fit(X, y) predicted = model.predict(X_v...
def tune_pipeline(X, y, X_val, y_val, generate_model, tuner)
Tunes a specified pipeline with the specified tuner for TUNING_BUDGET_PER_ITER (3) iterations. Params: X: np.array of X training data y: np.array of y training data X_val: np.array of X validation data y_val: np.array of y validation data generate_model: function that re...
4.018304
3.462165
1.160633
return max(choice_rewards, key=lambda a: np.mean(choice_rewards[a]))
def bandit(self, choice_rewards)
Return the choice to take next using multi-armed bandit Multi-armed bandit method. Accepts a mapping of choices to rewards which indicate their historical performance, and returns the choice that we should make next in order to maximize expected reward in the long term. The default imp...
5.010492
4.981711
1.005777
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)
def select(self, choice_scores)
Select the next best choice to make Args: choice_scores (Dict[object, List[float]]): Mapping of choice to list of scores for each possible choice. The caller is responsible for making sure each choice that is possible at this juncture is represented in the dict, even...
3.670487
4.527082
0.810784
if len(scores) > self.k: scores = np.copy(scores) inds = np.argsort(scores)[:-self.k] scores[inds] = np.nan return list(scores)
def compute_rewards(self, scores)
Retain the K best scores, and replace the rest with nans
3.714918
2.526042
1.470648
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)
def compute_rewards(self, scores)
Compute the velocity of the best scores The velocities are the k distances between the k+1 best scores.
4.606043
3.297251
1.396934
# decompose X and generate the rankings of the elements in the # decomposed matrix dpp_vector_decomposed = self.mf_model.transform(dpp_vector) dpp_vector_ranked = stats.rankdata( dpp_vector_decomposed, method='dense', ) max_agreement_ind...
def fit(self, dpp_vector)
Finds row of self.dpp_matrix most closely corresponds to X by means of Kendall tau distance. https://en.wikipedia.org/wiki/Kendall_tau_distance Args: dpp_vector (np.array): Array with shape (n_components, )
3.832356
3.514818
1.090343
# first, train a gaussian process like normal super(GPEiVelocity, self).fit(X, y) # probability of uniform self.POU = 0 if len(y) >= self.r_minimum: # get the best few scores so far, and compute the average distance # between them. to...
def fit(self, X, y)
Train a gaussian process like normal, then compute a "Probability Of Uniform selection" (POU) value.
8.721124
6.681819
1.305202
if np.random.random() < self.POU: # choose params at random to avoid local minima return Uniform(self.tunables).predict(X) return super(GPEiVelocity, self).predict(X)
def predict(self, X)
Use the POU value we computed in fit to choose randomly between GPEi and uniform random selection.
14.615937
9.976964
1.464968
for i in range(len(scores)): if i >= self.k: scores[i] = 0. return scores
def compute_rewards(self, scores)
Retain the K most recent scores, and replace the rest with zeros
3.995443
2.799805
1.427043
# if we don't have enough scores to do K-selection, fall back to UCB1 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 = ...
def select(self, choice_scores)
Use the top k learner's scores for usage in rewards for the bandit calculation
4.396058
4.112538
1.06894
# take the k + 1 most recent scores so we can get k velocities recent_scores = scores[:-self.k - 2:-1] velocities = [recent_scores[i] - recent_scores[i + 1] for i in range(len(recent_scores) - 1)] # pad the list out with zeros, so the length of the list is ...
def compute_rewards(self, scores)
Compute the velocity of thte k+1 most recent scores. The velocity is the average distance between scores. Return a list with those k velocities padded out with zeros so that the count remains the same.
5.089855
3.537587
1.438793
return -1 * ((a - x)**2 + b * (y - x**2)**2)
def rosenbrock(x, y, a=1, b=100)
Bigger is better; global optimum at x=a, y=a**2
3.141162
3.229031
0.972788
# choose algorithm using a bandit alg_scores = {} for algorithm, choices in self.by_algorithm.items(): # only make arms for algorithms that have options if not set(choices) & set(choice_scores.keys()): continue # sum up lists to get a ...
def select(self, choice_scores)
Groups the frozen sets by algorithm and first chooses an algorithm based on the traditional UCB1 criteria. Next, from that algorithm's frozen sets, makes the final set choice.
6.015516
5.269899
1.141486
# count the larger of 1 and the total number of arm pulls total_pulls = max(1, sum(len(r) for r in choice_rewards.values())) def ucb1(choice): rewards = choice_rewards[choice] choice_pulls = max(len(rewards), 1) average_reward = np.nanmean(rewards) ...
def bandit(self, choice_rewards)
Multi-armed bandit method which chooses the arm for which the upper confidence bound (UCB) of expected reward is greatest. If there are multiple arms with the same UCB1 index, then one is chosen at random. An explanation is here: https://www.cs.bham.ac.uk/internal/courses/robot...
3.96859
3.816442
1.039866
# get the k + 1 best scores in descending order best_scores = sorted(scores, reverse=True)[:self.k + 1] velocities = [best_scores[i] - best_scores[i + 1] for i in range(len(best_scores) - 1)] # pad the list out with zeros to maintain the length of the list...
def compute_rewards(self, scores)
Compute the "velocity" of (average distance between) the k+1 best scores. Return a list with those k velocities padded out with zeros so that the count remains the same.
3.737048
2.661022
1.404366