INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Find reads in the given SAM/BAM file which overlap the given variant and return them as a list of AlleleRead objects. Parameters ---------- samfile : pysam.AlignmentFile variant : varcode.Variant chromosome : str use_duplicate_reads : bool Should we use reads that have been marke...
def reads_overlapping_variant( samfile, variant, chromosome=None, use_duplicate_reads=USE_DUPLICATE_READS, use_secondary_alignments=USE_SECONDARY_ALIGNMENTS, min_mapping_quality=MIN_READ_MAPPING_QUALITY): """ Find reads in the given SAM/BAM file which overlap the ...
Generates sequence of tuples, each containing a variant paired with a list of AlleleRead objects. Parameters ---------- variants : varcode.VariantCollection samfile : pysam.AlignmentFile use_duplicate_reads : bool Should we use reads that have been marked as PCR duplicates use_se...
def reads_overlapping_variants(variants, samfile, **kwargs): """ Generates sequence of tuples, each containing a variant paired with a list of AlleleRead objects. Parameters ---------- variants : varcode.VariantCollection samfile : pysam.AlignmentFile use_duplicate_reads : bool ...
Returns dictionary mapping each allele's nucleotide sequence to a list of supporting AlleleRead objects.
def group_reads_by_allele(allele_reads): """ Returns dictionary mapping each allele's nucleotide sequence to a list of supporting AlleleRead objects. """ allele_to_reads_dict = defaultdict(list) for allele_read in allele_reads: allele_to_reads_dict[allele_read.allele].append(allele_read)...
Parameters ---------- variants_and_allele_reads : sequence List or generator of pairs whose first element is a Variant and whose second element is a sequence of AlleleRead objects.
def reads_to_dataframe(variants_and_allele_reads): """ Parameters ---------- variants_and_allele_reads : sequence List or generator of pairs whose first element is a Variant and whose second element is a sequence of AlleleRead objects. """ df_builder = DataFrameBuilder( A...
Given a single LocusRead object, return either an AlleleRead or None Parameters ---------- locus_read : LocusRead Read which overlaps a variant locus but doesn't necessarily contain the alternate nucleotides n_ref : int Number of reference positions ...
def from_locus_read(cls, locus_read, n_ref): """ Given a single LocusRead object, return either an AlleleRead or None Parameters ---------- locus_read : LocusRead Read which overlaps a variant locus but doesn't necessarily contain the alternate nucleotide...
Find the most common nucleotide at each offset to the left and right of a variant. Parameters ---------- partitioned_read_sequences : list of tuples Each tuple has three elements: - sequence before mutant nucleotides - mutant nucleotides - sequence after muta...
def most_common_nucleotides(partitioned_read_sequences): """ Find the most common nucleotide at each offset to the left and right of a variant. Parameters ---------- partitioned_read_sequences : list of tuples Each tuple has three elements: - sequence before mutant nucleotid...
Count the number of times {A, C, T, G} occur at each position to the left and right of the variant. Parameters ---------- variant_reads : list of AlleleRead objects Expected to all contain the same variant allele. Returns a tuple with the following elements: - a matrix with four ro...
def nucleotide_counts(variant_reads): """ Count the number of times {A, C, T, G} occur at each position to the left and right of the variant. Parameters ---------- variant_reads : list of AlleleRead objects Expected to all contain the same variant allele. Returns a tuple with the f...
Calculate the displacement vector between two n-D points. pt1 - pt2 .. todo:: Complete point_disp docstring
def point_displ(pt1, pt2): """ Calculate the displacement vector between two n-D points. pt1 - pt2 .. todo:: Complete point_disp docstring """ #Imports import numpy as np # Make iterable if not np.iterable(pt1): pt1 = np.float64(np.array([pt1])) else: pt1 = np.fl...
Calculate the Euclidean distance between two n-D points. |pt1 - pt2| .. todo:: Complete point_dist docstring
def point_dist(pt1, pt2): """ Calculate the Euclidean distance between two n-D points. |pt1 - pt2| .. todo:: Complete point_dist docstring """ # Imports from scipy import linalg as spla dist = spla.norm(point_displ(pt1, pt2)) return dist
Rotate a 3-D point around a 3-D axis through the origin. Handedness is a counter-clockwise rotation when viewing the rotation axis as pointing at the observer. Thus, in a right-handed x-y-z frame, a 90deg rotation of (1,0,0) around the z-axis (0,0,1) yields a point at (0,1,0). .. todo:: Complete ...
def point_rotate(pt, ax, theta): """ Rotate a 3-D point around a 3-D axis through the origin. Handedness is a counter-clockwise rotation when viewing the rotation axis as pointing at the observer. Thus, in a right-handed x-y-z frame, a 90deg rotation of (1,0,0) around the z-axis (0,0,1) yields a point...
Reflect a 3-D point through a plane intersecting the origin. nv defines the normal vector to the plane (needs not be normalized) .. todo:: Complete point_reflect docstring Raises ------ ValueError : If pt or nv are not reducible to 3-D vectors ValueError : If norm of nv is too small
def point_reflect(pt, nv): """ Reflect a 3-D point through a plane intersecting the origin. nv defines the normal vector to the plane (needs not be normalized) .. todo:: Complete point_reflect docstring Raises ------ ValueError : If pt or nv are not reducible to 3-D vectors ValueError : I...
Reflection symmetry operation. nv is normal vector to reflection plane g is assumed already translated to center of mass @ origin .. todo:: Complete geom_reflect docstring
def geom_reflect(g, nv): """ Reflection symmetry operation. nv is normal vector to reflection plane g is assumed already translated to center of mass @ origin .. todo:: Complete geom_reflect docstring """ # Imports import numpy as np # Force g to n-vector g = make_nd_vec(g, nd=N...
Rotation symmetry operation. ax is rotation axis g is assumed already translated to center of mass @ origin Sense of rotation is the same as point_rotate .. todo:: Complete geom_rotate docstring
def geom_rotate(g, ax, theta): """ Rotation symmetry operation. ax is rotation axis g is assumed already translated to center of mass @ origin Sense of rotation is the same as point_rotate .. todo:: Complete geom_rotate docstring """ # Imports import numpy as np # Force g to n-...
Perform general point symmetry operation on a geometry. .. todo:: Complete symm_op docstring
def symm_op(g, ax, theta, do_refl): """ Perform general point symmetry operation on a geometry. .. todo:: Complete symm_op docstring """ # Imports import numpy as np # Depend on lower functions' geometry vector coercion. Just # do the rotation and, if indicated, the reflection. gx =...
[Revised match factor calculation] .. todo:: Complete geom_symm_match docstring
def geom_symm_match(g, atwts, ax, theta, do_refl): """ [Revised match factor calculation] .. todo:: Complete geom_symm_match docstring """ # Imports import numpy as np from scipy import linalg as spla # Convert g and atwts to n-D vectors g = make_nd_vec(g, nd=None, t=np.float64, norm...
Identify highest-order symmetry for a geometry on a given axis. Regular and improper axes possible. .. todo:: Complete geom_find_rotsymm docstring
def geom_find_rotsymm(g, atwts, ax, improp, \ nmax=_DEF.SYMM_MATCH_NMAX, \ tol=_DEF.SYMM_MATCH_TOL): """ Identify highest-order symmetry for a geometry on a given axis. Regular and improper axes possible. .. todo:: Complete geom_find_rotsymm docstring """ # Imports import num...
[Get max proper order and reflection for an axis] .. todo:: Complete geom_parse_axis docstring
def geom_check_axis(g, atwts, ax, nmax=_DEF.SYMM_MATCH_NMAX, tol=_DEF.SYMM_MATCH_TOL): """ [Get max proper order and reflection for an axis] .. todo:: Complete geom_parse_axis docstring """ # Imports import numpy as np # Store the max found rotation order of the geometry. ...
[Find all(?) proper rotation axes (n > 1) and reflection planes.] .. todo:: Complete geom_find_axes docstring INCLUDING NEW HEADER LINE DEPENDS on principal axes and moments being sorted such that: I_A <= I_B <= I_C Logic flow developed using: 1) http://symmetry.otterbein.edu/common/image...
def geom_find_group(g, atwts, pr_ax, mom, tt, \ nmax=_DEF.SYMM_MATCH_NMAX, \ tol=_DEF.SYMM_MATCH_TOL, \ dig=_DEF.SYMM_ATWT_ROUND_DIGITS, avmax=_DEF.SYMM_AVG_MAX): """ [Find all(?) proper rotation axes (n > 1) and reflection planes.] .. todo:: Complete geom_find_axes docstring IN...
Extract a subset of a geometry matching a desired atom. .. todo:: Complete g_subset docstring
def g_subset(g, atwts, atwt, digits=_DEF.SYMM_ATWT_ROUND_DIGITS): """ Extract a subset of a geometry matching a desired atom. .. todo:: Complete g_subset docstring """ # Imports import numpy as np # Ensure g and atwts are n-D vectors g = make_nd_vec(g, nd=None, t=np.float64, ...
Coerce input to np.array() and validate dimensionality. Ensure dimensionality 'n' if passed. Cast to type 't' if passed Normalize output if norm=True .. todo:: Complete make_nd_vec docstring
def make_nd_vec(v, nd=None, t=None, norm=False): """ Coerce input to np.array() and validate dimensionality. Ensure dimensionality 'n' if passed. Cast to type 't' if passed Normalize output if norm=True .. todo:: Complete make_nd_vec docstring """ # Imports import numpy as np fro...
Generate block-diagonal reflection matrix about nv. reps must be >=1 and indicates the number of times the reflection matrix should be repeated along the block diagonal. Typically this will be the number of atoms in a geometry. .. todo:: Complete mtx_refl docstring
def mtx_refl(nv, reps=1): """ Generate block-diagonal reflection matrix about nv. reps must be >=1 and indicates the number of times the reflection matrix should be repeated along the block diagonal. Typically this will be the number of atoms in a geometry. .. todo:: Complete mtx_refl docstring ...
Generate block-diagonal rotation matrix about ax. [copy handedness from somewhere] .. todo:: Complete mtx_rot docstring
def mtx_rot(ax, theta, reps=1): """ Generate block-diagonal rotation matrix about ax. [copy handedness from somewhere] .. todo:: Complete mtx_rot docstring """ # Imports import numpy as np from scipy import linalg as spla from ..const import PRM # Ensure |ax| is large enough for...
First-Fit This is perhaps the simplest packing heuristic; it simply packs items in the next available bin. Complexity O(n^2)
def ff(items, targets): """First-Fit This is perhaps the simplest packing heuristic; it simply packs items in the next available bin. Complexity O(n^2) """ bins = [(target, []) for target in targets] skip = [] for item in items: for target, content in bins: if item...
First-Fit Decreasing This is perhaps the simplest packing heuristic; it simply packs items in the next available bin. This algorithm differs only from Next-Fit Decreasing in having a 'sort'; that is, the items are pre-sorted (largest to smallest). Complexity O(n^2)
def ffd(items, targets, **kwargs): """First-Fit Decreasing This is perhaps the simplest packing heuristic; it simply packs items in the next available bin. This algorithm differs only from Next-Fit Decreasing in having a 'sort'; that is, the items are pre-sorted (largest to smallest). Com...
Max-Rest Complexity O(n^2)
def mr(items, targets, **kwargs): """Max-Rest Complexity O(n^2) """ bins = [(target, []) for target in targets] skip = [] for item in items: capacities = [target - sum(content) for target, content in bins] weighted = weight(capacities, **kwargs) (target, content), capa...
Best-Fit Complexity O(n^2)
def bf(items, targets, **kwargs): """Best-Fit Complexity O(n^2) """ bins = [(target, []) for target in targets] skip = [] for item in items: containers = [] capacities = [] for target, content in bins: capacity = target - sum(content) if item <= ...
Best-Fit Decreasing Complexity O(n^2)
def bfd(items, targets, **kwargs): """Best-Fit Decreasing Complexity O(n^2) """ sizes = zip(items, weight(items, **kwargs)) sizes = sorted(sizes, key=operator.itemgetter(1), reverse=True) items = map(operator.itemgetter(0), sizes) return bf(items, targets, **kwargs)
A VariantSequence and ReferenceContext may contain a different number of nucleotides before the variant locus. Furthermore, the VariantSequence is always expressed in terms of the positive strand against which it aligned, but reference transcripts may have sequences from the negative strand of the genom...
def trim_sequences(variant_sequence, reference_context): """ A VariantSequence and ReferenceContext may contain a different number of nucleotides before the variant locus. Furthermore, the VariantSequence is always expressed in terms of the positive strand against which it aligned, but reference tra...
Computes the number of mismatching nucleotides between two cDNA sequences before a variant locus. Parameters ---------- reference_prefix : str cDNA sequence of a reference transcript before a variant locus cdna_prefix : str cDNA sequence detected from RNAseq before a variant locus
def count_mismatches_before_variant(reference_prefix, cdna_prefix): """ Computes the number of mismatching nucleotides between two cDNA sequences before a variant locus. Parameters ---------- reference_prefix : str cDNA sequence of a reference transcript before a variant locus cdna...
Computes the number of mismatching nucleotides between two cDNA sequences after a variant locus. Parameters ---------- reference_suffix : str cDNA sequence of a reference transcript after a variant locus cdna_suffix : str cDNA sequence detected from RNAseq after a variant locus
def count_mismatches_after_variant(reference_suffix, cdna_suffix): """ Computes the number of mismatching nucleotides between two cDNA sequences after a variant locus. Parameters ---------- reference_suffix : str cDNA sequence of a reference transcript after a variant locus cdna_suffix...
Once we've aligned the variant sequence to the ReferenceContext, we need to transfer reading frame from the reference transcripts to the variant sequences. Parameters ---------- offset_to_first_complete_reference_codon : int n_trimmed_from_reference_sequence : int Returns an offset into t...
def compute_offset_to_first_complete_codon( offset_to_first_complete_reference_codon, n_trimmed_from_reference_sequence): """ Once we've aligned the variant sequence to the ReferenceContext, we need to transfer reading frame from the reference transcripts to the variant sequences. P...
Iteratively trim low-coverage subsequences of a variant sequence until it either matches the given reference context or there are too few nucleotides left in the variant sequence. Parameters ---------- variant_sequence : VariantSequence Assembled sequence from RNA reads, will need to be to ...
def match_variant_sequence_to_reference_context( variant_sequence, reference_context, min_transcript_prefix_length, max_transcript_mismatches, include_mismatches_after_variant=False, max_trimming_attempts=2): """ Iteratively trim low-coverage subsequences of a var...
Combines a VariantSequence with the reading frame implied by a ReferenceContext, reverse complementing if necessary and finding the offset to the first complete codon in the cDNA sequence. Parameters ---------- variant_sequence : VariantSequence reference_context : Refer...
def from_variant_sequence_and_reference_context( cls, variant_sequence, reference_context): """ Combines a VariantSequence with the reading frame implied by a ReferenceContext, reverse complementing if necessary and finding the offset to the first complete codon in the cDNA s...
Given a cDNA sequence which is aligned to a reading frame, returns the translated protein sequence and a boolean flag indicating whether the translated sequence ended on a stop codon (or just ran out of codons). Parameters ---------- cdna_sequence : str cDNA sequence which is expected to st...
def translate_cdna( cdna_sequence, first_codon_is_start=False, mitochondrial=False): """ Given a cDNA sequence which is aligned to a reading frame, returns the translated protein sequence and a boolean flag indicating whether the translated sequence ended on a stop codon (or just...
If codon table is missing stop codons, then add them.
def _check_codons(self): """ If codon table is missing stop codons, then add them. """ for stop_codon in self.stop_codons: if stop_codon in self.codon_table: if self.codon_table[stop_codon] != "*": raise ValueError( ...
Given a cDNA sequence which is aligned to a reading frame, returns the translated protein sequence and a boolean flag indicating whether the translated sequence ended on a stop codon (or just ran out of codons). Parameters ---------- cdna_sequence : str cDNA sequence...
def translate(self, cdna_sequence, first_codon_is_start=False): """ Given a cDNA sequence which is aligned to a reading frame, returns the translated protein sequence and a boolean flag indicating whether the translated sequence ended on a stop codon (or just ran out of codons). ...
Make copy of this GeneticCode object with optional replacement values for all fields.
def copy( self, name, start_codons=None, stop_codons=None, codon_table=None, codon_table_changes=None): """ Make copy of this GeneticCode object with optional replacement values for all fields. """ new_start_...
Initialize :class:`OrcaEngrad` object from .engrad file Searches indicated file for energy, geometry, gradient, and number of atoms and stores in the corresponding instance variables. Parameters ---------- path |str| -- Complete path to the .engrad file to be read....
def _load(self, **kwargs): """ Initialize :class:`OrcaEngrad` object from .engrad file Searches indicated file for energy, geometry, gradient, and number of atoms and stores in the corresponding instance variables. Parameters ---------- path |str| -- Comple...
Start listening to changes
def start(self): """ Start listening to changes """ self.running = True self.thread = threading.Thread(target=self._main_loop) self.thread.start()
Subscribe to given fields. Special fields cannot be subscribed to and will be checked on every iteration. These include: * loco name * coordinates * fuel level * gradient * current heading * is in tunnel * time You can of course still receive no...
def subscribe(self, field_names): """ Subscribe to given fields. Special fields cannot be subscribed to and will be checked on every iteration. These include: * loco name * coordinates * fuel level * gradient * current heading * is in tunnel ...
Channels() adds a shared interface for single channel and multichannel structures. It will always return an ordered dict: its first element is the single channel of the pattern (if single-channel) or the channel average (if multichannel); the successive elements are the individual chann...
def channels(self, use_cached=False, **params_to_override): """ Channels() adds a shared interface for single channel and multichannel structures. It will always return an ordered dict: its first element is the single channel of the pattern (if single-channel) or the channel ave...
Produce pattern coordinate matrices from the bounds and density (or rows and cols), and transforms them according to x, y, and orientation.
def _setup_xy(self,bounds,xdensity,ydensity,x,y,orientation): """ Produce pattern coordinate matrices from the bounds and density (or rows and cols), and transforms them according to x, y, and orientation. """ self.debug("bounds=%s, xdensity=%s, ydensity=%s, x=%s, y=%s, o...
Create pattern matrices from x and y vectors, and rotate them to the specified orientation.
def _create_and_rotate_coordinate_arrays(self, x, y, orientation): """ Create pattern matrices from x and y vectors, and rotate them to the specified orientation. """ # Using this two-liner requires that x increase from left to # right and y decrease from left to right; I...
Create (if necessary) and apply the mask to the given matrix mat.
def _apply_mask(self,p,mat): """Create (if necessary) and apply the mask to the given matrix mat.""" mask = p.mask ms=p.mask_shape if ms is not None: mask = ms(x=p.x+p.size*(ms.x*np.cos(p.orientation)-ms.y*np.sin(p.orientation)), y=p.y+p.size*(ms.x*np.si...
Change the dimensions of the matrix into which the pattern will be drawn. Users of this class should call this method rather than changing the bounds, xdensity, and ydensity parameters directly. Subclasses can override this method to update any internal data structures that may depend ...
def set_matrix_dimensions(self, bounds, xdensity, ydensity): """ Change the dimensions of the matrix into which the pattern will be drawn. Users of this class should call this method rather than changing the bounds, xdensity, and ydensity parameters directly. Subclasses can ove...
Save the state of the output functions, to be restored with state_pop.
def state_push(self): "Save the state of the output functions, to be restored with state_pop." for of in self.output_fns: if hasattr(of,'state_push'): of.state_push() super(PatternGenerator, self).state_push()
Restore the state of the output functions saved by state_push.
def state_pop(self): "Restore the state of the output functions saved by state_push." for of in self.output_fns: if hasattr(of,'state_pop'): of.state_pop() super(PatternGenerator, self).state_pop()
duration: The temporal duration to animate in the units defined on the global time function. offset: The temporal offset from which the animation is generated given the supplied pattern timestep: The time interval between successive frames. The duration must be an exact multipl...
def anim(self, duration, offset=0, timestep=1, label=None, unit=None, time_fn=param.Dynamic.time_fn): """ duration: The temporal duration to animate in the units defined on the global time function. offset: The temporal offset from which the animation is ...
Returns a PIL image for this pattern, overriding parameters if provided.
def pil(self, **params_to_override): """Returns a PIL image for this pattern, overriding parameters if provided.""" from PIL.Image import fromarray nchans = self.num_channels() if nchans in [0, 1]: mode, arr = None, self(**params_to_override) arr = (255.0 / arr.m...
Push the state of all generators
def state_push(self): """ Push the state of all generators """ super(Composite,self).state_push() for gen in self.generators: gen.state_push()
Pop the state of all generators
def state_pop(self): """ Pop the state of all generators """ super(Composite,self).state_pop() for gen in self.generators: gen.state_pop()
Constructs combined pattern out of the individual ones.
def function(self,p): """Constructs combined pattern out of the individual ones.""" generators = self._advance_pattern_generators(p) assert hasattr(p.operator,'reduce'),repr(p.operator)+" does not support 'reduce'." # CEBALERT: mask gets applied by all PGs including the Composite itsel...
Postgresql Create Table statement formatter.
def compile_create_table(qualified_name: str, column_statement: str, primary_key_statement: str) -> str: """Postgresql Create Table statement formatter.""" statement = """ CREATE TABLE {table} ({columns} {primary_keys}); """.format(table=qualified_name, ...
Postgresql Create Temporary Table statement formatter.
def compile_create_temporary_table(table_name: str, column_statement: str, primary_key_statement: str) -> str: """Postgresql Create Temporary Table statement formatter.""" statement = """ CREATE TEMPORARY TABLE {table} ({colu...
Create column definition statement.
def compile_column(name: str, data_type: str, nullable: bool) -> str: """Create column definition statement.""" null_str = 'NULL' if nullable else 'NOT NULL' return '{name} {data_type} {null},'.format(name=name, data_type=data_type, ...
Declare materalized view.
def create(self, no_data=False): """Declare materalized view.""" if self.query: ddl_statement = self.compile_create_as() else: ddl_statement = self.compile_create() if no_data: ddl_statement += '\nWITH NO DATA' return ddl_statement, self.que...
For a given variant, return its set of predicted effects. Optionally filter to transcripts where this variant results in a non-synonymous change to the protein sequence. Parameters ---------- variant : varcode.Variant transcript_id_whitelist : set Filter effect predictions to only incl...
def predicted_effects_for_variant( variant, transcript_id_whitelist=None, only_coding_changes=True): """ For a given variant, return its set of predicted effects. Optionally filter to transcripts where this variant results in a non-synonymous change to the protein sequence. ...
For a given variant, find all the transcripts which overlap the variant and for which it has a predictable effect on the amino acid sequence of the protein.
def reference_transcripts_for_variant( variant, transcript_id_whitelist=None, only_coding_changes=True): """ For a given variant, find all the transcripts which overlap the variant and for which it has a predictable effect on the amino acid sequence of the protein. """ pr...
Returns a pileup column at the specified position. Unclear if a function like this is hiding somewhere in pysam API.
def pileup_reads_at_position(samfile, chromosome, base0_position): """ Returns a pileup column at the specified position. Unclear if a function like this is hiding somewhere in pysam API. """ # TODO: I want to pass truncate=True, stepper="all" # but for some reason I get this error: # ...
Generator that yields a sequence of ReadAtLocus records for reads which contain the positions before and after a variant. The actual work to figure out if what's between those positions matches a variant happens later in the `variant_reads` module. Parameters ---------- samfile : pysam.Alignmen...
def locus_read_generator( samfile, chromosome, base1_position_before_variant, base1_position_after_variant, use_duplicate_reads=USE_DUPLICATE_READS, use_secondary_alignments=USE_SECONDARY_ALIGNMENTS, min_mapping_quality=MIN_READ_MAPPING_QUALITY): """ Gener...
Traverse a BAM file to find all the reads overlapping a specified locus. Parameters are the same as those for read_locus_generator.
def locus_reads_dataframe(*args, **kwargs): """ Traverse a BAM file to find all the reads overlapping a specified locus. Parameters are the same as those for read_locus_generator. """ df_builder = DataFrameBuilder( LocusRead, variant_columns=False, converters={ "...
Parameters ---------- pileup_element : pysam.PileupRead base0_position_before_variant : int base0_position_after_variant : int use_secondary_alignments : bool use_duplicate_reads : bool min_mapping_quality : int use_soft_clipped_bases : bool. Default...
def from_pysam_pileup_element( cls, pileup_element, base0_position_before_variant, base0_position_after_variant, use_secondary_alignments, use_duplicate_reads, min_mapping_quality, use_soft_clipped_bases=False): """ ...
Generate copy from csv statement.
def copy_from_csv_sql(qualified_name: str, delimiter=',', encoding='utf8', null_str='', header=True, escape_str='\\', quote_char='"', force_not_null=None, force_null=None): """Generate copy from csv statement.""" options = [] options.append("DELIMITER '%s'" % del...
Sort protein sequences in decreasing order of priority
def sort_protein_sequences(protein_sequences): """ Sort protein sequences in decreasing order of priority """ return list( sorted( protein_sequences, key=ProteinSequence.ascending_sort_key, reverse=True))
Translates each coding variant in a collection to one or more Translation objects, which are then aggregated into equivalent ProteinSequence objects. Parameters ---------- variant_and_overlapping_reads_generator : generator Yields sequence of varcode.Variant objects paired with sequences ...
def reads_generator_to_protein_sequences_generator( variant_and_overlapping_reads_generator, transcript_id_whitelist=None, protein_sequence_length=PROTEIN_SEQUENCE_LENGTH, min_alt_rna_reads=MIN_ALT_RNA_READS, min_variant_sequence_coverage=MIN_VARIANT_SEQUENCE_COVERAGE, mi...
Given a generator which yields (Variant, [ProteinSequence]) elements, returns a pandas.DataFrame
def protein_sequences_generator_to_dataframe(variant_and_protein_sequences_generator): """ Given a generator which yields (Variant, [ProteinSequence]) elements, returns a pandas.DataFrame """ return dataframe_from_generator( element_class=ProteinSequence, variant_and_elements_generat...
Summarize a collection of Translation objects into three values: 1) List of unique reads supporting underlying variant sequences 2) Set of unique transcript names for establishing reading frames of the translations. 3) Set of unique gene names for all transcripts used ...
def _summarize_translations(cls, translations): """ Summarize a collection of Translation objects into three values: 1) List of unique reads supporting underlying variant sequences 2) Set of unique transcript names for establishing reading frames of the translation...
Create a ProteinSequence object from a TranslationKey, along with all the extra fields a ProteinSequence requires.
def from_translation_key( cls, translation_key, translations, overlapping_reads, ref_reads, alt_reads, alt_reads_supporting_protein_sequence, transcripts_overlapping_variant, transcripts_supporting_protein_sequen...
Sort protein sequences lexicographically by three criteria: - number of unique supporting reads - minimum mismatch versus a supporting reference transcript before variant - minimum mismatch versus a supporting reference transcript after variant - number of supporting refe...
def ascending_sort_key(self): """ Sort protein sequences lexicographically by three criteria: - number of unique supporting reads - minimum mismatch versus a supporting reference transcript before variant - minimum mismatch versus a supporting reference transcript aft...
Table referencing a delete from using primary key join.
def make_delete_table(table: Table, delete_prefix='delete_from__') -> Table: """Table referencing a delete from using primary key join.""" name = delete_prefix + table.name primary_key = table.primary_key key_names = set(primary_key.column_names) columns = [column for column in table.columns if col...
Record table column(s) and primary key columns by specified order.
def order_table_columns(table: Table, column_names: list) -> Table: """Record table column(s) and primary key columns by specified order.""" unordered_columns = table.column_names index_order = (unordered_columns.index(name) for name in column_names) ordered_columns = [table.columns[i] for i in index_o...
Trims common prefixes from the ref and alt sequences Parameters ---------- location : int Position (starting from 1) on some chromosome ref : str Reference nucleotides alt : str Alternate (mutant) nucleotide Returns adjusted triplet (location, ref, alt)
def trim_variant_fields(location, ref, alt): """ Trims common prefixes from the ref and alt sequences Parameters ---------- location : int Position (starting from 1) on some chromosome ref : str Reference nucleotides alt : str Alternate (mutant) nucleotide Ret...
Inteval of interbase offsets of the affected reference positions for a particular variant's primary fields (pos, ref, alt). Parameters ---------- base1_location : int First reference nucleotide of variant or, for insertions, the base before the insertion. ref : str Referenc...
def base0_interval_for_variant_fields(base1_location, ref, alt): """ Inteval of interbase offsets of the affected reference positions for a particular variant's primary fields (pos, ref, alt). Parameters ---------- base1_location : int First reference nucleotide of variant or, for inser...
Inteval of interbase offsets of the affected reference positions for a particular variant. Parameters ---------- variant : varcode.Variant Returns triplet of (base1_location, ref, alt)
def base0_interval_for_variant(variant): """ Inteval of interbase offsets of the affected reference positions for a particular variant. Parameters ---------- variant : varcode.Variant Returns triplet of (base1_location, ref, alt) """ base1_location, ref, alt = trim_variant(variant)...
Convert from a variant's position in global genomic coordinates on the forward strand to an interval of interbase offsets on a particular transcript's mRNA. Parameters ---------- variant : varcode.Variant transcript : pyensembl.Transcript Assumes that the transcript overlaps the variant. ...
def interbase_range_affected_by_variant_on_transcript(variant, transcript): """ Convert from a variant's position in global genomic coordinates on the forward strand to an interval of interbase offsets on a particular transcript's mRNA. Parameters ---------- variant : varcode.Variant t...
Insert a collection of namedtuple records.
def insert(conn, qualified_name: str, column_names, records): """Insert a collection of namedtuple records.""" query = create_insert_statement(qualified_name, column_names) with conn: with conn.cursor(cursor_factory=NamedTupleCursor) as cursor: for record in records: cu...
Insert many records by chunking data into insert statements. Notes ----- records should be Iterable collection of namedtuples or tuples.
def insert_many(conn, tablename, column_names, records, chunksize=2500): """Insert many records by chunking data into insert statements. Notes ----- records should be Iterable collection of namedtuples or tuples. """ groups = chunks(records, chunksize) column_str = ','.join(column_names) ...
Upsert records.
def upsert_records(conn, records, upsert_statement): """Upsert records.""" with conn: with conn.cursor() as cursor: for record in records: cursor.execute(upsert_statement, record)
SQL statement for a joined delete from. Generate SQL statement for deleting the intersection of rows between both tables from table referenced by tablename.
def delete_joined_table_sql(qualified_name, removing_qualified_name, primary_key): """SQL statement for a joined delete from. Generate SQL statement for deleting the intersection of rows between both tables from table referenced by tablename. """ condition_template = 't.{}=d.{}' where_clause = ...
Copy file-like object to database table. Notes ----- Implementation defaults to postgres standard except for encoding. Postgres falls back on client encoding, while function defaults to utf-8. References ---------- https://www.postgresql.org/docs/current/static/sql-copy.html
def copy_from_csv(conn, file, qualified_name: str, delimiter=',', encoding='utf8', null_str='', header=True, escape_str='\\', quote_char='"', force_not_null=None, force_null=None): """Copy file-like object to database table. Notes ----- Implementation defaults to pos...
Retrieve all user tables.
def get_user_tables(conn): """Retrieve all user tables.""" query_string = "select schemaname, relname from pg_stat_user_tables;" with conn.cursor() as cursor: cursor.execute(query_string) tables = cursor.fetchall() return tables
Returns primary key columns for a specific table.
def get_primary_keys(conn, table: str, schema='public'): """Returns primary key columns for a specific table.""" query = """\ SELECT c.constraint_name AS pkey_constraint_name, c.column_name AS column_name FROM information_schema.key_column_usage AS c JOIN information_schema.table_constraints AS t ...
Returns column data following db.Column parameter specification.
def get_column_metadata(conn, table: str, schema='public'): """Returns column data following db.Column parameter specification.""" query = """\ SELECT attname as name, format_type(atttypid, atttypmod) AS data_type, NOT attnotnull AS nullable FROM pg_catalog.pg_attribute WHERE attrelid=%s::regclass AND a...
Reflect basic table attributes.
def reflect_table(conn, table_name, schema='public'): """Reflect basic table attributes.""" column_meta = list(get_column_metadata(conn, table_name, schema=schema)) primary_key_columns = list(get_primary_keys(conn, table_name, schema=schema)) columns = [Column(**column_data) for column_data in column_...
Reset database.
def reset(db_name): """Reset database.""" conn = psycopg2.connect(database='postgres') db = Database(db_name) conn.autocommit = True with conn.cursor() as cursor: cursor.execute(db.drop_statement()) cursor.execute(db.create_statement()) conn.close()
Install Postgres extension if available. Notes ----- - superuser is generally required for installing extensions. - Currently does not support specific schema.
def install_extensions(extensions, **connection_parameters): """Install Postgres extension if available. Notes ----- - superuser is generally required for installing extensions. - Currently does not support specific schema. """ from postpy.connections import connect conn = connect(**c...
Sends a status update to the framework scheduler. Retrying as necessary until an acknowledgement has been received or the executor is terminated (in which case, a TASK_LOST status update will be sent). See Scheduler.statusUpdate for more information about status update acknowled...
def update(self, status): """Sends a status update to the framework scheduler. Retrying as necessary until an acknowledgement has been received or the executor is terminated (in which case, a TASK_LOST status update will be sent). See Scheduler.statusUpdate for more information ...
Sends a message to the framework scheduler. These messages are best effort; do not expect a framework message to be retransmitted in any reliable fashion.
def message(self, data): """Sends a message to the framework scheduler. These messages are best effort; do not expect a framework message to be retransmitted in any reliable fashion. """ logging.info('Driver sends framework message {}'.format(data)) return self.driver.se...
Returns an iterable of tuples containing (index, controller_name) pairs. Controller indexes start at 0. You may easily transform this to a {name: index} mapping by using: >>> controllers = {name: index for index, name in raildriver.get_controller_list()} :return enumerate
def get_controller_list(self): """ Returns an iterable of tuples containing (index, controller_name) pairs. Controller indexes start at 0. You may easily transform this to a {name: index} mapping by using: >>> controllers = {name: index for index, name in raildriver.get_contro...
Returns current/min/max value of controller at given index or name. It is much more efficient to query using an integer index rather than string name. Name is fine for seldom updates but it's not advised to be used every second or so. See `get_controller_list` for an example how to cache a dict...
def get_controller_value(self, index_or_name, value_type): """ Returns current/min/max value of controller at given index or name. It is much more efficient to query using an integer index rather than string name. Name is fine for seldom updates but it's not advised to be used every sec...
Get current time :return: datetime.time
def get_current_time(self): """ Get current time :return: datetime.time """ hms = [int(self.get_current_controller_value(i)) for i in range(406, 409)] return datetime.time(*hms)
Returns the Provider, Product and Engine name. :return list
def get_loco_name(self): """ Returns the Provider, Product and Engine name. :return list """ ret_str = self.dll.GetLocoName().decode() if not ret_str: return return ret_str.split('.:.')
Sets controller value :param index_or_name integer index or string name :param value float
def set_controller_value(self, index_or_name, value): """ Sets controller value :param index_or_name integer index or string name :param value float """ if not isinstance(index_or_name, int): index = self.get_controller_index(index_or_name) else: ...
Flask application initialization. :param app: The Flask application.
def init_app(self, app): """Flask application initialization. :param app: The Flask application. """ self.init_config(app) app.extensions['invenio-indexer'] = self hooks = app.config.get('INDEXER_BEFORE_INDEX_HOOKS', []) for hook in hooks: if isinsta...
.. todo:: REPO.close docstring
def close(self): """ .. todo:: REPO.close docstring """ # Imports import h5py as h5 from ..error import RepoError # Close the repo if it's bound, and wipe link; else complain if self._repo != None: self._repo.close() self._repo = None ...
.. todo:: REPO.load docstring
def load(self, fname): """ .. todo:: REPO.load docstring """ # Imports import h5py as h5 from ..error import RepoError # If repo not None, complain if not self._repo == None: raise RepoError(RepoError.STATUS, "Repository already o...
.. todo:: is_open docstring
def is_open(self): """ .. todo:: is_open docstring """ # Imports import h5py as h5 # Return whether repo is bound; depends on the 'None' assignment in # 'close' retval = isinstance(self._repo, h5.File) return retval
.. todo:: store_data docstring
def store_data(self, data, datatype, mode, disp, clobber=False): """ .. todo:: store_data docstring """ # Imports import h5py as h5 from ..error import RepoError as RErr from ..const import EnumDispDirection as _E_DD from ..const import EnumAnharmRepoData ...
.. todo:: docstring for get_data
def get_data(self, datatype, mode, disp): """ .. todo:: docstring for get_data """ # Imports import os from ..const import EnumDispDirection as _E_DD from ..const import EnumAnharmRepoData from ..error import RepoError as RErr # Must be valid mode ...
.. todo:: has_data docstring
def has_data(self, datatype, mode, disp): """ .. todo:: has_data docstring """ # Imports from ..error import RepoError # Just try to get the data. Simply pass up all exceptions except for # those if the group or data doesn't exist. DO re-raise a non-bound # re...