text
stringlengths
81
112k
Create folders with relative symlinks to the desired simulated/sampled reads. These folders will contain all the reads created for each sample, and will be processed with GeneSippr and COWBAT pipelines :param analysistype: Current analysis type. Will either be 'simulated' or 'sampled' def link_reads(se...
Run GeneSippr on each of the samples def run_genesippr(self): """ Run GeneSippr on each of the samples """ from pathlib import Path home = str(Path.home()) logging.info('GeneSippr') # These unfortunate hard coded paths appear to be necessary miniconda_pat...
Set the logging level of this logger. :param level: must be an int or a str. def set_level(self, level): """ Set the logging level of this logger. :param level: must be an int or a str. """ for handler in self.__coloredlogs_handlers: handler.setLevel(level=...
Disable all logging calls. def disable_logger(self, disabled=True): """ Disable all logging calls. """ # Disable standard IO streams if disabled: sys.stdout = _original_stdout sys.stderr = _original_stderr else: sys.stdout = self.__std...
Redirect sys.stdout to file-like object. def redirect_stdout(self, enabled=True, log_level=logging.INFO): """ Redirect sys.stdout to file-like object. """ if enabled: if self.__stdout_wrapper: self.__stdout_wrapper.update_log_level(log_level=log_level) ...
Redirect sys.stderr to file-like object. def redirect_stderr(self, enabled=True, log_level=logging.ERROR): """ Redirect sys.stderr to file-like object. """ if enabled: if self.__stderr_wrapper: self.__stderr_wrapper.update_log_level(log_level=log_level) ...
Handler for logging to a file, rotating the log file at certain timed intervals. def use_file(self, enabled=True, file_name=None, level=logging.WARNING, when='d', interval=1, backup_count=30, delay=False, ...
Enable handler for sending the record to Loggly service. def use_loggly(self, enabled=True, loggly_token=None, loggly_tag=None, level=logging.WARNING, log_format=None, date_format=None): """ Enable handler fo...
Find the stack frame of the caller so that we can note the source file name, line number and function name. def __find_caller(stack_info=False): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. """ frame = lo...
Log 'msg % args' with the integer severity 'level'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.log(level, "We have a %s", "mysterious problem", exc_info=1) def _log(self, level, msg, *args, **kwargs): """ Log 'msg % args' wi...
Flush the buffer, if applicable. def flush(self): """ Flush the buffer, if applicable. """ if self.__buffer.tell() > 0: # Write the buffer to log # noinspection PyProtectedMember self.__logger._log(level=self.__log_level, msg=self.__buffer.getvalue()....
Syllabify the given word, whether simplex or complex. def syllabify(word): '''Syllabify the given word, whether simplex or complex.''' compound = bool(re.search(r'(-| |=)', word)) syllabify = _syllabify_compound if compound else _syllabify syllabifications = list(syllabify(word)) for syll, rules i...
An agglutination diphthong that ends in /u, y/ optionally contains a syllable boundary when -C# or -CCV follow, e.g., [lau.ka.us], [va.ka.ut.taa]. def apply_T4(word): '''An agglutination diphthong that ends in /u, y/ optionally contains a syllable boundary when -C# or -CCV follow, e.g., [lau.ka.us], ...
Setup logging. def setup(product_name): """Setup logging.""" if CONF.log_config: _load_log_config(CONF.log_config) else: _setup_logging_from_conf() sys.excepthook = _create_logging_excepthook(product_name)
Uses contextstring if request_id is set, otherwise default. def format(self, record): """Uses contextstring if request_id is set, otherwise default.""" # NOTE(sdague): default the fancier formating params # to an empty string so we don't throw an exception if # they get used for...
Format exception output with CONF.logging_exception_prefix. def formatException(self, exc_info, record=None): """Format exception output with CONF.logging_exception_prefix.""" if not record: return logging.Formatter.formatException(self, exc_info) stringbuffer = cStringIO.StringIO(...
Display buttons given by the list of tuples (id,function,description,is_active) def _set_boutons_interface(self, buttons): """Display buttons given by the list of tuples (id,function,description,is_active)""" for id_action, f, d, is_active in buttons: icon = self.get_icon(id_action) ...
Add update toolbar callback to the interface def set_interface(self, interface): """Add update toolbar callback to the interface""" self.interface = interface self.interface.callbacks.update_toolbar = self._update self._update()
Update the display of button after querying data from interface def _update(self): """Update the display of button after querying data from interface""" self.clear() self._set_boutons_communs() if self.interface: self.addSeparator() l_actions = self.interface.get...
Display login screen. May ask for local data loading if from_local is True. def init_login(self, from_local=False): """Display login screen. May ask for local data loading if from_local is True.""" if self.toolbar: self.removeToolBar(self.toolbar) widget_login = login.Loading(self.s...
Shortcut for making a response to the client's request. def make_response(self, status, content_type, response): """Shortcut for making a response to the client's request.""" headers = [('Access-Control-Allow-Origin', '*'), ('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'), ...
Processes a request. def process_request(self, request): """Processes a request.""" try: request = Request.from_json(request.read().decode()) except ValueError: raise ClientError('Data is not valid JSON.') except KeyError: raise ClientError('Missing m...
Extracts the request, feeds the module, and returns the response. def on_post(self): """Extracts the request, feeds the module, and returns the response.""" request = self.environ['wsgi.input'] try: return self.process_request(request) except ClientError as exc: ...
Handles dispatching of the request. def dispatch(self): """Handles dispatching of the request.""" method_name = 'on_' + self.environ['REQUEST_METHOD'].lower() method = getattr(self, method_name, None) if method: return method() else: return self.on_bad_me...
Sync this model with latest data on the saltant server. Note that in addition to returning the updated object, it also updates the existing object. Returns: :class:`saltant.models.user.User`: This user instance after syncing. def sync(self): """Sync this mo...
Tuple containing the contents of the Block. def serialised( self ): """Tuple containing the contents of the Block.""" klass = self.__class__ return ((klass.__module__, klass.__name__), tuple( (name, field.serialise( self._field_data[name], parent=self ) ) for name, field in klass._fields.items(...
Clone data from another Block. source Block instance to copy from. def clone_data( self, source ): """Clone data from another Block. source Block instance to copy from. """ klass = self.__class__ assert isinstance( source, klass ) for n...
Import data from a byte array. raw_buffer Byte array to import from. def import_data( self, raw_buffer ): """Import data from a byte array. raw_buffer Byte array to import from. """ klass = self.__class__ if raw_buffer: assert common...
Export data to a byte array. def export_data( self ): """Export data to a byte array.""" klass = self.__class__ output = bytearray( b'\x00'*self.get_size() ) # prevalidate all data before export. # this is important to ensure that any dependent fields # are updated bef...
Update dependencies on all the fields on this Block instance. def update_deps( self ): """Update dependencies on all the fields on this Block instance.""" klass = self.__class__ for name in klass._fields: self.update_deps_on_field( name ) return
Validate all the fields on this Block instance. def validate( self ): """Validate all the fields on this Block instance.""" klass = self.__class__ for name in klass._fields: self.validate_field( name ) return
Get the projected size (in bytes) of the exported data from this Block instance. def get_size( self ): """Get the projected size (in bytes) of the exported data from this Block instance.""" klass = self.__class__ size = 0 for name in klass._fields: size = max( size, klass._f...
Save the GADDAG to file. Args: path: path to save the GADDAG to. compressed: compress the saved GADDAG using gzip. exist_ok: overwrite existing file at `path`. def save(self, path, compressed=True, exist_ok=False): """ Save the GADDAG to file. Args:...
Load a GADDAG from file, replacing the words currently in this GADDAG. Args: path: path to saved GADDAG to be loaded. def load(self, path): """ Load a GADDAG from file, replacing the words currently in this GADDAG. Args: path: path to saved GADDAG to be loaded....
Find all words starting with a prefix. Args: prefix: A prefix to be searched for. Returns: A list of all words found. def starts_with(self, prefix): """ Find all words starting with a prefix. Args: prefix: A prefix to be searched for. ...
Find all words containing a substring. Args: sub: A substring to be searched for. Returns: A list of all words found. def contains(self, sub): """ Find all words containing a substring. Args: sub: A substring to be searched for. Re...
Find all words ending with a suffix. Args: suffix: A suffix to be searched for. Returns: A list of all words found. def ends_with(self, suffix): """ Find all words ending with a suffix. Args: suffix: A suffix to be searched for. Re...
Add a word to the GADDAG. Args: word: A word to be added to the GADDAG. def add_word(self, word): """ Add a word to the GADDAG. Args: word: A word to be added to the GADDAG. """ word = word.lower() if not (word.isascii() and word.isalph...
Similar to format, but takes additional reserved params to promote logging best-practices :param level - severity of message - how bad is it? :param source - application context - where did it come from? :param title - brief description - what kind of event happened? :param data - additional information - what...
Updates this task type on the saltant server. Returns: :class:`saltant.models.container_task_type.ContainerTaskType`: A task type model instance representing the task type just updated. def put(self): """Updates this task type on the saltant server. ...
Create a container task type. Args: name (str): The name of the task. command_to_run (str): The command to run to execute the task. container_image (str): The container name and tag. For example, ubuntu:14.04 for Docker; and docker://ubuntu:14:04 ...
Updates a task type on the saltant server. Args: id (int): The ID of the task type. name (str): The name of the task type. description (str): The description of the task type. command_to_run (str): The command to run to execute the task. environment_v...
Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', '0' and ''. Raises ValueError if 'val' is anything else. def _strtobool(val): """Convert a string representation of truth to true...
Convert a string to a list with sanitization. def _str_to_list(value, separator): """Convert a string to a list with sanitization.""" value_list = [item.strip() for item in value.split(separator)] value_list_sanitized = builtins.list(filter(None, value_list)) if len(value_list_sanitized) > 0: r...
Write a raw env value. A ``None`` value clears the environment variable. Args: name: The environment variable name value: The value to write def write(name, value): """Write a raw env value. A ``None`` value clears the environment variable. Args: name: The environment va...
Read the raw env value. Read the raw environment variable or use the default. If the value is not found and no default is set throw an exception. Args: name: The environment variable name default: The default value to use if no environment variable is found allow_none: If the retur...
Get a string based environment value or the default. Args: name: The environment variable name default: The default value to use if no environment variable is found allow_none: If the return value can be `None` (i.e. optional) def str(name, default=None, allow_none=False, fallback=None): ...
Get a boolean based environment value or the default. Args: name: The environment variable name default: The default value to use if no environment variable is found allow_none: If the return value can be `None` (i.e. optional) def bool(name, default=None, allow_none=False, fallback=None):...
Get a string environment value or the default. Args: name: The environment variable name default: The default value to use if no environment variable is found allow_none: If the return value can be `None` (i.e. optional) def int(name, default=None, allow_none=False, fallback=None): """...
Get a list of strings or the default. The individual list elements are whitespace-stripped. Args: name: The environment variable name default: The default value to use if no environment variable is found allow_none: If the return value can be `None` (i.e. optional) separator: T...
this function adds some configuration for the application def includeme(config): """this function adds some configuration for the application""" config.add_route('references', '/references') _add_referencer(config.registry) config.add_view_deriver(protected_resources.protected_view) config.add_rend...
Gets the Referencer from config and adds it to the registry. def _add_referencer(registry): """ Gets the Referencer from config and adds it to the registry. """ referencer = registry.queryUtility(IReferencer) if referencer is not None: return referencer ref = registry.settings['urirefer...
Get the referencer class :rtype: pyramid_urireferencer.referencer.AbstractReferencer def get_referencer(registry): """ Get the referencer class :rtype: pyramid_urireferencer.referencer.AbstractReferencer """ # Argument might be a config or request regis = getattr(registry, 'registry', Non...
:param region: The region of AWS to connect to. :param EC2Credentials credentials: The credentials to use to authenticate with EC2. :return: a connection object to AWS EC2 def _connect_to_ec2(region, credentials): """ :param region: The region of AWS to connect to. :param EC2Credentials cr...
:param args: tuple(value, style), tuple(value, style) :param kwargs: header=tuple(value, style), header=tuple(value, style) :param args: value, value :param kwargs: header=value, header=value def write(self, *args, **kwargs): """ :param args: tuple(value, style), tuple(value, st...
Clear the layout off all its components def clear_layout(layout: QLayout) -> None: """Clear the layout off all its components""" if layout is not None: while layout.count(): item = layout.takeAt(0) widget = item.widget() if widget is not None: widget....
Helper function for parsing the contents of "HangulSyllableType.txt" from the Unicode Character Database (UCD) and generating a lookup table for determining whether or not a given Hangul syllable is of type "L", "V", "T", "LV" or "LVT". For more info on the UCD, see the following website: https://www.unicode.o...
Function for parsing the Jamo short names from the Unicode Character Database (UCD) and generating a lookup table For more info on how this is used, see the Unicode Standard, ch. 03, section 3.12, "Conjoining Jamo Behavior" and ch. 04, section 4.8, "Name". https://www.unicode.org/versions/latest/ch03.pdf ...
Function for taking a Unicode scalar value representing a Hangul syllable and determining the correct value for its Hangul_Syllable_Type property. For more information on the Hangul_Syllable_Type property see the Unicode Standard, ch. 03, section 3.12, Conjoining Jamo Behavior. https://www.unicode.org/ver...
Function for taking a Unicode scalar value representing a Jamo and determining the correct value for its Jamo_Short_Name property. For more information on the Jamo_Short_Name property see the Unicode Standard, ch. 03, section 3.12, Conjoining Jamo Behavior. https://www.unicode.org/versions/latest/ch03.pdf...
Function for taking a tuple or list of Unicode scalar values representing Jamo and composing it into a Hangul syllable. If the values in the list or tuple passed in are not in the ranges of Jamo, a ValueError will be raised. The algorithm for doing the composition is described in the Unicode Standard, ch. 03,...
Function for taking a Unicode scalar value representing a Hangul syllable and decomposing it into a tuple representing the scalar values of the decomposed (canonical decomposition) Jamo. If the Unicode scalar value passed in is not in the range of Hangul syllable values (as defined in UnicodeData.txt), a Value...
Function for taking a Unicode scalar value representing a Hangul syllable and converting it to its syllable name as defined by the Unicode naming rule NR1. See the Unicode Standard, ch. 04, section 4.8, Names, for more information. :param hangul_syllable: Unicode scalar value representing the Hangul syllable ...
Return a dict mapping method names to anonymous functions that will call the server's endpoint of the corresponding name as described in the api defined by the swagger dict and bravado spec def generate_client_callers(spec, timeout, error_callback, local, app): """Return a dict mapping method names to anon...
Call request and retry up to max_attempts times (or none if self.max_attempts=1) def _call_retry(self, force_retry): """Call request and retry up to max_attempts times (or none if self.max_attempts=1)""" last_exception = None for i in range(self.max_attempts): try: l...
Syllabify the given word, whether simplex or complex. def syllabify(word): '''Syllabify the given word, whether simplex or complex.''' word = split(word) # detect any non-delimited compounds compound = True if re.search(r'-| |\.', word) else False syllabify = _syllabify_compound if compound else _syll...
Syllabify the given word. def _syllabify(word, T4=True): '''Syllabify the given word.''' word = replace_umlauts(word) word, rules = apply_T1(word) if re.search(r'[^ieAyOauo]*([ieAyOauo]{2})[^ieAyOauo]*', word): word, T2 = apply_T2(word) word, T8 = apply_T8(word) word, T9 = appl...
There is a syllable boundary in front of every CV-sequence. def apply_T1(word): '''There is a syllable boundary in front of every CV-sequence.''' # split consonants and vowels: 'balloon' -> ['b', 'a', 'll', 'oo', 'n'] WORD = [w for w in re.split('([ieAyOauo]+)', word) if w] count = 0 for i, v in e...
Convert mutation annotations to extended cigar format https://github.com/lh3/minimap2#the-cs-optional-tag USAGE: >>> template = 'CGATCGATAAATAGAGTAG---GAATAGCA' >>> query = 'CGATCG---AATAGAGTAGGTCGAATtGCA' >>> extended_cigar(template, query) == ':6-ata:10+gtc:4*at:3' True def exte...
Generate query sequence from the template and extended cigar annotation USAGE: >>> template = 'CGATCGATAAATAGAGTAGGAATAGCA' >>> cigar = ':6-ata:10+gtc:4*at:3' >>> cigar2query(template, cigar) == 'CGATCGAATAGAGTAGGTCGAATtGCA'.upper() True def cigar2query(template, cigar): ''' Generate ...
BLAST wrapper method, that takes a simple input and produces a overview list of the hits to templates, and their alignments Usage >>> import os, subprocess, collections >>> from Bio.Blast import NCBIXML >>> from Bio import SeqIO >>> from string import maketrans >>> inputfile = 't...
Function for comparing hits and saving only the best hit def compare_results(save, best_hsp, tmp_results, tmp_gene_split): ''' Function for comparing hits and saving only the best hit ''' # Get data for comparison hit_id = best_hsp['hit_id'] new_start_query = best_hsp['query_start'] new_end_query = best...
Function for calcualting new length if the gene is split on several contigs def calculate_new_length(gene_split, gene_results, hit): ''' Function for calcualting new length if the gene is split on several contigs ''' # Looping over splitted hits and calculate new length first = 1 for split in gene...
Chop a stream of data into MODBUS packets. :param data: stream of data :returns: a tuple of the data that is a packet with the remaining data, or ``None`` def stream_to_packet(data): """ Chop a stream of data into MODBUS packets. :param data: stream of data :returns: a tuple of the da...
Convert a complex object into primitives. Handy for JSON serialization. We can optionally handle instances, but since this is a recursive function, we could have cyclical data structures. To handle cyclical data structures we could track the actual objects visited in a set, but not all objects are...
Return the firstmost vowel in 'syll'. def get_vowel(syll): '''Return the firstmost vowel in 'syll'.''' return re.search(r'([ieaouäöy]{1})', syll, flags=FLAGS).group(1).upper()
Return True if 'syll' is light. def is_light(syll): '''Return True if 'syll' is light.''' return re.match(r'(^|[^ieaouäöy]+)[ieaouäöy]{1}$', syll, flags=FLAGS)
Assign primary and secondary stress to 'syllabified_simplex_word'. def stress(syllabified_simplex_word): '''Assign primary and secondary stress to 'syllabified_simplex_word'.''' syllables = syllabified_simplex_word.split('.') stressed = '\'' + syllables[0] # primary stress try: n = 0 ...
Return True if 'word' does not violate sonority sequencing. def sonseq(word): '''Return True if 'word' does not violate sonority sequencing.''' parts = re.split(r'([ieaouäöy]+)', word, flags=re.I | re.U) onset, coda = parts[0], parts[-1] # simplex onset Finnish complex onset if len(onset) <=...
Return True if the word's vowels agree in frontness/backness. def harmonic(word): '''Return True if the word's vowels agree in frontness/backness.''' depth = {'ä': 0, 'ö': 0, 'y': 0, 'a': 1, 'o': 1, 'u': 1} vowels = filter(lambda ch: is_front(ch) or is_back(ch), word) depths = (depth[x.lower()] for x i...
Updates this task type on the saltant server. Returns: :class:`saltant.models.container_task_type.ExecutableTaskType`: An executable task type model instance representing the task type just updated. def put(self): """Updates this task type on the saltant ser...
Create a container task type. Args: name (str): The name of the task. command_to_run (str): The command to run to execute the task. description (str, optional): The description of the task type. environment_variables (list, optional): The environment ...
Updates a task type on the saltant server. Args: id (int): The ID of the task type. name (str): The name of the task type. description (str): The description of the task type. command_to_run (str): The command to run to execute the task. environment_v...
Creates a report of the genesippr results :param analysistype: The variable to use when accessing attributes in the metadata object def reporter(self, analysistype='genesippr'): """ Creates a report of the genesippr results :param analysistype: The variable to use when accessing attribu...
Creates simplified genus-specific reports. Instead of the % ID and the fold coverage, a simple +/- scheme is used for presence/absence :param analysistype: The variable to use when accessing attributes in the metadata object def genusspecific(self, analysistype='genesippr'): """ Creates...
Creates a report of the GDCS results :param analysistype: The variable to use when accessing attributes in the metadata object def gdcsreporter(self, analysistype='GDCS'): """ Creates a report of the GDCS results :param analysistype: The variable to use when accessing attributes in the ...
GDCS analyses need to use the .fai file supplied in the targets folder rather than the one created following reverse baiting :param sample: sample object :param analysistype: current analysis being performed def gdcs_fai(sample, analysistype='GDCS'): """ GDCS analyses need to us...
Creates a report of the results :param analysistype: The variable to use when accessing attributes in the metadata object def sixteensreporter(self, analysistype='sixteens_full'): """ Creates a report of the results :param analysistype: The variable to use when accessing attributes in t...
Creates a final report of all the ConFindr results def confindr_reporter(self, analysistype='confindr'): """ Creates a final report of all the ConFindr results """ # Initialise the data strings data = 'Strain,Genus,NumContamSNVs,ContamStatus,PercentContam,PercentContamSTD\n' ...
Create final reports collating results from all the individual iterations through the method pipeline def methodreporter(self): """ Create final reports collating results from all the individual iterations through the method pipeline """ # Ensure that the analyses are set to complete ...
Run the methods required to create the genesippr report summary image def main(self): """ Run the methods required to create the genesippr report summary image """ self.dataframe_setup() self.figure_populate(self.outputfolder, self.image_report, ...
Format the data to be consistent with heatmaps :param inputstring: string containing data to be formatted :param header: class of the data - certain categories have specific formatting requirements :return: the formatted output string def data_sanitise(self, inputstring, header=None): "...
Set-up a report to store the desired header: sanitized string combinations def dataframe_setup(self): """ Set-up a report to store the desired header: sanitized string combinations """ # Initialise a dictionary to store the sanitized headers and strings genesippr_dict = dict() ...
Create the report image from the summary report created in self.dataframesetup :param outputpath: Path in which the outputs are to be created :param csv: Name of the report file from which data are to be extracted :param xlabels: List of all the labels to use on the x-axis :param ylabels...
adds /usr/local/bin to $PATH def add_usr_local_bin_to_path(log=False): """ adds /usr/local/bin to $PATH """ if log: bookshelf2.logging_helpers.log_green('inserts /usr/local/bin into PATH') with settings(hide('warnings', 'running', 'stdout', 'stderr'), capture=True): try: ...
cuisine dir_attribs doesn't do sudo, so we implement our own Updates the mode/owner/group for the given remote directory. def dir_attribs(location, mode=None, owner=None, group=None, recursive=False, use_sudo=False): """ cuisine dir_attribs doesn't do sudo, so we implement our own U...
cuisine dir_ensure doesn't do sudo, so we implement our own Ensures that there is a remote directory at the given location, optionally updating its mode/owner/group. If we are not updating the owner/group then this can be done as a single ssh call, so use that method, otherwise set owner/group after cre...
Tells if there is a remote directory at the given location. def dir_exists(location, use_sudo=False): """Tells if there is a remote directory at the given location.""" with settings(hide('running', 'stdout', 'stderr'), warn_only=True): if use_sudo: # convert return code 0 to True ...
updates /etc/sudoers so that users from %wheel keep their environment when executing a sudo call def disable_env_reset_on_sudo(log=False): """ updates /etc/sudoers so that users from %wheel keep their environment when executing a sudo call """ if log: bookshelf2.logging_helpers.log_...
allow sudo calls through ssh without a tty def disable_requiretty_on_sudoers(log=False): """ allow sudo calls through ssh without a tty """ if log: bookshelf2.logging_helpers.log_green( 'disabling requiretty on sudo calls') comment_line('/etc/sudoers', '^Defaults.*requ...