INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Set API token by authenticating via username/password. :param retries: Number of authentication attempts to make before giving up as an int. :return: Learned API token :rtype: string
def authenticate(self, retries=3): """Set API token by authenticating via username/password. :param retries: Number of authentication attempts to make before giving up as an int. :return: Learned API token :rtype: string """ username = self.username or self._getuser(sel...
Get user email from github.
def _extract_email(gh): """Get user email from github.""" return next( (x.email for x in gh.emails() if x.verified and x.primary), None)
Retrieve remote account information used to find local user. It returns a dictionary with the following structure: .. code-block:: python { 'user': { 'email': '...', 'profile': { 'username': '...', 'full_name': '...',...
def account_info(remote, resp): """Retrieve remote account information used to find local user. It returns a dictionary with the following structure: .. code-block:: python { 'user': { 'email': '...', 'profile': { 'username': '...', ...
Perform additional setup after user have been logged in. :param remote: The remote application. :param token: The token value. :param resp: The response.
def account_setup(remote, token, resp): """Perform additional setup after user have been logged in. :param remote: The remote application. :param token: The token value. :param resp: The response. """ gh = github3.login(token=resp['access_token']) with db.session.begin_nested(): me ...
Authorized callback handler for GitHub. :param resp: The response. :param remote: The remote application.
def authorized(resp, remote): """Authorized callback handler for GitHub. :param resp: The response. :param remote: The remote application. """ if resp and 'error' in resp: if resp['error'] == 'bad_verification_code': # See https://developer.github.com/v3/oauth/#bad-verification-...
Construct an equal to (``=``) filter. :param value: Filter value :return: :class:`filters.Field <filters.Field>` object :rtype: filters.Field
def eq(self, value): """Construct an equal to (``=``) filter. :param value: Filter value :return: :class:`filters.Field <filters.Field>` object :rtype: filters.Field """ self.op = '=' self.negate_op = '!=' self.value = self._value(value) return se...
Construct a not equal to (``!=``) filter. :param value: Filter value :return: :class:`filters.Field <filters.Field>` object :rtype: filters.Field
def ne(self, value): """Construct a not equal to (``!=``) filter. :param value: Filter value :return: :class:`filters.Field <filters.Field>` object :rtype: filters.Field """ self.op = '!=' self.negate_op = '=' self.value = self._value(value) retur...
Construct a greater than (``>``) filter. :param value: Filter value :return: :class:`filters.Field <filters.Field>` object :rtype: filters.Field
def gt(self, value): """Construct a greater than (``>``) filter. :param value: Filter value :return: :class:`filters.Field <filters.Field>` object :rtype: filters.Field """ self.op = '>' self.negate_op = '<=' self.value = self._value(value) return...
Construct a greater than or equal to (``>=``) filter. :param value: Filter value :return: :class:`filters.Field <filters.Field>` object :rtype: filters.Field
def ge(self, value): """Construct a greater than or equal to (``>=``) filter. :param value: Filter value :return: :class:`filters.Field <filters.Field>` object :rtype: filters.Field """ self.op = '>=' self.negate_op = '<' self.value = self._value(value) ...
Construct a less than (``<``) filter. :param value: Filter value :return: :class:`filters.Field <filters.Field>` object :rtype: filters.Field
def lt(self, value): """Construct a less than (``<``) filter. :param value: Filter value :return: :class:`filters.Field <filters.Field>` object :rtype: filters.Field """ self.op = '<' self.negate_op = '>=' self.value = self._value(value) return se...
Construct a less than or equal to (``<=``) filter. :param value: Filter value :return: :class:`filters.Field <filters.Field>` object :rtype: filters.Field
def le(self, value): """Construct a less than or equal to (``<=``) filter. :param value: Filter value :return: :class:`filters.Field <filters.Field>` object :rtype: filters.Field """ self.op = '<=' self.negate_op = '>' self.value = self._value(value) ...
Construct a regexp match (``~``) filter. Combine with ``not_`` method to construct a negative regexp match (``!~``) filter. :param value: Filter value :param ignorecase: If bool `True`, make match case insensitive (``~*``, ``!~*``) :return: :class:`filters.Field <filters.Field>` object ...
def match(self, value, ignorecase=False): """Construct a regexp match (``~``) filter. Combine with ``not_`` method to construct a negative regexp match (``!~``) filter. :param value: Filter value :param ignorecase: If bool `True`, make match case insensitive (``~*``, ``!~*``) :return: ...
Construct an array contains (``@>``) filter. :param args: Filter values :return: :class:`filters.Field <filters.Field>` object :rtype: filters.Field
def contains(self, *args): """Construct an array contains (``@>``) filter. :param args: Filter values :return: :class:`filters.Field <filters.Field>` object :rtype: filters.Field """ self.op = '@>' self.negate_op = None self.value = self._array_value(args...
Construct an array contained by (``<@``) filter. :param args: Filter values :return: :class:`filters.Field <filters.Field>` object :rtype: filters.Field
def contained_by(self, *args): """Construct an array contained by (``<@``) filter. :param args: Filter values :return: :class:`filters.Field <filters.Field>` object :rtype: filters.Field """ self.op = '<@' self.negate_op = None self.value = self._array_va...
Construct an array overlaps (``&&``) filter. :param args: Filter values :return: :class:`filters.Field <filters.Field>` object :rtype: filters.Field
def overlaps(self, *args): """Construct an array overlaps (``&&``) filter. :param args: Filter values :return: :class:`filters.Field <filters.Field>` object :rtype: filters.Field """ self.op = '&&' self.negate_op = None self.value = self._array_value(args...
Get all unique sequences from reads spanning a variant locus. This will include partial sequences due to reads starting in the middle of the sequence around around a variant.
def initial_variant_sequences_from_reads( variant_reads, max_nucleotides_before_variant=None, max_nucleotides_after_variant=None): """ Get all unique sequences from reads spanning a variant locus. This will include partial sequences due to reads starting in the middle of the sequ...
Trim VariantSequences to desired coverage and then combine any subsequences which get generated.
def trim_variant_sequences(variant_sequences, min_variant_sequence_coverage): """ Trim VariantSequences to desired coverage and then combine any subsequences which get generated. """ n_total = len(variant_sequences) trimmed_variant_sequences = [ variant_sequence.trim_by_coverage(min_vari...
Drop variant sequences which are shorter than request or don't have enough supporting reads.
def filter_variant_sequences( variant_sequences, preferred_sequence_length, min_variant_sequence_coverage=MIN_VARIANT_SEQUENCE_COVERAGE,): """ Drop variant sequences which are shorter than request or don't have enough supporting reads. """ variant_sequences = trim_variant_seq...
Collapse variant-supporting RNA reads into consensus sequences of approximately the preferred length (may differ at the ends of transcripts), filter consensus sequences by length and number of supporting RNA reads. Parameters ---------- variant : varcode.Variant reads : list of AlleleRead obje...
def reads_to_variant_sequences( variant, reads, preferred_sequence_length, min_alt_rna_reads=MIN_ALT_RNA_READS, min_variant_sequence_coverage=MIN_VARIANT_SEQUENCE_COVERAGE, variant_sequence_assembly=VARIANT_SEQUENCE_ASSEMBLY): """ Collapse variant-supporting RNA r...
For each variant, collect all possible sequence contexts around the variant which are spanned by at least min_reads. Parameters ---------- variant_and_reads_generator : generator Sequence of Variant objects paired with a list of reads which overlap that variant. min_alt_rna_reads :...
def reads_generator_to_sequences_generator( variant_and_reads_generator, min_alt_rna_reads=MIN_ALT_RNA_READS, min_variant_sequence_coverage=MIN_VARIANT_SEQUENCE_COVERAGE, preferred_sequence_length=VARIANT_SEQUENCE_LENGTH, variant_sequence_assembly=VARIANT_SEQUENCE_ASSEMBLY): ...
Creates a dataframe from a generator which yields (Variant, [VariantSequence]) pairs. Returns pandas.DataFrame
def variant_sequences_generator_to_dataframe(variant_sequences_generator): """ Creates a dataframe from a generator which yields (Variant, [VariantSequence]) pairs. Returns pandas.DataFrame """ # TODO: Change VariantSequence.alt to VariantSequence.alt_nucleotides # or something else that do...
Is the other VariantSequence a subsequence of this one? The two sequences must agree on the alt nucleotides, the prefix of the longer must contain the prefix of the shorter, and the suffix of the longer must contain the suffix of the shorter.
def contains(self, other): """ Is the other VariantSequence a subsequence of this one? The two sequences must agree on the alt nucleotides, the prefix of the longer must contain the prefix of the shorter, and the suffix of the longer must contain the suffix of the shorter. ...
Does this VariantSequence overlap another on the left side?
def left_overlaps(self, other, min_overlap_size=1): """ Does this VariantSequence overlap another on the left side? """ if self.alt != other.alt: # allele must match! return False if len(other.prefix) > len(self.prefix): # only consider strin...
Create another VariantSequence with more supporting reads.
def add_reads(self, reads): """ Create another VariantSequence with more supporting reads. """ if len(reads) == 0: return self new_reads = self.reads.union(reads) if len(new_reads) > len(self.reads): return VariantSequence( prefix=s...
If this sequence is the prefix of another sequence, combine them into a single VariantSequence object. If the other sequence is contained in this one, then add its reads to this VariantSequence. Also tries to flip the order (e.g. this sequence is a suffix or this sequence is a subsequenc...
def combine(self, other_sequence): """ If this sequence is the prefix of another sequence, combine them into a single VariantSequence object. If the other sequence is contained in this one, then add its reads to this VariantSequence. Also tries to flip the order (e.g. this sequen...
When we combine prefix + alt + suffix into a single string, what are is base-0 index interval which gets us back the alt sequence? First returned index is inclusive, the second is exclusive.
def variant_indices(self): """ When we combine prefix + alt + suffix into a single string, what are is base-0 index interval which gets us back the alt sequence? First returned index is inclusive, the second is exclusive. """ variant_start_index = len(self.prefix) ...
Returns NumPy array indicating number of reads covering each nucleotides of this sequence.
def coverage(self): """ Returns NumPy array indicating number of reads covering each nucleotides of this sequence. """ variant_start_index, variant_end_index = self.variant_indices() n_nucleotides = len(self) coverage_array = np.zeros(n_nucleotides, dtype="int32")...
Given the min number of reads overlapping each nucleotide of a variant sequence, trim this sequence by getting rid of positions which are overlapped by fewer reads than specified.
def trim_by_coverage(self, min_reads): """ Given the min number of reads overlapping each nucleotide of a variant sequence, trim this sequence by getting rid of positions which are overlapped by fewer reads than specified. """ read_count_array = self.coverage() lo...
Load test data fixture.
def records(): """Load test data fixture.""" with db.session.begin_nested(): for idx in range(20): # create the record id_ = uuid.uuid4() Record.create({ 'title': 'LHC experiment {}'.format(idx), 'description': 'Data from experiment {}....
Drop all occurrences of 'N' from prefix and suffix nucleotide strings by trimming.
def trim_N_nucleotides(prefix, suffix): """ Drop all occurrences of 'N' from prefix and suffix nucleotide strings by trimming. """ if 'N' in prefix: # trim prefix to exclude all occurrences of N rightmost_index = prefix.rfind('N') logger.debug( "Trimming %d nucleo...
Depending on how we extract data from pysam we may end up with either a string or a byte array of nucleotides. For consistency and simplicity, we want to only use strings in the rest of our code.
def convert_from_bytes_if_necessary(prefix, suffix): """ Depending on how we extract data from pysam we may end up with either a string or a byte array of nucleotides. For consistency and simplicity, we want to only use strings in the rest of our code. """ if isinstance(prefix, bytes): p...
Given a SAM/BAM file and a collection of variants, generates a sequence of variants paired with reads which support each variant.
def reads_supporting_variants(variants, samfile, **kwargs): """ Given a SAM/BAM file and a collection of variants, generates a sequence of variants paired with reads which support each variant. """ for variant, allele_reads in reads_overlapping_variants( variants=variants, sa...
Validate operation type.
def publish(self, data, **kwargs): """Validate operation type.""" assert data.get('op') in {'index', 'create', 'delete', 'update'} return super(Producer, self).publish(data, **kwargs)
Index a record. The caller is responsible for ensuring that the record has already been committed to the database. If a newer version of a record has already been indexed then the provided record will not be indexed. This behavior can be controlled by providing a different ``version_typ...
def index(self, record): """Index a record. The caller is responsible for ensuring that the record has already been committed to the database. If a newer version of a record has already been indexed then the provided record will not be indexed. This behavior can be controlled by...
Delete a record. :param record: Record instance.
def delete(self, record): """Delete a record. :param record: Record instance. """ index, doc_type = self.record_to_index(record) return self.client.delete( id=str(record.id), index=index, doc_type=doc_type, )
Process bulk indexing queue. :param dict es_bulk_kwargs: Passed to :func:`elasticsearch:elasticsearch.helpers.bulk`.
def process_bulk_queue(self, es_bulk_kwargs=None): """Process bulk indexing queue. :param dict es_bulk_kwargs: Passed to :func:`elasticsearch:elasticsearch.helpers.bulk`. """ with current_celery_app.pool.acquire(block=True) as conn: consumer = Consumer( ...
Context manager that yields an instance of ``Producer``.
def create_producer(self): """Context manager that yields an instance of ``Producer``.""" with current_celery_app.pool.acquire(block=True) as conn: yield Producer( conn, exchange=self.mq_exchange, routing_key=self.mq_routing_key, ...
Index record in Elasticsearch asynchronously. :param record_id_iterator: Iterator that yields record UUIDs. :param op_type: Indexing operation (one of ``index``, ``create``, ``delete`` or ``update``). :param index: The Elasticsearch index. (Default: ``None``) :param doc_type...
def _bulk_op(self, record_id_iterator, op_type, index=None, doc_type=None): """Index record in Elasticsearch asynchronously. :param record_id_iterator: Iterator that yields record UUIDs. :param op_type: Indexing operation (one of ``index``, ``create``, ``delete`` or ``update``). ...
Iterate bulk actions. :param message_iterator: Iterator yielding messages from a queue.
def _actionsiter(self, message_iterator): """Iterate bulk actions. :param message_iterator: Iterator yielding messages from a queue. """ for message in message_iterator: payload = message.decode() try: if payload['op'] == 'delete': ...
Bulk delete action. :param payload: Decoded message body. :returns: Dictionary defining an Elasticsearch bulk 'delete' action.
def _delete_action(self, payload): """Bulk delete action. :param payload: Decoded message body. :returns: Dictionary defining an Elasticsearch bulk 'delete' action. """ index, doc_type = payload.get('index'), payload.get('doc_type') if not (index and doc_type): ...
Bulk index action. :param payload: Decoded message body. :returns: Dictionary defining an Elasticsearch bulk 'index' action.
def _index_action(self, payload): """Bulk index action. :param payload: Decoded message body. :returns: Dictionary defining an Elasticsearch bulk 'index' action. """ record = Record.get_record(payload['id']) index, doc_type = self.record_to_index(record) return ...
Prepare record data for indexing. :param record: The record to prepare. :param index: The Elasticsearch index. :param doc_type: The Elasticsearch document type. :returns: The record metadata.
def _prepare_record(record, index, doc_type): """Prepare record data for indexing. :param record: The record to prepare. :param index: The Elasticsearch index. :param doc_type: The Elasticsearch document type. :returns: The record metadata. """ if current_app.con...
Returns a list of merged VariantSequence objects, and True if any were successfully merged.
def greedy_merge_helper( variant_sequences, min_overlap_size=MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE): """ Returns a list of merged VariantSequence objects, and True if any were successfully merged. """ merged_variant_sequences = {} merged_any = False # here we'll keep tr...
Greedily merge overlapping sequences into longer sequences. Accepts a collection of VariantSequence objects and returns another collection of elongated variant sequences. The reads field of the returned VariantSequence object will contain reads which only partially overlap the full sequence.
def greedy_merge( variant_sequences, min_overlap_size=MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE): """ Greedily merge overlapping sequences into longer sequences. Accepts a collection of VariantSequence objects and returns another collection of elongated variant sequences. The reads fie...
Combine shorter sequences which are fully contained in longer sequences. Parameters ---------- variant_sequences : list List of VariantSequence objects Returns a (potentially shorter) list without any contained subsequences.
def collapse_substrings(variant_sequences): """ Combine shorter sequences which are fully contained in longer sequences. Parameters ---------- variant_sequences : list List of VariantSequence objects Returns a (potentially shorter) list without any contained subsequences. """ if...
Assembles longer sequences from reads centered on a variant by between merging all pairs of overlapping sequences and collapsing shorter sequences onto every longer sequence which contains them. Returns a list of variant sequences, sorted by decreasing read support.
def iterative_overlap_assembly( variant_sequences, min_overlap_size=MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE): """ Assembles longer sequences from reads centered on a variant by between merging all pairs of overlapping sequences and collapsing shorter sequences onto every longer sequen...
Group elements of the list `xs` by keys generated from calling `key_fn`. Returns a dictionary which maps keys to sub-lists of `xs`.
def groupby(xs, key_fn): """ Group elements of the list `xs` by keys generated from calling `key_fn`. Returns a dictionary which maps keys to sub-lists of `xs`. """ result = defaultdict(list) for x in xs: key = key_fn(x) result[key].append(x) return result
Generates an orthonormal basis in the plane perpendicular to `normal` The orthonormal basis generated spans the plane defined with `normal` as its normal vector. The handedness of `on1` and `on2` in the returned basis is such that: .. math:: \\mathsf{on1} \\times \\mathsf{on2} = ...
def ortho_basis(normal, ref_vec=None): """Generates an orthonormal basis in the plane perpendicular to `normal` The orthonormal basis generated spans the plane defined with `normal` as its normal vector. The handedness of `on1` and `on2` in the returned basis is such that: .. math:: ...
Checks orthonormality of the column vectors of a matrix. If a one-dimensional |nparray| is passed to `a`, it is treated as a single column vector, rather than a row matrix of length-one column vectors. The matrix `a` does not need to be square, though it must have at least as many rows as columns, sin...
def orthonorm_check(a, tol=_DEF.ORTHONORM_TOL, report=False): """Checks orthonormality of the column vectors of a matrix. If a one-dimensional |nparray| is passed to `a`, it is treated as a single column vector, rather than a row matrix of length-one column vectors. The matrix `a` does not need to be ...
Checks whether two vectors are parallel OR anti-parallel. Vectors must be of the same dimension. Parameters ---------- vec1 length-R |npfloat_| -- First vector to compare vec2 length-R |npfloat_| -- Second vector to compare Returns ------- par ...
def parallel_check(vec1, vec2): """Checks whether two vectors are parallel OR anti-parallel. Vectors must be of the same dimension. Parameters ---------- vec1 length-R |npfloat_| -- First vector to compare vec2 length-R |npfloat_| -- Second vector to compare ...
Vector projection. Calculated as: .. math:: \\mathsf{vec\\_onto} * \\frac{\\mathsf{vec}\\cdot\\mathsf{vec\\_onto}} {\\mathsf{vec\\_onto}\\cdot\\mathsf{vec\\_onto}} Parameters ---------- vec length-R |npfloat_| -- Vector to project vec_onto length-R ...
def proj(vec, vec_onto): """ Vector projection. Calculated as: .. math:: \\mathsf{vec\\_onto} * \\frac{\\mathsf{vec}\\cdot\\mathsf{vec\\_onto}} {\\mathsf{vec\\_onto}\\cdot\\mathsf{vec\\_onto}} Parameters ---------- vec length-R |npfloat_| -- Vector to projec...
Vector rejection. Calculated by subtracting from `vec` the projection of `vec` onto `vec_onto`: .. math:: \\mathsf{vec} - \\mathrm{proj}\\left(\\mathsf{vec}, \\ \\mathsf{vec\\_onto}\\right) Parameters ---------- vec length-R |npfloat_| -- Vector to reject ...
def rej(vec, vec_onto): """ Vector rejection. Calculated by subtracting from `vec` the projection of `vec` onto `vec_onto`: .. math:: \\mathsf{vec} - \\mathrm{proj}\\left(\\mathsf{vec}, \\ \\mathsf{vec\\_onto}\\right) Parameters ---------- vec length-R |npfloat_| ...
Angle between two R-dimensional vectors. Angle calculated as: .. math:: \\arccos\\left[ \\frac{\\mathsf{vec1}\cdot\\mathsf{vec2}} {\\left\\|\\mathsf{vec1}\\right\\| \\left\\|\\mathsf{vec2}\\right\\|} \\right] Parameters ---------- vec1 length-R...
def vec_angle(vec1, vec2): """ Angle between two R-dimensional vectors. Angle calculated as: .. math:: \\arccos\\left[ \\frac{\\mathsf{vec1}\cdot\\mathsf{vec2}} {\\left\\|\\mathsf{vec1}\\right\\| \\left\\|\\mathsf{vec2}\\right\\|} \\right] Parameters -...
Do all of the gruntwork associated with creating a new module.
def new_module(name): """ Do all of the gruntwork associated with creating a new module. """ parent = None if '.' in name: parent_name = name.rsplit('.', 1)[0] parent = __import__(parent_name, fromlist=['']) module = imp.new_module(name) sys.modules[name] = module if pa...
Creates a DataFrame containing number of reads supporting the ref vs. alt alleles for each variant.
def allele_counts_dataframe(variant_and_allele_reads_generator): """ Creates a DataFrame containing number of reads supporting the ref vs. alt alleles for each variant. """ df_builder = DataFrameBuilder( AlleleCount, extra_column_fns={ "gene": lambda variant, _: ";".join(...
Install Postgres extension.
def install_extension(conn, extension: str): """Install Postgres extension.""" query = 'CREATE EXTENSION IF NOT EXISTS "%s";' with conn.cursor() as cursor: cursor.execute(query, (AsIs(extension),)) installed = check_extension(conn, extension) if not installed: raise psycopg2.Prog...
Check to see if an extension is installed.
def check_extension(conn, extension: str) -> bool: """Check to see if an extension is installed.""" query = 'SELECT installed_version FROM pg_available_extensions WHERE name=%s;' with conn.cursor() as cursor: cursor.execute(query, (extension,)) result = cursor.fetchone() if result is ...
rangeobject.count(value) -> integer -- return number of occurrences of value
def count(self, i): """rangeobject.count(value) -> integer -- return number of occurrences of value """ if self._stop > self._start and self._step > 0: return int(self._start <= i < self._stop and (i - self._start) % self._step == 0) elif self._...
xrangeobject.index(value, [start, [stop]]) -> integer -- return index of value. Raise ValueError if the value is not present.
def index(self, i): """xrangeobject.index(value, [start, [stop]]) -> integer -- return index of value. Raise ValueError if the value is not present. """ if self.count(i) == 0: raise ValueError("{} is not in range".format(i)) return (i - self._start) // self._s...
Ensure obj is iterable.
def make_iterable(obj, default=None): """ Ensure obj is iterable. """ if obj is None: return default or [] if isinstance(obj, (compat.string_types, compat.integer_types)): return [obj] return obj
Return an iterator over corpus documents.
def iter_documents(self, fileids=None, categories=None, _destroy=False): """ Return an iterator over corpus documents. """ doc_ids = self._filter_ids(fileids, categories) for doc in imap(self.get_document, doc_ids): yield doc if _destroy: doc.destroy()
Return information about documents in corpora: a list of tuples (doc_id, doc_title).
def catalog(self, categories=None): """ Return information about documents in corpora: a list of tuples (doc_id, doc_title). """ ids = self._filter_ids(None, categories) doc_meta = self._get_meta() return [(doc_id, doc_meta[doc_id].title) for doc_id in ids]
Try to dump metadata to a file.
def _create_meta_cache(self): """ Try to dump metadata to a file. """ try: with open(self._cache_filename, 'wb') as f: compat.pickle.dump(self._document_meta, f, 1) except (IOError, compat.pickle.PickleError): pass
Try to load metadata from file.
def _load_meta_cache(self): """ Try to load metadata from file. """ try: if self._should_invalidate_cache(): os.remove(self._cache_filename) else: with open(self._cache_filename, 'rb') as f: self._document_meta = compat.pickle.l...
Return documents meta information that can be used for fast document lookups. Meta information consists of documents titles, categories and positions in file.
def _compute_document_meta(self): """ Return documents meta information that can be used for fast document lookups. Meta information consists of documents titles, categories and positions in file. """ meta = OrderedDict() bounds_iter = xml_utils.bounds(se...
Return xml Element for the document document_id.
def _document_xml(self, doc_id): """ Return xml Element for the document document_id. """ doc_str = self._get_doc_by_raw_offset(str(doc_id)) return compat.ElementTree.XML(doc_str.encode('utf8'))
Load document from xml using bytes offset information. XXX: this is not tested under Windows.
def _get_doc_by_raw_offset(self, doc_id): """ Load document from xml using bytes offset information. XXX: this is not tested under Windows. """ bounds = self._get_meta()[str(doc_id)].bounds return xml_utils.load_chunk(self.filename, bounds)
Load document from xml using line offset information. This is much slower than _get_doc_by_raw_offset but should work everywhere.
def _get_doc_by_line_offset(self, doc_id): """ Load document from xml using line offset information. This is much slower than _get_doc_by_raw_offset but should work everywhere. """ bounds = self._get_meta()[str(doc_id)].bounds return xml_utils.load_chunk(self.file...
Return Ma, where M is a 3x3 transformation matrix, for each pixel
def _threeDdot_simple(M,a): "Return Ma, where M is a 3x3 transformation matrix, for each pixel" result = np.empty(a.shape,dtype=a.dtype) for i in range(a.shape[0]): for j in range(a.shape[1]): A = np.array([a[i,j,0],a[i,j,1],a[i,j,2]]).reshape((3,1)) L = np.dot(M,A) ...
Reverse the order of an LCH numpy dstack or tuple for analysis.
def _swaplch(LCH): "Reverse the order of an LCH numpy dstack or tuple for analysis." try: # Numpy array L,C,H = np.dsplit(LCH,3) return np.dstack((H,C,L)) except: # Tuple L,C,H = LCH return H,C,L
Convert image or color "what" from "from_" colorpace to "to" colorspace. E.g.: ``convert("rgb", "hsv", X)``, where X is a numpy dstack or a color tuple.
def convert(self, from_, to, what): """ Convert image or color "what" from "from_" colorpace to "to" colorspace. E.g.: ``convert("rgb", "hsv", X)``, where X is a numpy dstack or a color tuple. """ if(from_.lower()==to.lower()): return what # Check i...
linear rgb to hsv
def rgb_to_hsv(self,RGB): "linear rgb to hsv" gammaRGB = self._gamma_rgb(RGB) return self._ABC_to_DEF_by_fn(gammaRGB,rgb_to_hsv)
hsv to linear rgb
def hsv_to_rgb(self,HSV): "hsv to linear rgb" gammaRGB = self._ABC_to_DEF_by_fn(HSV,hsv_to_rgb) return self._ungamma_rgb(gammaRGB)
Transform images i provided into the specified working color space.
def image2working(self,i): """Transform images i provided into the specified working color space.""" return self.colorspace.convert(self.image_space, self.working_space, i)
Transform working space inputs to the analysis color space.
def working2analysis(self,r): "Transform working space inputs to the analysis color space." a = self.colorspace.convert(self.working_space, self.analysis_space, r) return self.swap_polar_HSVorder[self.analysis_space](a)
Convert back from the analysis color space to the working space.
def analysis2working(self,a): "Convert back from the analysis color space to the working space." a = self.swap_polar_HSVorder[self.analysis_space](a) return self.colorspace.convert(self.analysis_space, self.working_space, a)
Utility conversion function that transforms data from the analysis color space to the display space (currently hard-set to RGB) for visualization.
def analysis2display(self,a): """ Utility conversion function that transforms data from the analysis color space to the display space (currently hard-set to RGB) for visualization. """ a = self.swap_polar_HSVorder[self.analysis_space](a) return self.colorspace.con...
iterparse variant that supports 'tag' parameter (like lxml), yields elements and clears nodes after parsing.
def iterparse(source, tag, clear=False, events=None): """ iterparse variant that supports 'tag' parameter (like lxml), yields elements and clears nodes after parsing. """ for event, elem in ElementTree.iterparse(source, events=events): if elem.tag == tag: yield elem if cl...
Compute chunk bounds from text file according to start_re and end_re: yields (start_match, Bounds) tuples.
def bounds(filename, start_re, end_re, encoding='utf8'): """ Compute chunk bounds from text file according to start_re and end_re: yields (start_match, Bounds) tuples. """ start_re, end_re = re.compile(start_re), re.compile(end_re) mo, line_start, line_end, byte_start, byte_end = [None]*5 of...
Load a chunk from file using Bounds info. Pass 'slow=True' for an alternative loading method based on line numbers.
def load_chunk(filename, bounds, encoding='utf8', slow=False): """ Load a chunk from file using Bounds info. Pass 'slow=True' for an alternative loading method based on line numbers. """ if slow: return _load_chunk_slow(filename, bounds, encoding) with open(filename, 'rb') as f: ...
Extends an ArgumentParser instance with the following commandline arguments: --context-size
def add_reference_context_args(parser): """ Extends an ArgumentParser instance with the following commandline arguments: --context-size """ reference_context_group = parser.add_argument_group("Reference Transcripts") parser.add_argument( "--context-size", default=CDNA_CONTEXT...
Generate postgresql numeric range and label for insertion. Parameters ---------- items: iterable labels for ranges. lower_bound: numeric lower bound upper_bound: numeric upper bound
def generate_numeric_range(items, lower_bound, upper_bound): """Generate postgresql numeric range and label for insertion. Parameters ---------- items: iterable labels for ranges. lower_bound: numeric lower bound upper_bound: numeric upper bound """ quantile_grid = create_quantiles(ite...
Return the mean value around the edge of an array.
def edge_average(a): "Return the mean value around the edge of an array." if len(np.ravel(a)) < 2: return float(a[0]) else: top_edge = a[0] bottom_edge = a[-1] left_edge = a[1:-1,0] right_edge = a[1:-1,-1] edge_sum = np.sum(top_edge) + np.sum(bottom_edge) + ...
Simplified version of PatternGenerator's __call__ method.
def _reduced_call(self, **params_to_override): """ Simplified version of PatternGenerator's __call__ method. """ p=param.ParamOverrides(self,params_to_override) fn_result = self.function(p) self._apply_mask(p,fn_result) result = p.scale*fn_result+p.offset ...
Add the channel information to the channel_data attribute.
def _process_channels(self,p,**params_to_override): """ Add the channel information to the channel_data attribute. """ orig_image = self._image for i in range(len(self._channel_data)): self._image = self._original_channel_data[i] self._channel_data[i] = s...
Subclassed to delete the cached image when matrix dimensions are changed.
def set_matrix_dimensions(self, *args): """ Subclassed to delete the cached image when matrix dimensions are changed. """ self._image = None super(FileImage, self).set_matrix_dimensions(*args)
Load image using PIL.
def _load_pil_image(self, filename): """ Load image using PIL. """ self._channel_data = [] self._original_channel_data = [] im = Image.open(filename) self._image = ImageOps.grayscale(im) im.load() file_data = np.asarray(im, float) file_da...
Load image using Numpy.
def _load_npy(self, filename): """ Load image using Numpy. """ self._channel_data = [] self._original_channel_data = [] file_channel_data = np.load(filename) file_channel_data = file_channel_data / file_channel_data.max() for i in range(file_channel_data....
Extends an ArgumentParser instance with the following args: --max-protein-sequences-per-variant Also adds all translation arguments such as: --protein-sequence-length
def add_protein_sequence_args(parser): """ Extends an ArgumentParser instance with the following args: --max-protein-sequences-per-variant Also adds all translation arguments such as: --protein-sequence-length """ protein_sequence_group = parser.add_argument_group( "Protein s...
Helper method for screening keyword arguments
def ok_kwarg(val): """Helper method for screening keyword arguments""" import keyword try: return str.isidentifier(val) and not keyword.iskeyword(val) except TypeError: # Non-string values are never a valid keyword arg return False
Run bulk record indexing.
def run(delayed, concurrency, version_type=None, queue=None, raise_on_error=True): """Run bulk record indexing.""" if delayed: celery_kwargs = { 'kwargs': { 'version_type': version_type, 'es_bulk_kwargs': {'raise_on_error': raise_on_error}, ...
Reindex all records. :param pid_type: Pid type.
def reindex(pid_type): """Reindex all records. :param pid_type: Pid type. """ click.secho('Sending records to indexing queue ...', fg='green') query = (x[0] for x in PersistentIdentifier.query.filter_by( object_type='rec', status=PIDStatus.REGISTERED ).filter( PersistentIdentif...
Process queue actions.
def process_actions(actions): """Process queue actions.""" queue = current_app.config['INDEXER_MQ_QUEUE'] with establish_connection() as c: q = queue(c) for action in actions: q = action(q)
Initialize indexing queue.
def init_queue(): """Initialize indexing queue.""" def action(queue): queue.declare() click.secho('Indexing queue has been initialized.', fg='green') return queue return action
Purge indexing queue.
def purge_queue(): """Purge indexing queue.""" def action(queue): queue.purge() click.secho('Indexing queue has been purged.', fg='green') return queue return action
Delete indexing queue.
def delete_queue(): """Delete indexing queue.""" def action(queue): queue.delete() click.secho('Indexing queue has been deleted.', fg='green') return queue return action
Make sure that reference nucleotides we expect to see on the reference transcript from a variant are the same ones we encounter.
def variant_matches_reference_sequence(variant, ref_seq_on_transcript, strand): """ Make sure that reference nucleotides we expect to see on the reference transcript from a variant are the same ones we encounter. """ if strand == "-": ref_seq_on_transcript = reverse_complement_dna(ref_seq_on...
Extracts the reference sequence around a variant locus on a particular transcript. Parameters ---------- variant : varcode.Variant transcript : pyensembl.Transcript context_size : int Returns SequenceKey object. Can also return None if Transcript lack...
def from_variant_and_transcript( cls, variant, transcript, context_size): """ Extracts the reference sequence around a variant locus on a particular transcript. Parameters ---------- variant : varcode.Variant transcript : pyensembl.Transcript ...
>>> print(ellipsize(u'lorem ipsum dolor sit amet', 40)) lorem ipsum dolor sit amet >>> print(ellipsize(u'lorem ipsum dolor sit amet', 20)) lorem ipsum dolor...
def ellipsize(s, max_length=60): """ >>> print(ellipsize(u'lorem ipsum dolor sit amet', 40)) lorem ipsum dolor sit amet >>> print(ellipsize(u'lorem ipsum dolor sit amet', 20)) lorem ipsum dolor... """ if len(s) > max_length: ellipsis = '...' return s[:(max_length - len(ellips...
Circularly alias the numeric value x into the range [lower,upper). Valid for cyclic quantities like orientations or hues.
def wrap(lower, upper, x): """ Circularly alias the numeric value x into the range [lower,upper). Valid for cyclic quantities like orientations or hues. """ #I have no idea how I came up with this algorithm; it should be simplified. # # Note that Python's % operator works on floats and arra...