give the score of the best match of each motif in each sequence
        returns an iterator of lists containing floats
173375
def best_score(self, seqs, scan_rc=True, normalize=False):
        
        self.set_threshold(threshold=0.0)
        if normalize and len(self.meanstd) == 0:
            self.set_meanstd()
            means = np.array([self.meanstd[m][0] for m in self.motif_ids])
            stds = np.array([self.meanstd[m][1] for m in self.motif_ids])

        for matches in self.scan(seqs, 1, scan_rc):
            scores = np.array([sorted(m, key=lambda x: x[0])[0][0] for m in matches if len(m) > 0])
            if normalize:
                scores = (scores - means) / stds
            yield scores
309060
def percentileofscore(inlist, score, histbins=10, defaultlimits=None):
    

    h, lrl, binsize, extras = histogram(inlist, histbins, defaultlimits)
    cumhist = cumsum(copy.deepcopy(h))
    i = int((score - lrl) / float(binsize))
    pct = (cumhist[i - 1] + ((score - (lrl + binsize * i)) / float(binsize)) * h[i]) / float(len(inlist)) * 100
    return pct
1086623
def litemfreq(inlist):
    
    scores = pstat.unique(inlist)
    scores.sort()
    freq = []
    for item in scores:
        freq.append(inlist.count(item))
    return pstat.abut(scores, freq)
535542
def fasta_motif_scan( fasta_fname, input_tuples, regex_ready=False, allow_overlaps=True, file_buffer=False, molecule='dna' ):
	
	
	###################
	# validity checks #
	###################
	if not isinstance( fasta_fname, six.string_types ):
		raise TypeError( "In fasta_motif_scan, fasta_fname must be a string!" )
	elif not isinstance( molecule, six.string_types ):
		raise TypeError( "In fasta_motif_scan, molecule must be a string!" )
	elif isinstance( input_tuples, six.string_types ) or not isinstance( input_tuples, tuple ):
		raise( TypeError( "In fasta_motif_scan, input_tuples should be a tuple!" ) )
	elif not type( regex_ready ) is bool:
		raise( TypeError( "In fasta_motif_scan, regex_ready should be a bool!" ) )
	elif not type( file_buffer ) is bool:
		raise( TypeError( "In fasta_motif_scan, file_buffer should be a bool!" ) )
		
	#######################################
	# deal with temporary files if needed #
	#######################################
	if file_buffer == True:
		TMPFILE = tempfile.NamedTemporaryFile( delete = False )
		return_name = TMPFILE.name
	
	#########################
	# setup some local vars #
	#########################
	motif_seq, contig, start, end, strand = input_tuples
	
	if regex_ready == False:
		if strand == '+':
			regex_compiled = regex.compile( make_degenerate_regex( motif_seq ) )
		elif strand == '-':
			regex_compiled = regex.compile( make_degenerate_regex( rev_comp( motif_seq, molecule ) ) )
	else:
		if strand == '+':
			regex_compiled = regex.compile( motif_seq )
		elif strand == '-':
			regex_compiled = regex.compile( rev_comp( motif_seq, molecule ) )
	
	#######
	# run #
	#######
	site_count = 0
	
	if file_buffer == True:
		site_list = None
	else:
		site_list = []
	
	with pyfaidx.Fasta( fasta_fname, as_raw=True ) as FAIDX:
		sequence = str( FAIDX[contig][start:end] ).upper()
		
		for m in regex_compiled.finditer( sequence, overlapped=allow_overlaps ):
			# self, motif, contig, positionStart, strand, regexMatch, molecule='dna'
			tmp = SequenceMotif( motif_seq, contig, start, strand, m, molecule )
			
			site_count += 1
			
			if file_buffer == True:
				TMPFILE.write( "%s\n" % ( tmp ) )
			else:
				site_list.append( tmp )
	
	if file_buffer == True:
		return( input_tuples, None, return_name, site_count )
	else:
		return ( input_tuples, site_list, None, site_count )
834360
def sequence(*es):
    
    def match_sequence(s, grm=None, pos=0):
        data = []
        start = pos
        for e in es:
            s, obj, span = e(s, grm, pos)
            pos = span[1]
            if obj is not Ignore:
                data.append(obj)
        return PegreResult(s, data, (start, pos))
    return match_sequence
1106233
function get_sequence(self, weight) {
  if (undefined === self.__sequences__[weight]) {
    self.__sequences__[weight] = [];
  }

  return self.__sequences__[weight];
}
299179
def normalized_distance(self, *sequences):
        
        return float(self.distance(*sequences)) / self.maximum(*sequences)
1371739
def scores(self):
        
        return map(
            lambda x: (x[0], sum(x[1]) * len(x[1]) ** -.5),
            iter(self.items.viewitems())
        )
810317
def _plot_weights_motif(self, index, plot_type="motif_raw",
                            background_probs=DEFAULT_BASE_BACKGROUND,
                            ncol=1,
                            figsize=None):
        

        w_all = self.get_weights()

        if len(w_all) == 0:
            raise Exception("Layer needs to be initialized first")
        W = w_all[0]
        if index is None:
            index = np.arange(W.shape[2])

        if isinstance(index, int):
            index = [index]
        fig = plt.figure(figsize=figsize)

        if plot_type == "motif_pwm" and plot_type in self.AVAILABLE_PLOTS:
            arr = pssm_array2pwm_array(W, background_probs)
        elif plot_type == "motif_raw" and plot_type in self.AVAILABLE_PLOTS:
            arr = W
        elif plot_type == "motif_pwm_info" and plot_type in self.AVAILABLE_PLOTS:
            quasi_pwm = pssm_array2pwm_array(W, background_probs)
            arr = _pwm2pwm_info(quasi_pwm)
        else:
            raise ValueError("plot_type needs to be from {0}".format(self.AVAILABLE_PLOTS))

        fig = seqlogo_fig(arr, vocab=self.VOCAB_name, figsize=figsize, ncol=ncol, plot_name="filter: ")
        # fig.show()
        return fig
141221
def uniform_iterator(sequence):
    """"""

    if isinstance(sequence, abc.Mapping):
        return six.iteritems(sequence)
    else:
        return enumerate(sequence)
1177205
def compute_rewards(self, scores):
        
        k = self.k
        m = max(len(scores) - k, 0)
        best_scores = sorted(scores)[-k - 1:]
        velocities = np.diff(best_scores)
        nans = np.full(m, np.nan)
        return list(velocities) + list(nans)
615062
def bestscan(self,seq):
        
        matches,endpoints,scores = self.scan(seq,-100)
        if not scores: return -100
        scores.sort()
        best = scores[-1]
        return best
319915
def _compute_hline_scores(self):
        
        M, N, L = self.M, self.N, self.L
        hline_score = {}
        for y in range(N):
            laststart = [0 if (0, y, 0, k) in self else None for k in range(L)]
            for x in range(M):
                block = [0] * (x + 1)
                for k in range(L):
                    if (x, y, 0, k) not in self:
                        laststart[k] = None
                    elif laststart[k] is None:
                        laststart[k] = x
                        block[x] += 1
                    elif x and (x, y, 0, k) not in self[x - 1, y, 0, k]:
                        laststart[k] = x
                    else:
                        for x1 in range(laststart[k], x + 1):
                            block[x1] += 1
                for x1 in range(x + 1):
                    hline_score[y, x1, x] = block[x1]
        self._hline_score = hline_score
747613
def ILIKE(pattern):
    """"""
    return P(lambda x: fnmatch.fnmatch(x.lower(), pattern.lower()))
774982
def make_simple_col_consensus(bg_freqs):
    
    # Hack: use default kwargs to persist across iterations
    def col_consensus(col, prev_col=[], prev_char=[]):
        # Count the amino acid types in this column
        aa_counts = sequtils.aa_frequencies(col)
        assert aa_counts, "Column is all gaps! That's not allowed."
        # Take the most common residue(s)
        best_char, best_score = max(aa_counts.iteritems(),
                                    key=lambda kv: kv[1])
        # Resolve ties
        ties = [aa for aa in aa_counts if aa_counts[aa] == best_score]
        if len(ties) > 1:
            # Breaker #1: most common after the prev. consensus char
            # Resolve a tied col by restricting to rows where the preceding
            # char is the consensus type for that (preceding) col
            if prev_char and prev_col:
                mc_next = Counter(
                        [b for a, b in zip(prev_col, col)
                            if a == prev_char[0] and b in ties]
                        ).most_common()
                ties_next = [x[0] for x in mc_next
                        if x[1] == mc_next[0][1]]
                if ties_next:
                    ties = ties_next
            if len(ties) > 1:
                # Breaker #2: lowest overall residue frequency
                ties.sort(key=lambda aa: bg_freqs[aa])
            best_char = ties[0]
        else:
            assert best_char == ties[0], \
                    'WTF %s != %s[0]' % (best_char, ties)
        # Save values for tie-breaker #1
        prev_col[:] = col
        prev_char[:] = best_char
        return best_char
    return col_consensus
703853
@Benchmark
  public void fizzBuzzPatternMatching() {
    IntStream.range(0, 101).forEach(
        n -> System.out.println(
            match(Tuple2.of(n % 3, n % 5))
                .when(tuple2(eq(0), eq(0))).get(() -> "FizzBuzz")
                .when(tuple2(eq(0), any())).get(y -> "Fizz")
                .when(tuple2(any(), eq(0))).get(x -> "Buzz")
                .orElse(String.valueOf(n))
                .getMatch()
        )
    );
  }
599145
def get_sequences_from_cluster(c1, c2, data):
    """"""
    seqs1 = data[c1]['seqs']
    seqs2 = data[c2]['seqs']
    seqs = list(set(seqs1 + seqs2))
    names = []
    for s in seqs:
        if s in seqs1 and s in seqs2:
            names.append("both")
        elif s in seqs1:
            names.append(c1)
        else:
            names.append(c2)
    return seqs, names