Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def lss(inlist): ss = 0 for item in inlist: ss = ss + item*item return ss
[ "\nSquares each value in the passed list, adds up these squares and\nreturns the result.\n\nUsage: lss(inlist)\n" ]
Please provide a description of the function:def lsummult (list1,list2): if len(list1) != len(list2): raise ValueError("Lists not equal length in summult.") s = 0 for item1,item2 in pstat.abut(list1,list2): s = s + item1*item2 return s
[ "\nMultiplies elements in list1 and list2, element by element, and\nreturns the sum of all resulting multiplications. Must provide equal\nlength lists.\n\nUsage: lsummult(list1,list2)\n" ]
Please provide a description of the function:def lsumdiffsquared(x,y): sds = 0 for i in range(len(x)): sds = sds + (x[i]-y[i])**2 return sds
[ "\nTakes pairwise differences of the values in lists x and y, squares\nthese differences, and returns the sum of these squares.\n\nUsage: lsumdiffsquared(x,y)\nReturns: sum[(x[i]-y[i])**2]\n" ]
Please provide a description of the function:def outputpairedstats(fname,writemode,name1,n1,m1,se1,min1,max1,name2,n2,m2,se2,min2,max2,statname,stat,prob): suffix = '' # for *s after the p-value try: x = prob.shape prob = prob[0] except: pass if prob <...
[ "\nPrints or write to a file stats for two groups, using the name, n,\nmean, sterr, min and max for each group, as well as the statistic name,\nits value, and the associated p-value.\n\nUsage: outputpairedstats(fname,writemode,\n name1,n1,mean1,stderr1,min1,max1,\n ...
Please provide a description of the function:def GeneReader( fh, format='gff' ): known_formats = ( 'gff', 'gtf', 'bed') if format not in known_formats: print('%s format not in %s' % (format, ",".join( known_formats )), file=sys.stderr) raise Exception('?') if format == 'bed': ...
[ " yield chrom, strand, gene_exons, name " ]
Please provide a description of the function:def CDSReader( fh, format='gff' ): known_formats = ( 'gff', 'gtf', 'bed') if format not in known_formats: print('%s format not in %s' % (format, ",".join( known_formats )), file=sys.stderr) raise Exception('?') if format == 'bed': ...
[ " yield chrom, strand, cds_exons, name " ]
Please provide a description of the function:def FeatureReader( fh, format='gff', alt_introns_subtract="exons", gtf_parse=None): known_formats = ( 'gff', 'gtf', 'bed') if format not in known_formats: print('%s format not in %s' % (format, ",".join( known_formats )), file=sys.stderr) raise...
[ " \n yield chrom, strand, cds_exons, introns, exons, name\n\n gtf_parse Example:\n # parse gene_id from transcript_id \"AC073130.2-001\"; gene_id \"TES\";\n gene_name = lambda s: s.split(';')[1].split()[1].strip('\"')\n\n for chrom, strand, cds_exons, introns, exons, name in FeatureReader( sys.stdin,...
Please provide a description of the function:def throw_random_gap_list( lengths, mask, save_interval_func, allow_overlap=False ): # Use mask to find the gaps; gaps is a list of (length,start,end) lengths = [length for length in lengths if length > 0] min_length = min( lengths ) gaps = [] start...
[ "\n Generates a set of non-overlapping random intervals from a length \n distribution.\n \n `lengths`: list containing the length of each interval to be generated.\n We expect this to be sorted by decreasing length to minimize\n the chance of failure (MaxtriesException) and f...
Please provide a description of the function:def throw_random_intervals( lengths, regions, save_interval_func=None, allow_overlap=False ): # Copy regions regions = [( x[1]-x[0], x[0], x ) for x in regions] # Sort (long regions first) regions.sort() regions.reverse() # Throw if (save...
[ "\n Generates a set of non-overlapping random intervals from a length \n distribution.\n \n `lengths`: list containing the length of each interval to be generated.\n We expect this to be sorted by decreasing length to minimize\n the chance of failure (MaxtriesException) and f...
Please provide a description of the function:def throw_random_private( lengths, regions, save_interval_func, allow_overlap=False, three_args=True ): # Implementation: # We keep a list of the regions, sorted from largest to smallest. We then # place each length by following steps: # (1) co...
[ "\n (Internal function; we expect calls only through the interface functions\n above)\n \n `lengths`: A list containing the length of each interval to be generated.\n `regions`: A list of regions in which intervals can be placed, sorted by\n decreasing length. Elements are triples of ...
Please provide a description of the function:def get(self, start, length): # Check parameters assert length >= 0, "Length must be non-negative (got %d)" % length assert start >= 0,"Start must be greater than 0 (got %d)" % start assert start + length <= self.length, \ ...
[ "\n Fetch subsequence starting at position `start` with length `length`. \n This method is picky about parameters, the requested interval must \n have non-negative length and fit entirely inside the NIB sequence,\n the returned string will contain exactly 'length' characters, or an\n ...
Please provide a description of the function:def read_scoring_scheme( f, gap_open, gap_extend, gap1="-", gap2=None, **kwargs ): close_it = False if (type(f) == str): f = file(f,"rt") close_it = True ss = build_scoring_scheme("".join([line for line in f]),gap_open, gap_extend, gap1=gap1,...
[ "\n Initialize scoring scheme from a file containint a blastz style text blob.\n f can be either a file or the name of a file.\n " ]
Please provide a description of the function:def build_scoring_scheme( s, gap_open, gap_extend, gap1="-", gap2=None, **kwargs ): # perform initial parse to determine alphabets and locate scores bad_matrix = "invalid scoring matrix" s = s.rstrip( "\n" ) lines = s.split( "\n" ) rows = [] sym...
[ "\n Initialize scoring scheme from a blastz style text blob, first line\n specifies the bases for each row/col, subsequent lines contain the\n corresponding scores. Slaw extensions allow for unusual and/or\n asymmetric alphabets. Symbols can be two digit hex, and each row\n begins with symbol. Not...
Please provide a description of the function:def accumulate_scores( scoring_scheme, text1, text2, skip_ref_gaps=False ): if skip_ref_gaps: rval = zeros( len( text1 ) - text1.count( scoring_scheme.gap1 ) ) else: rval = zeros( len( text1 ) ) score = 0 pos = 0 last_gap_a = last_gap...
[ "\n Return cumulative scores for each position in alignment as a 1d array.\n \n If `skip_ref_gaps` is False positions in returned array correspond to each\n column in alignment, if True they correspond to each non-gap position (each\n base) in text1.\n " ]
Please provide a description of the function:def shuffle_columns( a ): mask = range( a.text_size ) random.shuffle( mask ) for c in a.components: c.text = ''.join( [ c.text[i] for i in mask ] )
[ "Randomize the columns of an alignment" ]
Please provide a description of the function:def slice_by_component( self, component_index, start, end ): if type( component_index ) == type( 0 ): ref = self.components[ component_index ] elif type( component_index ) == type( "" ): ref = self.get_component_by_src( compon...
[ "\n Return a slice of the alignment, corresponding to an coordinate interval in a specific component.\n\n component_index is one of\n an integer offset into the components list\n a string indicating the src of the desired component\n a component\n\n start and en...
Please provide a description of the function:def remove_all_gap_columns( self ): seqs = [] for c in self.components: try: seqs.append( list( c.text ) ) except TypeError: seqs.append( None ) i = 0 text_size = self.text_size ...
[ "\n Remove any columns containing only gaps from alignment components,\n text of components is modified IN PLACE.\n " ]
Please provide a description of the function:def slice_by_coord( self, start, end ): start_col = self.coord_to_col( start ) end_col = self.coord_to_col( end ) if (self.strand == '-'): (start_col,end_col) = (end_col,start_col) return self.slice( start_col, end_col )
[ "\n Return the slice of the component corresponding to a coordinate interval.\n\n start and end are relative to the + strand, regardless of the component's strand.\n\n " ]
Please provide a description of the function:def coord_to_col( self, pos ): start,end = self.get_forward_strand_start(),self.get_forward_strand_end() if pos < start or pos > end: raise ValueError("Range error: %d not in %d-%d" % ( pos, start, end )) if not self.index: ...
[ "\n Return the alignment column index corresponding to coordinate pos.\n\n pos is relative to the + strand, regardless of the component's strand.\n\n " ]
Please provide a description of the function:def thread( mafs, species ): for m in mafs: new_maf = deepcopy( m ) new_components = get_components_for_species( new_maf, species ) if new_components: remove_all_gap_columns( new_components ) new_maf.compon...
[ "\n Restrict an list of alignments to a given list of species by:\n \n 1) Removing components for any other species \n 2) Remove any columns containing all gaps\n \n Example:\n \n >>> import bx.align.maf\n \n >>> block1 = bx.align.maf.from_string( '''\n ... a score=496...
Please provide a description of the function:def get_components_for_species( alignment, species ): # If the number of components in the alignment is less that the requested number # of species we can immediately fail if len( alignment.components ) < len( species ): return None # Otherwise, build an...
[ "Return the component for each species in the list `species` or None" ]
Please provide a description of the function:def remove_all_gap_columns( components ): seqs = [ list( c.text ) for c in components ] i = 0 text_size = len( seqs[0] ) while i < text_size: all_gap = True for seq in seqs: if seq[i] != '-': all_gap = False if...
[ "\n Remove any columns containing only gaps from a set of alignment components,\n text of components is modified IN PLACE.\n \n TODO: Optimize this with Pyrex.\n " ]
Please provide a description of the function:def read_next_maf( file, species_to_lengths=None, parse_e_rows=False ): alignment = Alignment(species_to_lengths=species_to_lengths) # Attributes line line = readline( file, skip_blank=True ) if not line: return None fields = line.split() if fie...
[ "\n Read the next MAF block from `file` and return as an `Alignment` \n instance. If `parse_i_rows` is true, empty components will be created \n when e rows are encountered.\n " ]
Please provide a description of the function:def readline( file, skip_blank=False ): while 1: line = file.readline() #print "every line: %r" % line if not line: return None if line[0] != '#' and not ( skip_blank and line.isspace() ): return line
[ "Read a line from provided file, skipping any blank or comment lines" ]
Please provide a description of the function:def parse_attributes( fields ): attributes = {} for field in fields: pair = field.split( '=' ) attributes[ pair[0] ] = pair[1] return attributes
[ "Parse list of key=value strings into a dict" ]
Please provide a description of the function:def as_dict( self, key="id" ): rval = {} for motif in self: rval[ getattr( motif, key ) ] = motif return rval
[ "\n Return a dictionary containing all remaining motifs, using `key`\n as the dictionary key.\n " ]
Please provide a description of the function:def parse_record( self, lines ): # Break lines up temp_lines = [] for line in lines: fields = line.rstrip( "\r\n" ).split( None, 1 ) if len( fields ) == 1: fields.append( "" ) temp_lines.app...
[ "\n Parse a TRANSFAC record out of `lines` and return a motif.\n " ]
Please provide a description of the function:def bit_clone( bits ): new = BitSet( bits.size ) new.ior( bits ) return new
[ "\n Clone a bitset\n " ]
Please provide a description of the function:def throw_random( lengths, mask ): saved = None for i in range( maxtries ): try: return throw_random_bits( lengths, mask ) except MaxtriesException as e: saved = e continue raise e
[ "\n Try multiple times to run 'throw_random'\n " ]
Please provide a description of the function:def as_bits( region_start, region_length, intervals ): bits = BitSet( region_length ) for chr, start, stop in intervals: bits.set_range( start - region_start, stop - start ) return bits
[ "\n Convert a set of intervals overlapping a region of a chromosome into \n a bitset for just that region with the bits covered by the intervals \n set.\n " ]
Please provide a description of the function:def interval_lengths( bits ): end = 0 while 1: start = bits.next_set( end ) if start == bits.size: break end = bits.next_clear( start ) yield end - start
[ "\n Get the length distribution of all contiguous runs of set bits from\n " ]
Please provide a description of the function:def count_overlap( bits1, bits2 ): b = BitSet( bits1.size ) b |= bits1 b &= bits2 return b.count_range( 0, b.size )
[ "\n Count the number of bits that overlap between two sets\n " ]
Please provide a description of the function:def overlapping_in_bed( fname, r_chr, r_start, r_stop ): rval = [] for line in open( fname ): if line.startswith( "#" ) or line.startswith( "track" ): continue fields = line.split() chr, start, stop = fields[0], int( fields[1]...
[ "\n Get from a bed all intervals that overlap the region defined by\n r_chr, r_start, r_stop.\n " ]
Please provide a description of the function:def tile_interval( sources, index, ref_src, start, end, seq_db=None ): # First entry in sources should also be on the reference species assert sources[0].split('.')[0] == ref_src.split('.')[0], \ "%s != %s" % ( sources[0].split('.')[0], ref_src.split('.'...
[ "\n Tile maf blocks onto an interval. The resulting block will span the interval\n exactly and contain the column from the highest scoring alignment at each\n position.\n\n `sources`: list of sequence source names to include in final block\n `index`: an instnace that can return maf blocks overlapping...
Please provide a description of the function:def MafMotifSelect(mafblock,pwm,motif=None,threshold=0): if motif != None and len(motif) != len(pwm): raise Exception("pwm and motif must be the same length") # generic alignment alignlist = [ c.text for c in mafblock.components ] align = pwmx.Align...
[ "\n for ir in range(nrows):\n # scan alignment row for motif subsequences\n for start in range(ncols):\n if align.rows[ir][start] == '-': continue\n elif align.rows[ir][start] == 'n': continue\n elif align.rows[ir][start] == 'N': continue\n # gather enoug...
Please provide a description of the function:def create_parser(): # Basic tokens real = Combine( Word( "+-" + nums, nums ) + Optional( "." + Optional( Word( nums ) ) ) + Optional( CaselessLiteral( "E" ) + Word( "+-" + nums, nums ) ) ) lpar = Suppress( "(" ) r...
[ "\n Create a 'pyparsing' parser for newick format trees roughly based on the\n grammar here:\n http://evolution.genetics.washington.edu/phylip/newick_doc.html\n\n Problems:\n - Is a single leaf a valid tree?\n - Branch length on root? Doesn't make sense to me, and forces the root\n ...
Please provide a description of the function:def get_fill_char( maf_status ): ## assert maf_status not in ( maf.MAF_CONTIG_NESTED_STATUS, maf.MAF_NEW_NESTED_STATUS, ## maf.MAF_MAYBE_NEW_NESTED_STATUS ), \ ## "Nested rows do not make sense in a single coverage MAF (or do ...
[ "\n Return the character that should be used to fill between blocks\n having a given status\n " ]
Please provide a description of the function:def guess_fill_char( left_comp, right_comp ): # No left component, obiously new return "*" # First check that the blocks have the same src (not just species) and # orientation if ( left_comp.src == right_comp.src and left_comp.strand != right_comp.s...
[ "\n For the case where there is no annotated synteny we will try to guess it\n " ]
Please provide a description of the function:def remove_all_gap_columns( texts ): seqs = [ list( t ) for t in texts ] i = 0 text_size = len( texts[0] ) while i < text_size: all_gap = True for seq in seqs: if seq[i] not in ( '-', '#', '*', '=', 'X', '@' ): ...
[ "\n Remove any columns containing only gaps from alignment texts\n " ]
Please provide a description of the function:def cross_lists(*sets): wheels = [iter(_) for _ in sets] digits = [next(it) for it in wheels] while True: yield digits[:] for i in range(len(digits)-1, -1, -1): try: digits[i] = next(wheels[i]) brea...
[ "Return the cross product of the arguments" ]
Please provide a description of the function:def read_lengths_file( name ): chrom_to_length = {} f = file ( name, "rt" ) for line in f: line = line.strip() if line == '' or line[0] == '#': continue try: fields = line.split() if len(fields) != 2: raise ...
[ "\n Returns a hash from sequence name to length.\n " ]
Please provide a description of the function:def IntervalReader( f ): current_chrom = None current_pos = None current_step = None # always for wiggle data strand = '+' mode = "bed" for line in f: if line.isspace() or line.startswith( "track" ) or line.startswith( "#" ) or lin...
[ "\n Iterator yielding chrom, start, end, strand, value.\n Values are zero-based, half-open.\n Regions which lack a score are ignored.\n " ]
Please provide a description of the function:def read_and_unpack( self, format, byte_count=None ): pattern = "%s%s" % ( self.endian_code, format ) if byte_count is None: byte_count = struct.calcsize( pattern ) return struct.unpack( pattern, self.file.read( byte_count ) )
[ "\n Read enough bytes to unpack according to `format` and return the\n tuple of unpacked values.\n " ]
Please provide a description of the function:def read_c_string( self ): rval = [] while 1: ch = self.file.read(1) assert len( ch ) == 1, "Unexpected end of file" if ch == b'\0': break rval.append( ch ) return b''.join( rval...
[ "\n Read a zero terminated (C style) string\n " ]
Please provide a description of the function:def pack_and_write( self, format, value ): pattern = "%s%s" % ( self.endian_code, format ) return self.file.write( struct.pack( pattern, value ) )
[ "\n Read enough bytes to unpack according to `format` and return the\n tuple of unpacked values.\n " ]
Please provide a description of the function:def write_c_string( self, value ): self.file.write( value ) self.file.write( b'\0' )
[ "\n Read a zero terminated (C style) string\n " ]
Please provide a description of the function:def fuse_list( mafs ): last = None for m in mafs: if last is None: last = m else: fused = fuse( last, m ) if fused: last = fused else: yield last last...
[ "\n Try to fuse a list of blocks by progressively fusing each adjacent pair.\n " ]
Please provide a description of the function:def fuse( m1, m2 ): # Check if the blocks are adjacent, return none if not. if len( m1.components ) != len( m2.components ): return None for c1, c2 in zip( m1.components, m2.components ): if c1.src != c2.src: return None if c1.strand != c2.st...
[ "\n Attempt to fuse two blocks. If they can be fused returns a new block, \n otherwise returns None.\n \n Example:\n \n >>> import bx.align.maf\n \n >>> block1 = bx.align.maf.from_string( '''\n ... a score=0.0\n ... s hg18.chr10 52686 44 + 135374737 GTGCTAACTTACTGCTCCACAGAAAACATC...
Please provide a description of the function:def countedArray( expr ): arrayExpr = Forward() def countFieldParseAction(s,l,t): n = int(t[0]) arrayExpr << (n and Group(And([expr]*n)) or Group(empty)) return [] return ( Word(nums).setName("arrayLen").setParseAction(countFieldParse...
[ "Helper to define a counted list of expressions.\n This helper defines a pattern of the form::\n integer expr expr expr...\n where the leading integer tells how many expr expressions follow.\n The matched tokens returns the array of expr tokens as a list - the leading count token is supp...
Please provide a description of the function:def nestedExpr(opener="(", closer=")", content=None, ignoreExpr=quotedString): if opener == closer: raise ValueError("opening and closing strings cannot be the same") if content is None: if isinstance(opener,basestring) and isinstance(closer,base...
[ "Helper method for defining nested lists enclosed in opening and closing\n delimiters (\"(\" and \")\" are the default).\n\n Parameters:\n - opener - opening character for a nested list (default=\"(\"); can also be a pyparsing expression\n - closer - closing character for a nested list (de...
Please provide a description of the function:def setBreak(self,breakFlag = True): if breakFlag: _parseMethod = self._parse def breaker(instring, loc, doActions=True, callPreParse=True): import pdb pdb.set_trace() _parseMethod( inst...
[ "Method to invoke the Python pdb debugger when this element is\n about to be parsed. Set breakFlag to True to enable, False to\n disable.\n " ]
Please provide a description of the function:def _normalizeParseActionArgs( f ): STAR_ARGS = 4 try: restore = None if isinstance(f,type): restore = f f = f.__init__ if not _PY3K: codeObj = f.func_code ...
[ "Internal method used to decorate parse actions that take fewer than 3 arguments,\n so that all parse actions can be called as f(s,l,t)." ]
Please provide a description of the function:def parseString( self, instring, parseAll=False ): ParserElement.resetCache() if not self.streamlined: self.streamline() #~ self.saveAsList = True for e in self.ignoreExprs: e.streamline() if not se...
[ "Execute the parse expression with the given string.\n This is the main interface to the client code, once the complete\n expression has been built.\n\n If you want the grammar to require that the entire input string be\n successfully parsed, then set parseAll to True (equiva...
Please provide a description of the function:def transformString( self, instring ): out = [] lastE = 0 # force preservation of <TAB>s, to minimize unwanted transformation of string, and to # keep string locs straight between transformString and scanString self.keepTabs =...
[ "Extension to scanString, to modify matching text with modified tokens that may\n be returned from a parse action. To use transformString, define a grammar and\n attach a parse action to it that modifies the returned token list.\n Invoking transformString() on a target string will the...
Please provide a description of the function:def searchString( self, instring, maxMatches=_MAX_INT ): return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ])
[ "Another extension to scanString, simplifying the access to the tokens found\n to match the given parse expression. May be called with optional\n maxMatches argument, to clip searching after 'n' matches are found.\n " ]
Please provide a description of the function:def parseFile( self, file_or_filename ): try: file_contents = file_or_filename.read() except AttributeError: f = open(file_or_filename, "rb") file_contents = f.read() f.close() return self.parse...
[ "Execute the parse expression on the given file or filename.\n If a filename is specified (instead of a file object),\n the entire file is opened, read, and closed before parsing.\n " ]
Please provide a description of the function:def _strfactory(cls, line): assert type(line) == str, "this is a factory from string" line = line.rstrip().split()[1:] # the first component is the keyword "chain" tup = [t[0](t[1]) for t in zip([int, str, int, str, int, int, str, int, str,...
[ "factory class method for Chain\n\n :param line: header of a chain (in .chain format)\n " ]
Please provide a description of the function:def _make_from_epo(cls, trg_comp, qr_comp, trg_chrom_sizes, qr_chrom_sizes): # size, target, query arrays S, T, Q = [], [], [] #the target strand of the chain must be on the forward strand trg_intervals = trg_comp.intervals(reverse ...
[ "crate a chain of collinear rings from the given components.\n\n The target of the chain will always be on the forward strand.\n This is done to avoid confusion when mapping psl files. So,\n if trg_comp.strand=-, qr_comp.strand=- (resp. +) the\n chain header will have tStrand=+, qStrand...
Please provide a description of the function:def slice(self, who): "return the slice entry (in a bed6 format), AS IS in the chain header" assert who in ('t', 'q'), "who should be 't' or 'q'" if who == 't': return (self.tName, self.tStart, self.tEnd, self.id, self.score, self.tStran...
[]
Please provide a description of the function:def bedInterval(self, who): "return a BED6 entry, thus DOES coordinate conversion for minus strands" if who == 't': st, en = self.tStart, self.tEnd if self.tStrand == '-': st, en = self.tSize-en, self.tSize-st ...
[]
Please provide a description of the function:def _parse_file(cls, path, pickle=False): fname = path if fname.endswith(".gz"): fname = path[:-3] if fname.endswith('.pkl'): #you asked for the pickled file. I'll give it to you log.debug("loading pickle...
[ "parse a .chain file into a list of the type [(L{Chain}, arr, arr, arr) ...]\n\n :param fname: name of the file" ]
Please provide a description of the function:def _strfactory(cls, line): cmp = line.rstrip().split() chrom = cmp[2] if not chrom.startswith("chr"): chrom = "chr%s" % chrom instance = tuple.__new__(cls, (cmp[0], cmp[1], chrom, int...
[ "factory method for an EPOitem\n\n :param line: a line of input" ]
Please provide a description of the function:def _parse_epo(cls, fname): data = {} with open(fname) as fd: for el in (cls._strfactory(_) for _ in fd): if el: data.setdefault(el.gabid, []).append( el ) log.info("parsed %d elements from %s"...
[ "Load an entire file in the EPO format into a dictionary of the type {gab_id => [Epoitem, ...]}\n\n :param fname: file name" ]
Please provide a description of the function:def cigar_iter(self, reverse): l = 0 P = self.cigar_pattern data = [] cigar = self.cigar parsed_cigar = re.findall(P, cigar) if reverse: parsed_cigar = parsed_cigar[::-1] for _l, t in parsed_cigar...
[ "self.cigar => [(length, type) ... ] iterate the cigar\n\n :param reverse: whether to iterate in the reverse direction (right-to-left)\n :type reverse: boolean\n\n :return a list of pairs of the type [(length, M/D) ..]\n " ]
Please provide a description of the function:def intervals(self, reverse, thr=0): d = [(thr,thr)] dl = 0 for tup in self.cigar_iter(reverse): if tup[1] == "D": dl = tup[0] else: s = d[-1][1] + dl d.append( (s, s+tu...
[ "return a list of (0-based half-open) intervals representing the match regions of the cigar\n\n for example 4MD4M2DM with reverse=False will produce [(0,4), (5,9), (11,12)]\n 4MD4M2DM with reverse=True will produce [(0,1), (3,7), (8,12)] (= 12 - previous interval)\n\n :param reverse: whether to...
Please provide a description of the function:def do_interval( sources, index, out, ref_src, start, end, seq_db, missing_data, strand ): ref_src_size = None # Make sure the reference component is also the first in the source list assert sources[0].split('.')[0] == ref_src.split('.')[0], "%s != %s" \ ...
[ "\n Join together alignment blocks to create a semi human projected local \n alignment (small reference sequence deletions are kept as supported by \n the local alignment).\n " ]
Please provide a description of the function:def binned_bitsets_from_file( f, chrom_col=0, start_col=1, end_col=2, strand_col=5, upstream_pad=0, downstream_pad=0, lens={} ): last_chrom = None last_bitset = None bitsets = dict() for line in f: if line.startswith("#") or line.isspace(): ...
[ "\n Read a file into a dictionary of bitsets. The defaults arguments \n \n - 'f' should be a file like object (or any iterable containing strings)\n - 'chrom_col', 'start_col', and 'end_col' must exist in each line. \n - 'strand_col' is optional, any line without it will be assumed to be '+'\n - i...
Please provide a description of the function:def binned_bitsets_proximity( f, chrom_col=0, start_col=1, end_col=2, strand_col=5, upstream=0, downstream=0 ): last_chrom = None last_bitset = None bitsets = dict() for line in f: if line.startswith("#"): continue # print "input=%s" % ( l...
[ "Read a file into a dictionary of bitsets" ]
Please provide a description of the function:def binned_bitsets_from_list( list=[] ): last_chrom = None last_bitset = None bitsets = dict() for l in list: chrom = l[0] if chrom != last_chrom: if chrom not in bitsets: bitsets[chrom] = BinnedBitSet(MAX) ...
[ "Read a list into a dictionary of bitsets" ]
Please provide a description of the function:def binned_bitsets_by_chrom( f, chrom, chrom_col=0, start_col=1, end_col=2): bitset = BinnedBitSet( MAX ) for line in f: if line.startswith("#"): continue fields = line.split() if fields[chrom_col] == chrom: start, end = int( ...
[ "Read a file by chrom name into a bitset" ]
Please provide a description of the function:def chop_list( blocks, src, start, end ): new_blocks = [] for block in blocks: ref = block.get_component_by_src( src ) # If the reference component is on the '-' strand we should complement the interval if ref.strand == '-': ...
[ "\n For each alignment block in the sequence `blocks`, chop out the portion\n of the block that overlaps the interval [`start`,`end`) in the\n component/species named `src`.\n " ]
Please provide a description of the function:def _double_as_bytes(dval): "Use struct.unpack to decode a double precision float into eight bytes" tmp = list(struct.unpack('8B',struct.pack('d', dval))) if not _big_endian: tmp.reverse() return tmp
[]
Please provide a description of the function:def _mantissa(dval): bb = _double_as_bytes(dval) mantissa = bb[1] & 0x0f << 48 mantissa += bb[2] << 40 mantissa += bb[3] << 32 mantissa += bb[4] return mantissa
[ "Extract the _mantissa bits from a double-precision floating\n point value." ]
Please provide a description of the function:def _zero_mantissa(dval): bb = _double_as_bytes(dval) return ((bb[1] & 0x0f) | reduce(operator.or_, bb[2:])) == 0
[ "Determine whether the mantissa bits of the given double are all\n zero." ]
Please provide a description of the function:def load_scores_wiggle( fname ): scores_by_chrom = dict() for chrom, pos, val in bx.wiggle.Reader( misc.open_compressed( fname ) ): if chrom not in scores_by_chrom: scores_by_chrom[chrom] = BinnedArray() scores_by_chrom[chrom][pos] = ...
[ "\n Read a wiggle file and return a dict of BinnedArray objects keyed \n by chromosome.\n " ]
Please provide a description of the function:def offsets_for_max_size( max_size ): for i, max in enumerate( reversed( BIN_OFFSETS_MAX ) ): if max_size < max: break else: raise Exception( "%d is larger than the maximum possible size (%d)" % ( max_size, BIN_OFFSETS_MAX[0] ) ) ...
[ "\n Return the subset of offsets needed to contain intervals over (0,max_size)\n " ]
Please provide a description of the function:def bin_for_range( start, end, offsets=None ): if offsets is None: offsets = BIN_OFFSETS start_bin, end_bin = start, max(start, end - 1) start_bin >>= BIN_FIRST_SHIFT end_bin >>= BIN_FIRST_SHIFT for offset in offsets: if start_bin == ...
[ "Find the smallest bin that can contain interval (start,end)" ]
Please provide a description of the function:def new( self, min, max ): # Ensure the range will fit given the shifting strategy assert MIN <= min <= max <= MAX self.min = min self.max = max # Determine offsets to use self.offsets = offsets_for_max_size( max ) ...
[ "Create an empty index for intervals in the range min, max" ]
Please provide a description of the function:def add( self, start, end, val ): insort( self.bins[ bin_for_range( start, end, offsets=self.offsets ) ], ( start, end, val ) ) assert val >= 0 self.max_val = max(self.max_val,val)
[ "Add the interval (start,end) with associated value val to the index" ]
Please provide a description of the function:def seek( self, offset, whence=0 ): # Determine absolute target position if whence == 0: target_pos = offset elif whence == 1: target_pos = self.file_pos + offset elif whence == 2: target_pos = self...
[ "\n Move the file pointer to a particular offset.\n " ]
Please provide a description of the function:def mtime(self, key): if key not in self.__dict: raise CacheKeyError(key) else: node = self.__dict[key] return node.mtime
[ "Return the last modification time for the cache record with key.\n May be useful for cache instances where the stored values can get\n 'stale', such as caching file or network resource contents." ]
Please provide a description of the function:def class_space(classlevel=3): "returns the calling class' name and dictionary" frame = sys._getframe(classlevel) classname = frame.f_code.co_name classdict = frame.f_locals return classname, classdict
[]
Please provide a description of the function:def _attribute(permission='rwd', **kwds): classname, classdict = class_space() def _property(attrname, default): propname, attrname = attrname, mangle(classname, attrname) fget, fset, fdel, doc = None, None, None, propname if 'r' in permi...
[ "returns one property for each (key,value) pair in kwds;\n each property provides the specified level of access(permission):\n 'r': readable, 'w':writable, 'd':deletable\n " ]
Please provide a description of the function:def parse_a_stanza(self): # 's' line -- score, 1 field line = self.fetch_line(report=" in a-stanza") fields = line.split() assert (fields[0] == "s"), "s line expected in a-stanza (line %d, \"%s\")" \ % (self.lineNumber,line) try: score = int(fields[1...
[ "returns the pair (score,pieces)\n\t\t where pieces is a list of ungapped segments (start1,start2,length,pctId)\n\t\t with start1,start2 origin-0" ]
Please provide a description of the function:def build_alignment(self,score,pieces): # build text self.open_seqs() text1 = text2 = "" end1 = end2 = None for (start1,start2,length,pctId) in pieces: if (end1 != None): if (start1 == end1): # insertion in sequence 2 text1 += self.seq1_gap * (sta...
[ "converts a score and pieces to an alignment" ]
Please provide a description of the function:def bits_clear_in_range( bits, range_start, range_end ): end = range_start while 1: start = bits.next_clear( end ) if start >= range_end: break end = min( bits.next_set( start ), range_end ) yield start, end
[ "\n Yield start,end tuples for each span of clear bits in [range_start,range_end)\n " ]
Please provide a description of the function:def iterprogress( sized_iterable ): pb = ProgressBar( 0, len( sized_iterable ) ) for i, value in enumerate( sized_iterable ): yield value pb.update_and_print( i, sys.stderr )
[ "\n Iterate something printing progress bar to stdout\n " ]
Please provide a description of the function:def to_file( Class, dict, file, is_little_endian=True ): io = BinaryFileWriter( file, is_little_endian=is_little_endian ) start_offset = io.tell() # Header is of fixed length io.seek( start_offset + ( 8 * 256 ) ) # For each it...
[ "\n For constructing a CDB structure in a file. Able to calculate size on\n disk and write to a file\n " ]
Please provide a description of the function:def read_len( f ): mapping = dict() for line in f: fields = line.split() mapping[ fields[0] ] = int( fields[1] ) return mapping
[ "Read a 'LEN' file and return a mapping from chromosome to length" ]
Please provide a description of the function:def freqs_to_heights( matrix ): # Columns are sequence positions, rows are symbol counts/frequencies f = matrix.values.transpose() n, m = f.shape # Ensure normalized f = f / sum( f, axis=0 ) # Shannon entropy (the where replaces 0 with 1 so that ...
[ "\n Calculate logo height using the method of:\n \n Schneider TD, Stephens RM. \"Sequence logos: a new way to display consensus \n sequences.\" Nucleic Acids Res. 1990 Oct 25;18(20):6097-100.\n " ]
Please provide a description of the function:def eps_logo( matrix, base_width, height, colors=DNA_DEFAULT_COLORS ): alphabet = matrix.sorted_alphabet rval = StringIO() # Read header ans substitute in width / height header = Template( pkg_resources.resource_string( __name__, "template.ps" ) ) rv...
[ "\n Return an EPS document containing a sequence logo for matrix where each\n bases is shown as a column of `base_width` points and the total logo\n height is `height` points. If `colors` is provided it is a mapping from\n characters to rgb color strings. \n " ]
Please provide a description of the function:def transform(elem, chain_CT_CQ, max_gap): (chain, CT, CQ) = chain_CT_CQ start, end = max(elem['start'], chain.tStart) - chain.tStart, min(elem['end'], chain.tEnd) - chain.tStart assert np.all( (CT[:,1] - CT[:,0]) == (CQ[:,1] - CQ[:,0]) ) to_chrom = cha...
[ "transform the coordinates of this elem into the other species.\n\n elem intersects this chain's ginterval.\n :return: a list of the type [(to_chr, start, end, elem[id]) ... ]" ]
Please provide a description of the function:def union_elements(elements): if len(elements) < 2: return elements assert set( [e[3] for e in elements] ) == set( [elements[0][3]] ), "more than one id" el_id = elements[0][3] unioned_elements = [] for ch, chgrp in groupby(elements, key=itemgetter...
[ "elements = [(chr, s, e, id), ...], this is to join elements that have a\n deletion in the 'to' species\n " ]
Please provide a description of the function:def transform_file(ELEMS, ofname, EPO, TREE, opt): "transform/map the elements of this file and dump the output on 'ofname'" BED4_FRM = "%s\t%d\t%d\t%s\n" log.info("%s (%d) elements ..." % (opt.screen and "screening" or "transforming", ELEMS.shape[0])) with ...
[]
Please provide a description of the function:def loadChains(path): "name says it." EPO = epo.Chain._parse_file(path, True) ## convert coordinates w.r.t the forward strand (into slices) ## compute cummulative intervals for i in range( len(EPO) ): ch, S, T, Q = EPO[i] if ch.tStrand ==...
[]
Please provide a description of the function:def loadFeatures(path, opt): log.info("loading from %s ..." % path) data = [] if opt.in_format == "BED": with open(path) as fd: for line in fd: cols = line.split() data.append( (cols[0], int(cols[1...
[ "\n Load features. For BED, only BED4 columns are loaded.\n For narrowPeak, all columns are loaded.\n " ]
Please provide a description of the function:def add(self, chrom, element): self._trees.setdefault(chrom, IntervalTree()).insert_interval( element )
[ "insert an element. use this method as the IntervalTree one.\n this will simply call the IntervalTree.add method on the right tree\n\n :param chrom: chromosome\n :param element: the argument of IntervalTree.insert_interval\n :return: None\n " ]
Please provide a description of the function:def find(self, chrom, start, end): tree = self._trees.get( chrom, None ) if tree: return tree.find( start, end ) #return always a list return []
[ "find the intersecting elements\n\n :param chrom: chromosome\n :param start: start\n :param end: end\n :return: a list of intersecting elements" ]
Please provide a description of the function:def from_rows( Class, alphabet, rows ): # Sorted alphabet sorted_alphabet = sorted( alphabet ) # Character to index mapping (initialized to -1) char_to_index = zeros( (256), int16 ) - 1 for i, ch in enumerate( sorted_alphabet...
[ "\n Create a new matrix for a sequence over alphabet `alphabet` taking \n values from `rows` which is a list whose length is the width of the\n matrix, and whose elements are lists of values associated with each\n character (in the order those characters appear in alphabet). \n " ...
Please provide a description of the function:def create_from_other( Class, other, values=None ): m = Class() m.alphabet = other.alphabet m.sorted_alphabet = other.sorted_alphabet m.char_to_index = other.char_to_index if values is not None: m.values = values ...
[ "\n Create a new Matrix with attributes taken from `other` but with the \n values taken from `values` if provided\n " ]