code stringlengths 1 18.2k |
|---|
def getReadLengths(reads, gapChars): """ Get all read lengths, excluding gap characters. @param reads: A C{Reads} instance. @param gapChars: A C{str} of sequence characters considered to be gaps. @return: A C{dict} keyed by read id, with C{int} length values. """ gapChars = set(gapChars) result = {} for read in reads: ... |
def explanation(matchAmbiguous, concise, showLengths, showGaps, showNs): """ Make an explanation of the output HTML table. @param matchAmbiguous: If C{True}, count ambiguous nucleotides that are possibly correct as actually being correct. Otherwise, we are strict and insist that only non-ambiguous nucleotides can contr... |
fraction numerator is the sum of the number of identical """] if matchAmbiguous: result.append('nucleotides plus the number of ambiguously matching ' 'nucleotides.') else: result.append('nucleotides.') result.append("""The denominator is the length of the sequence <em>for the row</em>. Sequence gaps are not included wh... |
def collectData(reads1, reads2, square, matchAmbiguous): """ Get pairwise matching statistics for two sets of reads. @param reads1: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the rows of the table. @param reads2: An C{OrderedDict} of C{str} read ids whose values are C{Read} i... |
reads2.items(): if id1 != id2 or not square: match = compareDNAReads( read1, read2, matchAmbiguous=matchAmbiguous)['match'] if not matchAmbiguous: assert match['ambiguousMatchCount'] == 0 result[id1][id2] = result[id2][id1] = match return result |
def simpleTable(tableData, reads1, reads2, square, matchAmbiguous, gapChars): """ Make a text table showing inter-sequence distances. @param tableData: A C{defaultdict(dict)} keyed by read ids, whose values are the dictionaries returned by compareDNAReads. @param reads1: An C{OrderedDict} of C{str} read ids whose value... |
matching nucleotide count. @param gapChars: A C{str} of sequence characters considered to be gaps. """ readLengths1 = getReadLengths(reads1.values(), gapChars) print('ID\t' + '\t'.join(reads2)) for id1, read1 in reads1.items(): read1Len = readLengths1[id1] print(id1, end='') for id2, read2 in reads2.items(): if id1 == ... |
def htmlTable(tableData, reads1, reads2, square, matchAmbiguous, colors, concise=False, showLengths=False, showGaps=False, showNs=False, footer=False, div=False, gapChars='-'): """ Make an HTML table showing inter-sequence distances. @param tableData: A C{defaultdict(dict)} keyed by read ids, whose values are the dicti... |
only non-ambiguous nucleotides can contribute to the matching nucleotide count. @param colors: A C{list} of (threshold, color) tuples, where threshold is a C{float} and color is a C{str} to be used as a cell background. This is as returned by C{parseColors}. @param concise: If C{True}, do not show match details. @param... |
HTML C{str} showing inter-sequence distances. """ readLengths1 = getReadLengths(reads1.values(), gapChars) readLengths2 = getReadLengths(reads2.values(), gapChars) result = [] append = result.append def writeHeader(): # The header row of the table. append(' <tr>') append(' <td> </td>') for read2 in reads2.values()... |
color style information for the identity thresholds. for threshold, color in colors: append('.%s { background-color: %s; }' % ( thresholdToCssName(threshold), color)) append('</style>') if not div: append(explanation( matchAmbiguous, concise, showLengths, showGaps, showNs)) append('<div style="overflow-x:auto;">') appe... |
class="name">%s</span>' % id1) if showLengths: append('<br/>L:%d' % read1Len) if showGaps: append('<br/>G:%d' % (len(read1) - read1Len)) if showNs: append('<br/>N:%d' % read1.sequence.count('N')) append('</td>') for id2, read2 in reads2.items(): if id1 == id2 and square: append('<td> </td>') continue stats = table... |
def create_task(function, *args, **kwargs): """ Create a task object name: The name of the task. function: The actual task function. It should take no arguments, and return a False-y value if it fails. dependencies: (optional, ()) Any dependencies that this task relies on. """ name = "{}".format(uuid4()) handler = None... |
def hs_join(ls_hsi, hso): """ [Many-to-one] Synchronizes (joins) a list of input handshake interfaces: output is ready when ALL inputs are ready ls_hsi - (i) list of input handshake tuples (ready, valid) hso - (o) an output handshake tuple (ready, valid) """ N = len(ls_hsi) ls_hsi_rdy, ls_hsi_vld = zip(*ls_hsi) ls_hsi_... |
def hs_fork(hsi, ls_hso): """ [One-to-many] Synchronizes (forks) to a list of output handshake interfaces: input is ready when ALL outputs are ready hsi - (i) input handshake tuple (ready, valid) ls_hso - (o) list of output handshake tuples (ready, valid) """ N = len(ls_hso) hsi_rdy, hsi_vld = hsi ls_hso_rdy, ls_hso_vl... |
def hs_mux(sel, ls_hsi, hso): """ [Many-to-one] Multiplexes a list of input handshake interfaces sel - (i) selects an input handshake interface to be connected to the output ls_hsi - (i) list of input handshake tuples (ready, valid) hso - (o) output handshake tuple (ready, valid) """ N = len(ls_hsi) ls_hsi_rdy, ls_hsi_... |
def hs_demux(sel, hsi, ls_hso): """ [One-to-many] Demultiplexes to a list of output handshake interfaces sel - (i) selects an output handshake interface to connect to the input hsi - (i) input handshake tuple (ready, valid) ls_hso - (o) list of output handshake tuples (ready, valid) """ N = len(ls_hso) hsi_rdy, hsi_vld... |
def hs_arbmux(rst, clk, ls_hsi, hso, sel, ARBITER_TYPE="priority"): """ [Many-to-one] Arbitrates a list of input handshake interfaces. Selects one of the active input interfaces and connects it to the output. Active input is an input interface with asserted "valid" signal ls_hsi - (i) list of input handshake tuples (re... |
priority_update = None if (ARBITER_TYPE == "roundrobin"): hso_rdy, hso_vld = hso priority_update = Signal(bool(0)) @always_comb def _prio(): priority_update.next = hso_rdy and hso_vld _arb = arbiter(rst=rst, clk=clk, req_vec=ls_vld, gnt_idx=sel_s, gnt_rdy=priority_update, ARBITER_TYPE=ARBITER_TYPE) _mux = hs_mux(sel=se... |
def hs_arbdemux(rst, clk, hsi, ls_hso, sel, ARBITER_TYPE="priority"): """ [One-to-many] Arbitrates a list output handshake interfaces Selects one of the active output interfaces and connects it to the input. Active is an output interface with asserted "ready" signal hsi - (i) input handshake tuple (ready, valid) ls_hso... |
= None if (ARBITER_TYPE == "roundrobin"): shi_rdy, hsi_vld = hsi priority_update = Signal(bool(0)) @always_comb def _prio(): priority_update.next = shi_rdy and hsi_vld _arb = arbiter(rst=rst, clk=clk, req_vec=ls_rdy, gnt_idx=sel_s, gnt_rdy=priority_update, ARBITER_TYPE=ARBITER_TYPE) _demux = hs_demux(sel_s, hsi, ls_hso... |
def get_file_md5sum(path): """Calculate the MD5 hash for a file.""" with open(path, 'rb') as fh: h = str(hashlib.md5(fh.read()).hexdigest()) return h |
def smart_open_read(path=None, mode='rb', encoding=None, try_gzip=False): """Open a file for reading or return ``stdin``. Adapted from StackOverflow user "Wolph" (http://stackoverflow.com/a/17603000). """ assert mode in ('r', 'rb') assert path is None or isinstance(path, (str, _oldstr)) assert isinstance(mode, (str, _o... |
fh if fh is None: yield_fh = binfh try: yield yield_fh finally: # close all open files if fh is not None: # make sure we don't close stdin if fh.fileno() != sys.stdin.fileno(): fh.close() if binfh is not None: binfh.close() if gzfh is not None: gzfh.close() |
def smart_open_write(path=None, mode='wb', encoding=None): """Open a file for writing or return ``stdout``. Adapted from StackOverflow user "Wolph" (http://stackoverflow.com/a/17603000). """ if path is not None: # open a file fh = io.open(path, mode=mode, encoding=encoding) else: # open stdout fh = io.open(sys.stdout.f... |
def get_url_size(url): """Get the size of a URL. Note: Uses requests, so it does not work for FTP URLs. Source: StackOverflow user "Burhan Khalid". (http://stackoverflow.com/a/24585314/5651021) Parameters ---------- url : str The URL. Returns ------- int The size of the URL in bytes. """ r = requests.head(url, headers=... |
def get_url_file_name(url): """Get the file name from an url Parameters ---------- url : str Returns ------- str The file name """ assert isinstance(url, (str, _oldstr)) return urlparse.urlparse(url).path.split('/')[-1] |
def make_sure_dir_exists(dir_, create_subfolders=False): """Ensures that a directory exists. Adapted from StackOverflow users "Bengt" and "Heikki Toivonen" (http://stackoverflow.com/a/5032238). Parameters ---------- dir_: str The directory path. create_subfolders: bool, optional Whether to create any inexistent subfold... |
def get_file_size(path): """The the size of a file in bytes. Parameters ---------- path: str The path of the file. Returns ------- int The size of the file in bytes. Raises ------ IOError If the file does not exist. OSError If a file system error occurs. """ assert isinstance(path, (str, _oldstr)) if not os.path.isfile... |
def get_file_checksum(path): """Get the checksum of a file (using ``sum``, Unix-only). This function is only available on certain platforms. Parameters ---------- path: str The path of the file. Returns ------- int The checksum. Raises ------ IOError If the file does not exist. """ if not (sys.platform.startswith('linu... |
file_checksum |
def gzip_open_text(path, encoding=None): """Opens a plain-text file that may be gzip'ed. Parameters ---------- path : str The file. encoding : str, optional The encoding to use. Returns ------- file-like A file-like object. Notes ----- Generally, reading gzip'ed files with gzip.open is very slow, and it is preferable t... |
fh |
def bisect_index(a, x): """ Find the leftmost index of an element in a list using binary search. Parameters ---------- a: list A sorted list. x: arbitrary The element. Returns ------- int The index. """ i = bisect.bisect_left(a, x) if i != len(a) and a[i] == x: return i raise ValueError |
def read_single(path, encoding = 'UTF-8'): """ Reads the first column of a tab-delimited text file. The file can either be uncompressed or gzip'ed. Parameters ---------- path: str The path of the file. enc: str The file encoding. Returns ------- List of str A list containing the elements in the first column. """ assert... |
def add_tcp_firewall_rule(project, access_token, name, tag, port): """Adds a TCP firewall rule. TODO: docstring""" headers = { 'Authorization': 'Bearer %s' % access_token.access_token } payload = { "name": name, "kind": "compute#firewall", "sourceRanges": [ "0.0.0.0/0" ], "targetTags": [ tag ], "allowed": [ { "IPProtoc... |
def update(taxids, conn, force_download, silent): """Update local UniProt database""" if not silent: click.secho("WARNING: Update is very time consuming and can take several " "hours depending which organisms you are importing!", fg="yellow") if not taxids: click.echo("Please note that you can restrict import to organi... |
def web(host, port): """Start web application""" from .webserver.web import get_app get_app().run(host=host, port=port) |
def connection(connection, without_connection_test): """Set MySQL/MariaDB connection""" database.set_connection(connection=connection) if not without_connection_test: test_connection(connection) |
def checkCompatibleParams(initialParams, laterParams): """ Check a later set of BLAST parameters against those originally found. @param initialParams: A C{dict} with the originally encountered BLAST parameter settings. @param laterParams: A C{dict} with BLAST parameter settings encountered later. @return: A C{str} summ... |
laterParams[param]): err.append( '\tParam %r initial value %r differs from ' 'later value %r' % (param, initialParams[param], laterParams[param])) else: err.append('\t%r found in initial parameters, not found ' 'in later parameters' % param) for param in laterParams: if param not in initialParams: err.append('\t%r foun... |
def to_list(self): """Converts the GeneSet object to a flat list of strings. Note: see also :meth:`from_list`. Parameters ---------- Returns ------- list of str The data from the GeneSet object as a flat list. """ src = self._source or '' coll = self._collection or '' desc = self._description or '' l = [self._id, src, ... |
def from_list(cls, l): """Generate an GeneSet object from a list of strings. Note: See also :meth:`to_list`. Parameters ---------- l: list or tuple of str A list of strings representing gene set ID, name, genes, source, collection, and description. The genes must be comma-separated. See also :meth:`to_list`. Returns --... |
def findPrimer(primer, seq): """ Look for a primer sequence. @param primer: A C{str} primer sequence. @param seq: A BioPython C{Bio.Seq} sequence. @return: A C{list} of zero-based offsets into the sequence at which the primer can be found. If no instances are found, return an empty C{list}. """ offsets = [] seq = seq.u... |
def findPrimerBidi(primer, seq): """ Look for a primer in a sequence and its reverse complement. @param primer: A C{str} primer sequence. @param seq: A BioPython C{Bio.Seq} sequence. @return: A C{tuple} of two lists. The first contains (zero-based) ascending offsets into the sequence at which the primer can be found. T... |
findPrimer(primer, seq) reverse = findPrimer(reverse_complement(primer), seq) return forward, reverse |
def findPrimerBidiLimits(primer, seq): """ Report the extreme (inner) offsets of primer in a sequence and its reverse complement. @param primer: A C{str} primer sequence. @param seq: A BioPython C{Bio.Seq} sequence. @return: A C{tuple} of two C{int} offsets. The first is a (zero-based) offset into the sequence that is ... |
findPrimerBidi(primer, seq) if forward: start = forward[-1] + len(primer) end = len(seq) for offset in reverse: if offset >= start: end = offset break else: start = 0 end = reverse[0] if reverse else len(seq) return start, end |
def numericallySortFilenames(names): """ Sort (ascending) a list of file names by their numerical prefixes. The number sorted on is the numeric prefix of the basename of the given filename. E.g., '../output/1.json.bz2' will sort before '../output/10.json.bz2'. @param: A C{list} of file names, each of whose basename sta... |
== 0 else int(name[0:count]) return sorted(names, key=lambda name: numericPrefix(basename(name))) |
def asHandle(fileNameOrHandle, mode='r'): """ Decorator for file opening that makes it easy to open compressed files. Based on L{Bio.File.as_handle}. @param fileNameOrHandle: Either a C{str} or a file handle. @return: A generator that can be turned into a context manager via L{contextlib.contextmanager}. """ if isinsta... |
def parseRangeString(s, convertToZeroBased=False): """ Parse a range string of the form 1-5,12,100-200. @param s: A C{str} specifiying a set of numbers, given in the form of comma separated numeric ranges or individual indices. @param convertToZeroBased: If C{True} all indices will have one subtracted from them. @retur... |
def nucleotidesToStr(nucleotides, prefix=''): """ Convert offsets and base counts to a string. @param nucleotides: A C{defaultdict(Counter)} instance, keyed by C{int} offset, with nucleotides keying the Counters. @param prefix: A C{str} to put at the start of each line. @return: A C{str} representation of the offsets a... |
def countPrint(mesg, count, len1, len2=None): """ Format a message followed by an integer count and a percentage (or two, if the sequence lengths are unequal). @param mesg: a C{str} message. @param count: a numeric value. @param len1: the C{int} length of sequence 1. @param len2: the C{int} length of sequence 2. If C{N... |
len1)) else: return ('%s: %d/%d (%.2f%%) of sequence 1, ' '%d/%d (%.2f%%) of sequence 2' % ( mesg, count, len1, percentage(count, len1), count, len2, percentage(count, len2))) |
def upload_scripts(client, script_dir, overwrite=True): """Uploads general-purpose scripts to a Google Storage bucket. TODO: docstring""" local_dir = os.path.join(genometools._root, 'data', 'gcloud', 'scripts') match = _BUCKET_PAT.match(script_dir) script_bucket = match.group(1) script_prefix = match.group(2) depth = l... |
def _getReader(self, filename, scoreClass): """ Obtain a JSON record reader for DIAMOND records. @param filename: The C{str} file name holding the JSON. @param scoreClass: A class to hold and compare scores (see scores.py). """ if filename.endswith('.json') or filename.endswith('.json.bz2'): return JSONRecordsReader(fi... |
def iter(self): """ Extract DIAMOND records and yield C{ReadAlignments} instances. @return: A generator that yields C{ReadAlignments} instances. """ # Note that self._reader is already initialized (in __init__) for # the first input file. This is less clean than it could be, but it # makes testing easier, since open() ... |
def getSubjectSequence(self, title): """ Obtain information about a subject sequence given its title. @param title: A C{str} sequence title from a DIAMOND hit. @raise KeyError: If the C{title} is not present in the DIAMOND database. @return: An C{AAReadWithX} instance. """ if self._subjectTitleToSubject is None: if sel... |
def get_project_urls(project): """Get the URLs for all runs from a given project. TODO: docstring""" urls = [] with ftputil.FTPHost(sra_host, sra_user, sra_password) as ftp_host: download_paths = [] exp_dir = '/sra/sra-instant/reads/ByStudy/sra/SRP/%s/%s/' \ %(project[:6], project) ftp_host.chdir(exp_dir) run_folders =... |
def twos_complement(rst, clk, rx_rdy, rx_vld, rx_dat, tx_rdy, tx_vld, tx_dat): ''' Two's complement conversion of a binary number Input handshake & data rx_rdy - (o) Ready rx_vld - (i) Valid rx_dat - (i) Data Output handshake & data tx_rdy - (i) Ready tx_vld - (o) Valid tx_dat - (o) Data Implementation: 3-stage pipelin... |
pipeline_control( rst = rst, clk = clk, rx_vld = rx_vld, rx_rdy = rx_rdy, tx_vld = tx_vld, tx_rdy = tx_rdy, stage_enable = stage_en) s0_dat = Signal(intbv(0)[DATA_WIDTH:]) @always_seq(clk.posedge, reset=rst) def stage_0(): ''' Register input data''' if (stage_en[0]): s0_dat.next = rx_dat s1_dat = Signal(intbv(0)[DATA_W... |
def get_argument_parser(): """Creates the argument parser for the extract_entrez2gene.py script. Returns ------- A fully configured `argparse.ArgumentParser` object. Notes ----- This function is used by the `sphinx-argparse` extension for sphinx. """ desc = 'Generate a mapping of Entrez IDs to gene symbols.' parser = c... |
parser |
def read_gene2acc(file_path, logger): """Extracts Entrez ID -> gene symbol mapping from gene2accession.gz file. Parameters ---------- file_path: str The path of the gene2accession.gz file (or a filtered version thereof). The file may be gzip'ed. Returns ------- dict A mapping of Entrez IDs to gene symbols. """ gene2acc... |
n, m) return gene2acc |
def write_entrez2gene(file_path, entrez2gene, logger): """Writes Entrez ID -> gene symbol mapping to a tab-delimited text file. Parameters ---------- file_path: str The path of the output file. entrez2gene: dict The mapping of Entrez IDs to gene symbols. Returns ------- None """ with misc.smart_open_write(file_path, mo... |
def main(args=None): """Extracts Entrez ID -> gene symbol mapping and writes it to a text file. Parameters ---------- args: argparse.Namespace object, optional The argument values. If not specified, the values will be obtained by parsing the command line arguments using the `argparse` module. Returns ------- int Exit c... |
sys.stderr logger = misc.get_logger(log_stream=log_stream, log_file=log_file, quiet=quiet, verbose=verbose) entrez2gene = read_gene2acc(gene2acc_file, logger) write_entrez2gene(output_file, entrez2gene, logger) return 0 |
def find(s): """ Find an amino acid whose name or abbreviation is s. @param s: A C{str} amino acid specifier. This may be a full name, a 3-letter abbreviation or a 1-letter abbreviation. Case is ignored. return: An L{AminoAcid} instance or C{None} if no matching amino acid can be located. """ abbrev1 = None origS = s i... |
codons: if codon == target: return abbrev1 abbrev1 = findCodon(origS.upper()) if abbrev1: return AminoAcid( NAMES[abbrev1], ABBREV3[abbrev1], abbrev1, CODONS[abbrev1], PROPERTIES[abbrev1], PROPERTY_DETAILS[abbrev1], PROPERTY_CLUSTERS[abbrev1]) |
def _propertiesOrClustersForSequence(sequence, propertyNames, propertyValues, missingAAValue): """ Extract amino acid property values or cluster numbers for a sequence. @param sequence: An C{AARead} (or a subclass) instance. @param propertyNames: An iterable of C{str} property names (each of which must be a key of a ke... |
one AA. knownProperties = set() for names in propertyValues.values(): knownProperties.update(names) unknown = set(propertyNames) - knownProperties if unknown: raise ValueError( 'Unknown propert%s: %s.' % ('y' if len(unknown) == 1 else 'ies', ', '.join(unknown))) aas = sequence.sequence.upper() result = {} for propertyN... |
def matchToString(aaMatch, read1, read2, indent='', offsets=None): """ Format amino acid sequence match as a string. @param aaMatch: A C{dict} returned by C{compareAaReads}. @param read1: A C{Read} instance or an instance of one of its subclasses. @param read2: A C{Read} instance or an instance of one of its subclasses... |
gapGapMismatchCount + nonGapMismatchCount) append(countPrint('%sMismatches' % indent, mismatchCount, len1, len2)) append(countPrint('%s Not involving gaps (i.e., conflicts)' % (indent), nonGapMismatchCount, len1, len2)) append(countPrint('%s Involving a gap in one sequence' % indent, gapMismatchCount, len1, len2)) appe... |
def compareAaReads(read1, read2, gapChars='-', offsets=None): """ Compare two amino acid sequences. @param read1: A C{Read} instance or an instance of one of its subclasses. @param read2: A C{Read} instance or an instance of one of its subclasses. @param gapChars: An object supporting __contains__ with characters that ... |
set # to be passed. if offsets is not None and offset not in offsets: continue if a is None: # b has an extra character at its end (it cannot be None). assert b is not None read2ExtraCount += 1 if b in gapChars: read2GapOffsets.append(offset) elif b is None: # a has an extra character at its end. read1ExtraCount += 1 i... |
in gapChars: # b is a gap, a is not. gapMismatchCount += 1 read2GapOffsets.append(offset) else: # Neither is a gap character. if a == b: matchCount += 1 else: nonGapMismatchCount += 1 return { 'match': { 'matchCount': matchCount, 'gapMismatchCount': gapMismatchCount, 'gapGapMismatchCount': gapGapMismatchCount, 'nonGapM... |
def parseColors(colors, args): """ Parse read id color specification. @param colors: A C{list} of C{str}s. Each item is of the form, e.g., 'green X Y Z...', where each of X, Y, Z, ... etc. is either a read id or the name of a FASTA or FASTQ file containing reads whose ids should be displayed with the corresponding colo... |
in readIds: if os.path.isfile(readId): filename = readId if args.fasta: reads = FastaReads(filename) else: reads = FastqReads(filename) for read in reads: result[color].add(read.id) else: result[color].add(readId) return result |
def download_release(download_file, release=None): """Downloads the "go-basic.obo" file for the specified release.""" if release is None: release = get_latest_release() url = 'http://viewvc.geneontology.org/viewvc/GO-SVN/ontology-releases/%s/go-basic.obo' % release #download_file = 'go-basic_%s.obo' % release misc.http... |
def get_current_ontology_date(): """Get the release date of the current Gene Ontolgo release.""" with closing(requests.get( 'http://geneontology.org/ontology/go-basic.obo', stream=True)) as r: for i, l in enumerate(r.iter_lines(decode_unicode=True)): if i == 1: assert l.split(':')[0] == 'data-version' date = l.split('/... |
def execute(function, name): """ Execute a task, returning a TaskResult """ try: return TaskResult(name, True, None, function()) except Exception as exc: return TaskResult(name, False, exc, None) |
def truncatechars(value, arg): """ Truncates a string after a certain number of chars. Argument: Number of chars to truncate after. """ try: length = int(arg) except ValueError: # Invalid literal for int(). return value # Fail silently. if len(value) > length: return value[:length] + '...' return value |
def handler500(request): """ 500 error handler. Templates: `500.html` Context: None """ from django.template import Context, loader from django.http import HttpResponseServerError from overseer.context_processors import default import logging import sys try: context = default(request) except Exception, e: logging.error... |
def get_gtf_argument_parser(desc, default_field_name='gene'): """Return an argument parser with basic options for reading GTF files. Parameters ---------- desc: str Description of the ArgumentParser default_field_name: str, optional Name of field in GTF file to look for. Returns ------- `argparse.ArgumentParser` object... |
required=False, default=None, help=textwrap.dedent("""\ Regular expression that chromosome names have to match. [None] """) ) #parser.add_argument( # '-f', '--field-name', type=str, default=default_field_name, # help=textwrap.dedent("""\ # Rows in the GTF file that do not contain this value # in the third column are ig... |
def jsonresolver_loader(url_map): """JSON resolver plugin that loads the schema endpoint. Injected into Invenio-Records JSON resolver. """ from flask import current_app from . import current_jsonschemas url_map.add(Rule( "{0}/<path:path>".format(current_app.config['JSONSCHEMAS_ENDPOINT']), endpoint=current_jsonschemas.... |
def merge_layouts(layouts): ''' Utility function for merging multiple layouts. Args: layouts (list): A list of BIDSLayout instances to merge. Returns: A BIDSLayout containing merged files and entities. Notes: Layouts will be merged in the order of the elements in the list. I.e., the first Layout will be updated with al... |
def _matches(self, entities=None, extensions=None, domains=None, regex_search=False): """ Checks whether the file matches all of the passed entities and extensions. Args: entities (dict): A dictionary of entity names -> regex patterns. extensions (str, list): One or more file extensions to allow. domains (str, list): O... |
name, val in entities.items(): if (name not in self.tags) ^ (val is None): return False if val is None: continue def make_patt(x): patt = '%s' % x if isinstance(x, (int, float)): # allow for leading zeros if a number was specified # regardless of regex_search patt = '0*' + patt if not regex_search: patt = '^%s$' % patt... |
def as_named_tuple(self): """ Returns the File as a named tuple. The full path plus all entity key/value pairs are returned as attributes. """ keys = list(self.entities.keys()) replaced = [] for i, k in enumerate(keys): if iskeyword(k): replaced.append(k) keys[i] = '%s_' % k if replaced: safe = ['%s_' % k for k in repl... |
def copy(self, path_patterns, symbolic_link=False, root=None, conflicts='fail'): ''' Copy the contents of a file to a new location, with target filename defined by the current File's entities and the specified path_patterns. ''' new_filename = build_path(self.entities, path_patterns) if not new_filename: return None if... |
def match_file(self, f, update_file=False): """ Determine whether the passed file matches the Entity. Args: f (File): The File instance to match against. Returns: the matched value if a match was found, otherwise None. """ if self.map_func is not None: val = self.map_func(f) else: m = self.regex.search(f.path) val = m.... |
def _get_or_load_domain(self, domain): ''' Return a domain if one already exists, or create a new one if not. Args: domain (str, dict): Can be one of: - The name of the Domain to return (fails if none exists) - A path to the Domain configuration file - A dictionary containing configuration information ''' if isinstance... |
" "Domain configuration.".format(name)) warnings.warn(msg) return self.domains[name] entities = domain.get('entities', []) domain = Domain(domain) for e in entities: self.add_entity(domain=domain, **e) self.domains[name] = domain return self.domains[name] |
def _check_inclusions(self, f, domains=None): ''' Check file or directory against regexes in config to determine if it should be included in the index ''' filename = f if isinstance(f, six.string_types) else f.path if domains is None: domains = list(self.domains.values()) # Inject the Layout at the first position for g... |
def _find_entity(self, entity): ''' Find an Entity instance by name. Checks both name and id fields.''' if entity in self.entities: return self.entities[entity] _ent = [e for e in self.entities.values() if e.name == entity] if len(_ent) > 1: raise ValueError("Entity name '%s' matches %d entities. To " "avoid ambiguity,... |
def save_index(self, filename): ''' Save the current Layout's index to a .json file. Args: filename (str): Filename to write to. Note: At the moment, this won't serialize directory-specific config files. This means reconstructed indexes will only work properly in cases where there aren't multiple layout specs within a ... |
def load_index(self, filename, reindex=False): ''' Load the Layout's index from a plaintext file. Args: filename (str): Path to the plaintext index file. reindex (bool): If True, discards entity values provided in the loaded index and instead re-indexes every file in the loaded index against the entities defined in the... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.