repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Interpolator.Reverse
def Reverse(self, y): """Looks up y and returns the corresponding value of x.""" return self._Bisect(y, self.ys, self.xs)
python
def Reverse(self, y): """Looks up y and returns the corresponding value of x.""" return self._Bisect(y, self.ys, self.xs)
Looks up y and returns the corresponding value of x.
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L104-L106
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Interpolator._Bisect
def _Bisect(self, x, xs, ys): """Helper function.""" if x <= xs[0]: return ys[0] if x >= xs[-1]: return ys[-1] i = bisect.bisect(xs, x) frac = 1.0 * (x - xs[i - 1]) / (xs[i] - xs[i - 1]) y = ys[i - 1] + frac * 1.0 * (ys[i] - ys[i - 1]) retu...
python
def _Bisect(self, x, xs, ys): """Helper function.""" if x <= xs[0]: return ys[0] if x >= xs[-1]: return ys[-1] i = bisect.bisect(xs, x) frac = 1.0 * (x - xs[i - 1]) / (xs[i] - xs[i - 1]) y = ys[i - 1] + frac * 1.0 * (ys[i] - ys[i - 1]) retu...
Helper function.
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L108-L117
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
_DictWrapper.InitMapping
def InitMapping(self, values): """Initializes with a map from value to probability. values: map from value to probability """ for value, prob in values.iteritems(): self.Set(value, prob)
python
def InitMapping(self, values): """Initializes with a map from value to probability. values: map from value to probability """ for value, prob in values.iteritems(): self.Set(value, prob)
Initializes with a map from value to probability. values: map from value to probability
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L162-L168
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
_DictWrapper.InitPmf
def InitPmf(self, values): """Initializes with a Pmf. values: Pmf object """ for value, prob in values.Items(): self.Set(value, prob)
python
def InitPmf(self, values): """Initializes with a Pmf. values: Pmf object """ for value, prob in values.Items(): self.Set(value, prob)
Initializes with a Pmf. values: Pmf object
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L170-L176
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
_DictWrapper.Copy
def Copy(self, name=None): """Returns a copy. Make a shallow copy of d. If you want a deep copy of d, use copy.deepcopy on the whole object. Args: name: string name for the new Hist """ new = copy.copy(self) new.d = copy.copy(self.d) new.nam...
python
def Copy(self, name=None): """Returns a copy. Make a shallow copy of d. If you want a deep copy of d, use copy.deepcopy on the whole object. Args: name: string name for the new Hist """ new = copy.copy(self) new.d = copy.copy(self.d) new.nam...
Returns a copy. Make a shallow copy of d. If you want a deep copy of d, use copy.deepcopy on the whole object. Args: name: string name for the new Hist
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L194-L206
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
_DictWrapper.Scale
def Scale(self, factor): """Multiplies the values by a factor. factor: what to multiply by Returns: new object """ new = self.Copy() new.d.clear() for val, prob in self.Items(): new.Set(val * factor, prob) return new
python
def Scale(self, factor): """Multiplies the values by a factor. factor: what to multiply by Returns: new object """ new = self.Copy() new.d.clear() for val, prob in self.Items(): new.Set(val * factor, prob) return new
Multiplies the values by a factor. factor: what to multiply by Returns: new object
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L208-L220
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
_DictWrapper.Log
def Log(self, m=None): """Log transforms the probabilities. Removes values with probability 0. Normalizes so that the largest logprob is 0. """ if self.log: raise ValueError("Pmf/Hist already under a log transform") self.log = True if m is N...
python
def Log(self, m=None): """Log transforms the probabilities. Removes values with probability 0. Normalizes so that the largest logprob is 0. """ if self.log: raise ValueError("Pmf/Hist already under a log transform") self.log = True if m is N...
Log transforms the probabilities. Removes values with probability 0. Normalizes so that the largest logprob is 0.
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L222-L240
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
_DictWrapper.Exp
def Exp(self, m=None): """Exponentiates the probabilities. m: how much to shift the ps before exponentiating If m is None, normalizes so that the largest prob is 1. """ if not self.log: raise ValueError("Pmf/Hist not under a log transform") self.log = False ...
python
def Exp(self, m=None): """Exponentiates the probabilities. m: how much to shift the ps before exponentiating If m is None, normalizes so that the largest prob is 1. """ if not self.log: raise ValueError("Pmf/Hist not under a log transform") self.log = False ...
Exponentiates the probabilities. m: how much to shift the ps before exponentiating If m is None, normalizes so that the largest prob is 1.
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L242-L257
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
_DictWrapper.Print
def Print(self): """Prints the values and freqs/probs in ascending order.""" for val, prob in sorted(self.d.iteritems()): print(val, prob)
python
def Print(self): """Prints the values and freqs/probs in ascending order.""" for val, prob in sorted(self.d.iteritems()): print(val, prob)
Prints the values and freqs/probs in ascending order.
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L288-L291
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
_DictWrapper.Incr
def Incr(self, x, term=1): """Increments the freq/prob associated with the value x. Args: x: number value term: how much to increment by """ self.d[x] = self.d.get(x, 0) + term
python
def Incr(self, x, term=1): """Increments the freq/prob associated with the value x. Args: x: number value term: how much to increment by """ self.d[x] = self.d.get(x, 0) + term
Increments the freq/prob associated with the value x. Args: x: number value term: how much to increment by
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L302-L309
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
_DictWrapper.Mult
def Mult(self, x, factor): """Scales the freq/prob associated with the value x. Args: x: number value factor: how much to multiply by """ self.d[x] = self.d.get(x, 0) * factor
python
def Mult(self, x, factor): """Scales the freq/prob associated with the value x. Args: x: number value factor: how much to multiply by """ self.d[x] = self.d.get(x, 0) * factor
Scales the freq/prob associated with the value x. Args: x: number value factor: how much to multiply by
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L311-L318
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Hist.IsSubset
def IsSubset(self, other): """Checks whether the values in this histogram are a subset of the values in the given histogram.""" for val, freq in self.Items(): if freq > other.Freq(val): return False return True
python
def IsSubset(self, other): """Checks whether the values in this histogram are a subset of the values in the given histogram.""" for val, freq in self.Items(): if freq > other.Freq(val): return False return True
Checks whether the values in this histogram are a subset of the values in the given histogram.
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L361-L367
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Hist.Subtract
def Subtract(self, other): """Subtracts the values in the given histogram from this histogram.""" for val, freq in other.Items(): self.Incr(val, -freq)
python
def Subtract(self, other): """Subtracts the values in the given histogram from this histogram.""" for val, freq in other.Items(): self.Incr(val, -freq)
Subtracts the values in the given histogram from this histogram.
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L369-L372
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Pmf.ProbGreater
def ProbGreater(self, x): """Probability that a sample from this Pmf exceeds x. x: number returns: float probability """ t = [prob for (val, prob) in self.d.iteritems() if val > x] return sum(t)
python
def ProbGreater(self, x): """Probability that a sample from this Pmf exceeds x. x: number returns: float probability """ t = [prob for (val, prob) in self.d.iteritems() if val > x] return sum(t)
Probability that a sample from this Pmf exceeds x. x: number returns: float probability
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L402-L410
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Pmf.Normalize
def Normalize(self, fraction=1.0): """Normalizes this PMF so the sum of all probs is fraction. Args: fraction: what the total should be after normalization Returns: the total probability before normalizing """ if self.log: raise ValueError("Pmf is under ...
python
def Normalize(self, fraction=1.0): """Normalizes this PMF so the sum of all probs is fraction. Args: fraction: what the total should be after normalization Returns: the total probability before normalizing """ if self.log: raise ValueError("Pmf is under ...
Normalizes this PMF so the sum of all probs is fraction. Args: fraction: what the total should be after normalization Returns: the total probability before normalizing
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L485-L506
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Pmf.Random
def Random(self): """Chooses a random element from this PMF. Returns: float value from the Pmf """ if len(self.d) == 0: raise ValueError('Pmf contains no values.') target = random.random() total = 0.0 for x, p in self.d.iteritems(): ...
python
def Random(self): """Chooses a random element from this PMF. Returns: float value from the Pmf """ if len(self.d) == 0: raise ValueError('Pmf contains no values.') target = random.random() total = 0.0 for x, p in self.d.iteritems(): ...
Chooses a random element from this PMF. Returns: float value from the Pmf
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L508-L525
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Pmf.Mean
def Mean(self): """Computes the mean of a PMF. Returns: float mean """ mu = 0.0 for x, p in self.d.iteritems(): mu += p * x return mu
python
def Mean(self): """Computes the mean of a PMF. Returns: float mean """ mu = 0.0 for x, p in self.d.iteritems(): mu += p * x return mu
Computes the mean of a PMF. Returns: float mean
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L527-L536
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Pmf.Var
def Var(self, mu=None): """Computes the variance of a PMF. Args: mu: the point around which the variance is computed; if omitted, computes the mean Returns: float variance """ if mu is None: mu = self.Mean() var = 0.0...
python
def Var(self, mu=None): """Computes the variance of a PMF. Args: mu: the point around which the variance is computed; if omitted, computes the mean Returns: float variance """ if mu is None: mu = self.Mean() var = 0.0...
Computes the variance of a PMF. Args: mu: the point around which the variance is computed; if omitted, computes the mean Returns: float variance
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L538-L554
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Pmf.MaximumLikelihood
def MaximumLikelihood(self): """Returns the value with the highest probability. Returns: float probability """ prob, val = max((prob, val) for val, prob in self.Items()) return val
python
def MaximumLikelihood(self): """Returns the value with the highest probability. Returns: float probability """ prob, val = max((prob, val) for val, prob in self.Items()) return val
Returns the value with the highest probability. Returns: float probability
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L556-L562
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Pmf.AddPmf
def AddPmf(self, other): """Computes the Pmf of the sum of values drawn from self and other. other: another Pmf returns: new Pmf """ pmf = Pmf() for v1, p1 in self.Items(): for v2, p2 in other.Items(): pmf.Incr(v1 + v2, p1 * p2) retur...
python
def AddPmf(self, other): """Computes the Pmf of the sum of values drawn from self and other. other: another Pmf returns: new Pmf """ pmf = Pmf() for v1, p1 in self.Items(): for v2, p2 in other.Items(): pmf.Incr(v1 + v2, p1 * p2) retur...
Computes the Pmf of the sum of values drawn from self and other. other: another Pmf returns: new Pmf
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L590-L601
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Pmf.AddConstant
def AddConstant(self, other): """Computes the Pmf of the sum a constant and values from self. other: a number returns: new Pmf """ pmf = Pmf() for v1, p1 in self.Items(): pmf.Set(v1 + other, p1) return pmf
python
def AddConstant(self, other): """Computes the Pmf of the sum a constant and values from self. other: a number returns: new Pmf """ pmf = Pmf() for v1, p1 in self.Items(): pmf.Set(v1 + other, p1) return pmf
Computes the Pmf of the sum a constant and values from self. other: a number returns: new Pmf
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L603-L613
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Pmf.Max
def Max(self, k): """Computes the CDF of the maximum of k selections from this dist. k: int returns: new Cdf """ cdf = self.MakeCdf() cdf.ps = [p ** k for p in cdf.ps] return cdf
python
def Max(self, k): """Computes the CDF of the maximum of k selections from this dist. k: int returns: new Cdf """ cdf = self.MakeCdf() cdf.ps = [p ** k for p in cdf.ps] return cdf
Computes the CDF of the maximum of k selections from this dist. k: int returns: new Cdf
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L628-L637
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Joint.Marginal
def Marginal(self, i, name=''): """Gets the marginal distribution of the indicated variable. i: index of the variable we want Returns: Pmf """ pmf = Pmf(name=name) for vs, prob in self.Items(): pmf.Incr(vs[i], prob) return pmf
python
def Marginal(self, i, name=''): """Gets the marginal distribution of the indicated variable. i: index of the variable we want Returns: Pmf """ pmf = Pmf(name=name) for vs, prob in self.Items(): pmf.Incr(vs[i], prob) return pmf
Gets the marginal distribution of the indicated variable. i: index of the variable we want Returns: Pmf
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L646-L656
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Joint.Conditional
def Conditional(self, i, j, val, name=''): """Gets the conditional distribution of the indicated variable. Distribution of vs[i], conditioned on vs[j] = val. i: index of the variable we want j: which variable is conditioned on val: the value the jth variable has to have ...
python
def Conditional(self, i, j, val, name=''): """Gets the conditional distribution of the indicated variable. Distribution of vs[i], conditioned on vs[j] = val. i: index of the variable we want j: which variable is conditioned on val: the value the jth variable has to have ...
Gets the conditional distribution of the indicated variable. Distribution of vs[i], conditioned on vs[j] = val. i: index of the variable we want j: which variable is conditioned on val: the value the jth variable has to have Returns: Pmf
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L658-L675
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Joint.MaxLikeInterval
def MaxLikeInterval(self, percentage=90): """Returns the maximum-likelihood credible interval. If percentage=90, computes a 90% CI containing the values with the highest likelihoods. percentage: float between 0 and 100 Returns: list of values from the suite """ ...
python
def MaxLikeInterval(self, percentage=90): """Returns the maximum-likelihood credible interval. If percentage=90, computes a 90% CI containing the values with the highest likelihoods. percentage: float between 0 and 100 Returns: list of values from the suite """ ...
Returns the maximum-likelihood credible interval. If percentage=90, computes a 90% CI containing the values with the highest likelihoods. percentage: float between 0 and 100 Returns: list of values from the suite
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L677-L699
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Cdf.Copy
def Copy(self, name=None): """Returns a copy of this Cdf. Args: name: string name for the new Cdf """ if name is None: name = self.name return Cdf(list(self.xs), list(self.ps), name)
python
def Copy(self, name=None): """Returns a copy of this Cdf. Args: name: string name for the new Cdf """ if name is None: name = self.name return Cdf(list(self.xs), list(self.ps), name)
Returns a copy of this Cdf. Args: name: string name for the new Cdf
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L881-L889
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Cdf.Append
def Append(self, x, p): """Add an (x, p) pair to the end of this CDF. Note: this us normally used to build a CDF from scratch, not to modify existing CDFs. It is up to the caller to make sure that the result is a legal CDF. """ self.xs.append(x) self.ps.append(p...
python
def Append(self, x, p): """Add an (x, p) pair to the end of this CDF. Note: this us normally used to build a CDF from scratch, not to modify existing CDFs. It is up to the caller to make sure that the result is a legal CDF. """ self.xs.append(x) self.ps.append(p...
Add an (x, p) pair to the end of this CDF. Note: this us normally used to build a CDF from scratch, not to modify existing CDFs. It is up to the caller to make sure that the result is a legal CDF.
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L907-L915
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Cdf.Shift
def Shift(self, term): """Adds a term to the xs. term: how much to add """ new = self.Copy() new.xs = [x + term for x in self.xs] return new
python
def Shift(self, term): """Adds a term to the xs. term: how much to add """ new = self.Copy() new.xs = [x + term for x in self.xs] return new
Adds a term to the xs. term: how much to add
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L917-L924
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Cdf.Scale
def Scale(self, factor): """Multiplies the xs by a factor. factor: what to multiply by """ new = self.Copy() new.xs = [x * factor for x in self.xs] return new
python
def Scale(self, factor): """Multiplies the xs by a factor. factor: what to multiply by """ new = self.Copy() new.xs = [x * factor for x in self.xs] return new
Multiplies the xs by a factor. factor: what to multiply by
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L926-L933
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Cdf.Prob
def Prob(self, x): """Returns CDF(x), the probability that corresponds to value x. Args: x: number Returns: float probability """ if x < self.xs[0]: return 0.0 index = bisect.bisect(self.xs, x) p = self.ps[index - 1] return p
python
def Prob(self, x): """Returns CDF(x), the probability that corresponds to value x. Args: x: number Returns: float probability """ if x < self.xs[0]: return 0.0 index = bisect.bisect(self.xs, x) p = self.ps[index - 1] return p
Returns CDF(x), the probability that corresponds to value x. Args: x: number Returns: float probability
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L935-L947
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Cdf.Value
def Value(self, p): """Returns InverseCDF(p), the value that corresponds to probability p. Args: p: number in the range [0, 1] Returns: number value """ if p < 0 or p > 1: raise ValueError('Probability p must be in range [0, 1]') if ...
python
def Value(self, p): """Returns InverseCDF(p), the value that corresponds to probability p. Args: p: number in the range [0, 1] Returns: number value """ if p < 0 or p > 1: raise ValueError('Probability p must be in range [0, 1]') if ...
Returns InverseCDF(p), the value that corresponds to probability p. Args: p: number in the range [0, 1] Returns: number value
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L949-L967
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Cdf.Mean
def Mean(self): """Computes the mean of a CDF. Returns: float mean """ old_p = 0 total = 0.0 for x, new_p in zip(self.xs, self.ps): p = new_p - old_p total += p * x old_p = new_p return total
python
def Mean(self): """Computes the mean of a CDF. Returns: float mean """ old_p = 0 total = 0.0 for x, new_p in zip(self.xs, self.ps): p = new_p - old_p total += p * x old_p = new_p return total
Computes the mean of a CDF. Returns: float mean
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L992-L1004
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Cdf.CredibleInterval
def CredibleInterval(self, percentage=90): """Computes the central credible interval. If percentage=90, computes the 90% CI. Args: percentage: float between 0 and 100 Returns: sequence of two floats, low and high """ prob = (1 - percentage / 100...
python
def CredibleInterval(self, percentage=90): """Computes the central credible interval. If percentage=90, computes the 90% CI. Args: percentage: float between 0 and 100 Returns: sequence of two floats, low and high """ prob = (1 - percentage / 100...
Computes the central credible interval. If percentage=90, computes the 90% CI. Args: percentage: float between 0 and 100 Returns: sequence of two floats, low and high
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1006-L1019
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Cdf.Render
def Render(self): """Generates a sequence of points suitable for plotting. An empirical CDF is a step function; linear interpolation can be misleading. Returns: tuple of (xs, ps) """ xs = [self.xs[0]] ps = [0.0] for i, p in enumerate(self.ps)...
python
def Render(self): """Generates a sequence of points suitable for plotting. An empirical CDF is a step function; linear interpolation can be misleading. Returns: tuple of (xs, ps) """ xs = [self.xs[0]] ps = [0.0] for i, p in enumerate(self.ps)...
Generates a sequence of points suitable for plotting. An empirical CDF is a step function; linear interpolation can be misleading. Returns: tuple of (xs, ps)
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1031-L1051
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Cdf.Max
def Max(self, k): """Computes the CDF of the maximum of k selections from this dist. k: int returns: new Cdf """ cdf = self.Copy() cdf.ps = [p ** k for p in cdf.ps] return cdf
python
def Max(self, k): """Computes the CDF of the maximum of k selections from this dist. k: int returns: new Cdf """ cdf = self.Copy() cdf.ps = [p ** k for p in cdf.ps] return cdf
Computes the CDF of the maximum of k selections from this dist. k: int returns: new Cdf
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1053-L1062
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Suite.LogUpdate
def LogUpdate(self, data): """Updates a suite of hypotheses based on new data. Modifies the suite directly; if you want to keep the original, make a copy. Note: unlike Update, LogUpdate does not normalize. Args: data: any representation of the data """ ...
python
def LogUpdate(self, data): """Updates a suite of hypotheses based on new data. Modifies the suite directly; if you want to keep the original, make a copy. Note: unlike Update, LogUpdate does not normalize. Args: data: any representation of the data """ ...
Updates a suite of hypotheses based on new data. Modifies the suite directly; if you want to keep the original, make a copy. Note: unlike Update, LogUpdate does not normalize. Args: data: any representation of the data
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1165-L1178
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Suite.UpdateSet
def UpdateSet(self, dataset): """Updates each hypothesis based on the dataset. This is more efficient than calling Update repeatedly because it waits until the end to Normalize. Modifies the suite directly; if you want to keep the original, make a copy. dataset: a sequ...
python
def UpdateSet(self, dataset): """Updates each hypothesis based on the dataset. This is more efficient than calling Update repeatedly because it waits until the end to Normalize. Modifies the suite directly; if you want to keep the original, make a copy. dataset: a sequ...
Updates each hypothesis based on the dataset. This is more efficient than calling Update repeatedly because it waits until the end to Normalize. Modifies the suite directly; if you want to keep the original, make a copy. dataset: a sequence of data returns: the normal...
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1180-L1197
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Suite.Print
def Print(self): """Prints the hypotheses and their probabilities.""" for hypo, prob in sorted(self.Items()): print(hypo, prob)
python
def Print(self): """Prints the hypotheses and their probabilities.""" for hypo, prob in sorted(self.Items()): print(hypo, prob)
Prints the hypotheses and their probabilities.
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1228-L1231
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Suite.MakeOdds
def MakeOdds(self): """Transforms from probabilities to odds. Values with prob=0 are removed. """ for hypo, prob in self.Items(): if prob: self.Set(hypo, Odds(prob)) else: self.Remove(hypo)
python
def MakeOdds(self): """Transforms from probabilities to odds. Values with prob=0 are removed. """ for hypo, prob in self.Items(): if prob: self.Set(hypo, Odds(prob)) else: self.Remove(hypo)
Transforms from probabilities to odds. Values with prob=0 are removed.
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1233-L1242
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Suite.MakeProbs
def MakeProbs(self): """Transforms from odds to probabilities.""" for hypo, odds in self.Items(): self.Set(hypo, Probability(odds))
python
def MakeProbs(self): """Transforms from odds to probabilities.""" for hypo, odds in self.Items(): self.Set(hypo, Probability(odds))
Transforms from odds to probabilities.
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1244-L1247
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Pdf.MakePmf
def MakePmf(self, xs, name=''): """Makes a discrete version of this Pdf, evaluated at xs. xs: equally-spaced sequence of values Returns: new Pmf """ pmf = Pmf(name=name) for x in xs: pmf.Set(x, self.Density(x)) pmf.Normalize() return pmf
python
def MakePmf(self, xs, name=''): """Makes a discrete version of this Pdf, evaluated at xs. xs: equally-spaced sequence of values Returns: new Pmf """ pmf = Pmf(name=name) for x in xs: pmf.Set(x, self.Density(x)) pmf.Normalize() return pmf
Makes a discrete version of this Pdf, evaluated at xs. xs: equally-spaced sequence of values Returns: new Pmf
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1332-L1343
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Beta.Update
def Update(self, data): """Updates a Beta distribution. data: pair of int (heads, tails) """ heads, tails = data self.alpha += heads self.beta += tails
python
def Update(self, data): """Updates a Beta distribution. data: pair of int (heads, tails) """ heads, tails = data self.alpha += heads self.beta += tails
Updates a Beta distribution. data: pair of int (heads, tails)
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1663-L1670
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Beta.Sample
def Sample(self, n): """Generates a random sample from this distribution. n: int sample size """ size = n, return numpy.random.beta(self.alpha, self.beta, size)
python
def Sample(self, n): """Generates a random sample from this distribution. n: int sample size """ size = n, return numpy.random.beta(self.alpha, self.beta, size)
Generates a random sample from this distribution. n: int sample size
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1680-L1686
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Beta.MakePmf
def MakePmf(self, steps=101, name=''): """Returns a Pmf of this distribution. Note: Normally, we just evaluate the PDF at a sequence of points and treat the probability density as a probability mass. But if alpha or beta is less than one, we have to be more careful beca...
python
def MakePmf(self, steps=101, name=''): """Returns a Pmf of this distribution. Note: Normally, we just evaluate the PDF at a sequence of points and treat the probability density as a probability mass. But if alpha or beta is less than one, we have to be more careful beca...
Returns a Pmf of this distribution. Note: Normally, we just evaluate the PDF at a sequence of points and treat the probability density as a probability mass. But if alpha or beta is less than one, we have to be more careful because the PDF goes to infinity at x=0 and x=...
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1692-L1712
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Beta.MakeCdf
def MakeCdf(self, steps=101): """Returns the CDF of this distribution.""" xs = [i / (steps - 1.0) for i in xrange(steps)] ps = [scipy.special.betainc(self.alpha, self.beta, x) for x in xs] cdf = Cdf(xs, ps) return cdf
python
def MakeCdf(self, steps=101): """Returns the CDF of this distribution.""" xs = [i / (steps - 1.0) for i in xrange(steps)] ps = [scipy.special.betainc(self.alpha, self.beta, x) for x in xs] cdf = Cdf(xs, ps) return cdf
Returns the CDF of this distribution.
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1714-L1719
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Dirichlet.Update
def Update(self, data): """Updates a Dirichlet distribution. data: sequence of observations, in order corresponding to params """ m = len(data) self.params[:m] += data
python
def Update(self, data): """Updates a Dirichlet distribution. data: sequence of observations, in order corresponding to params """ m = len(data) self.params[:m] += data
Updates a Dirichlet distribution. data: sequence of observations, in order corresponding to params
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1743-L1749
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Dirichlet.Random
def Random(self): """Generates a random variate from this distribution. Returns: normalized vector of fractions """ p = numpy.random.gamma(self.params) return p / p.sum()
python
def Random(self): """Generates a random variate from this distribution. Returns: normalized vector of fractions """ p = numpy.random.gamma(self.params) return p / p.sum()
Generates a random variate from this distribution. Returns: normalized vector of fractions
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1751-L1757
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Dirichlet.Likelihood
def Likelihood(self, data): """Computes the likelihood of the data. Selects a random vector of probabilities from this distribution. Returns: float probability """ m = len(data) if self.n < m: return 0 x = data p = self.Random() q = ...
python
def Likelihood(self, data): """Computes the likelihood of the data. Selects a random vector of probabilities from this distribution. Returns: float probability """ m = len(data) if self.n < m: return 0 x = data p = self.Random() q = ...
Computes the likelihood of the data. Selects a random vector of probabilities from this distribution. Returns: float probability
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1759-L1773
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Dirichlet.LogLikelihood
def LogLikelihood(self, data): """Computes the log likelihood of the data. Selects a random vector of probabilities from this distribution. Returns: float log probability """ m = len(data) if self.n < m: return float('-inf') x = self.Random() ...
python
def LogLikelihood(self, data): """Computes the log likelihood of the data. Selects a random vector of probabilities from this distribution. Returns: float log probability """ m = len(data) if self.n < m: return float('-inf') x = self.Random() ...
Computes the log likelihood of the data. Selects a random vector of probabilities from this distribution. Returns: float log probability
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1775-L1788
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Dirichlet.MarginalBeta
def MarginalBeta(self, i): """Computes the marginal distribution of the ith element. See http://en.wikipedia.org/wiki/Dirichlet_distribution #Marginal_distributions i: int Returns: Beta object """ alpha0 = self.params.sum() alpha = self.params[i] ...
python
def MarginalBeta(self, i): """Computes the marginal distribution of the ith element. See http://en.wikipedia.org/wiki/Dirichlet_distribution #Marginal_distributions i: int Returns: Beta object """ alpha0 = self.params.sum() alpha = self.params[i] ...
Computes the marginal distribution of the ith element. See http://en.wikipedia.org/wiki/Dirichlet_distribution #Marginal_distributions i: int Returns: Beta object
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1790-L1802
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
Dirichlet.PredictivePmf
def PredictivePmf(self, xs, name=''): """Makes a predictive distribution. xs: values to go into the Pmf Returns: Pmf that maps from x to the mean prevalence of x """ alpha0 = self.params.sum() ps = self.params / alpha0 return MakePmfFromItems(zip(xs, ps), name=n...
python
def PredictivePmf(self, xs, name=''): """Makes a predictive distribution. xs: values to go into the Pmf Returns: Pmf that maps from x to the mean prevalence of x """ alpha0 = self.params.sum() ps = self.params / alpha0 return MakePmfFromItems(zip(xs, ps), name=n...
Makes a predictive distribution. xs: values to go into the Pmf Returns: Pmf that maps from x to the mean prevalence of x
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1804-L1813
lpantano/seqcluster
seqcluster/libs/report.py
_get_ann
def _get_ann(dbs, features): """ Gives format to annotation for html table output """ value = "" for db, feature in zip(dbs, features): value += db + ":" + feature return value
python
def _get_ann(dbs, features): """ Gives format to annotation for html table output """ value = "" for db, feature in zip(dbs, features): value += db + ":" + feature return value
Gives format to annotation for html table output
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/report.py#L21-L28
lpantano/seqcluster
seqcluster/libs/report.py
make_profile
def make_profile(data, out_dir, args): """ Make data report for each cluster """ safe_dirs(out_dir) main_table = [] header = ['id', 'ann'] n = len(data[0]) bar = ProgressBar(maxval=n) bar.start() bar.update(0) for itern, c in enumerate(data[0]): bar.update(itern) ...
python
def make_profile(data, out_dir, args): """ Make data report for each cluster """ safe_dirs(out_dir) main_table = [] header = ['id', 'ann'] n = len(data[0]) bar = ProgressBar(maxval=n) bar.start() bar.update(0) for itern, c in enumerate(data[0]): bar.update(itern) ...
Make data report for each cluster
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/report.py#L39-L61
lpantano/seqcluster
seqcluster/libs/report.py
_expand
def _expand(dat, counts, start, end): """ expand the same counts from start to end """ for pos in range(start, end): for s in counts: dat[s][pos] += counts[s] return dat
python
def _expand(dat, counts, start, end): """ expand the same counts from start to end """ for pos in range(start, end): for s in counts: dat[s][pos] += counts[s] return dat
expand the same counts from start to end
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/report.py#L64-L71
lpantano/seqcluster
seqcluster/libs/report.py
_convert_to_df
def _convert_to_df(in_file, freq, raw_file): """ convert data frame into table with pandas """ dat = defaultdict(Counter) if isinstance(in_file, (str, unicode)): with open(in_file) as in_handle: for line in in_handle: cols = line.strip().split("\t") ...
python
def _convert_to_df(in_file, freq, raw_file): """ convert data frame into table with pandas """ dat = defaultdict(Counter) if isinstance(in_file, (str, unicode)): with open(in_file) as in_handle: for line in in_handle: cols = line.strip().split("\t") ...
convert data frame into table with pandas
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/report.py#L74-L97
lpantano/seqcluster
seqcluster/libs/report.py
_make
def _make(c): """ create html from template, adding figure, annotation and sequences counts """ ann = defaultdict(list) for pos in c['ann']: for db in pos: ann[db] += list(pos[db]) logger.debug(ann) valid = [l for l in c['valid']] ann_list = [", ".join(list(set(...
python
def _make(c): """ create html from template, adding figure, annotation and sequences counts """ ann = defaultdict(list) for pos in c['ann']: for db in pos: ann[db] += list(pos[db]) logger.debug(ann) valid = [l for l in c['valid']] ann_list = [", ".join(list(set(...
create html from template, adding figure, annotation and sequences counts
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/report.py#L100-L115
lpantano/seqcluster
seqcluster/libs/report.py
_single_cluster
def _single_cluster(c, data, out_file, args): """ Map sequences on precursors and create expression profile """ valid, ann = 0, 0 raw_file = None freq = defaultdict() [freq.update({s.keys()[0]: s.values()[0]}) for s in data[0][c]['freq']] names = [s.keys()[0] for s in data[0][c]['seq...
python
def _single_cluster(c, data, out_file, args): """ Map sequences on precursors and create expression profile """ valid, ann = 0, 0 raw_file = None freq = defaultdict() [freq.update({s.keys()[0]: s.values()[0]}) for s in data[0][c]['freq']] names = [s.keys()[0] for s in data[0][c]['seq...
Map sequences on precursors and create expression profile
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/report.py#L118-L149
lpantano/seqcluster
seqcluster/methods/__init__.py
read_cluster
def read_cluster(data, id=1): """Read json cluster and populate as cluster class""" cl = cluster(1) # seqs = [s.values()[0] for s in data['seqs']] names = [s.keys()[0] for s in data['seqs']] cl.add_id_member(names, 1) freq = defaultdict() [freq.update({s.keys()[0]: s.values()[0]}) for s in ...
python
def read_cluster(data, id=1): """Read json cluster and populate as cluster class""" cl = cluster(1) # seqs = [s.values()[0] for s in data['seqs']] names = [s.keys()[0] for s in data['seqs']] cl.add_id_member(names, 1) freq = defaultdict() [freq.update({s.keys()[0]: s.values()[0]}) for s in ...
Read json cluster and populate as cluster class
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/methods/__init__.py#L6-L14
lpantano/seqcluster
seqcluster/libs/read.py
write_data
def write_data(data, out_file): """write json file from seqcluster cluster""" with open(out_file, 'w') as handle_out: handle_out.write(json.dumps([data], skipkeys=True, indent=2))
python
def write_data(data, out_file): """write json file from seqcluster cluster""" with open(out_file, 'w') as handle_out: handle_out.write(json.dumps([data], skipkeys=True, indent=2))
write json file from seqcluster cluster
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/read.py#L33-L36
lpantano/seqcluster
seqcluster/libs/read.py
get_sequences_from_cluster
def get_sequences_from_cluster(c1, c2, data): """get all sequences from on cluster""" 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: ...
python
def get_sequences_from_cluster(c1, c2, data): """get all sequences from on cluster""" 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: ...
get all sequences from on cluster
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/read.py#L38-L51
lpantano/seqcluster
seqcluster/libs/read.py
map_to_precursors
def map_to_precursors(seqs, names, loci, out_file, args): """map sequences to precursors with razers3""" with make_temp_directory() as temp: pre_fasta = os.path.join(temp, "pre.fa") seqs_fasta = os.path.join(temp, "seqs.fa") out_sam = os.path.join(temp, "out.sam") pre_fasta = get...
python
def map_to_precursors(seqs, names, loci, out_file, args): """map sequences to precursors with razers3""" with make_temp_directory() as temp: pre_fasta = os.path.join(temp, "pre.fa") seqs_fasta = os.path.join(temp, "seqs.fa") out_sam = os.path.join(temp, "out.sam") pre_fasta = get...
map sequences to precursors with razers3
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/read.py#L58-L74
lpantano/seqcluster
seqcluster/libs/read.py
precursor_sequence
def precursor_sequence(loci, reference): """Get sequence from genome""" region = "%s\t%s\t%s\t.\t.\t%s" % (loci[1], loci[2], loci[3], loci[4]) precursor = pybedtools.BedTool(str(region), from_string=True).sequence(fi=reference, s=True) return open(precursor.seqfn).read().split("\n")[1]
python
def precursor_sequence(loci, reference): """Get sequence from genome""" region = "%s\t%s\t%s\t.\t.\t%s" % (loci[1], loci[2], loci[3], loci[4]) precursor = pybedtools.BedTool(str(region), from_string=True).sequence(fi=reference, s=True) return open(precursor.seqfn).read().split("\n")[1]
Get sequence from genome
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/read.py#L76-L80
lpantano/seqcluster
seqcluster/libs/read.py
map_to_precursors_on_fly
def map_to_precursors_on_fly(seqs, names, loci, args): """map sequences to precursors with franpr algorithm to avoid writting on disk""" precursor = precursor_sequence(loci, args.ref).upper() dat = dict() for s, n in itertools.izip(seqs, names): res = pyMatch.Match(precursor, str(s), 1, 3) ...
python
def map_to_precursors_on_fly(seqs, names, loci, args): """map sequences to precursors with franpr algorithm to avoid writting on disk""" precursor = precursor_sequence(loci, args.ref).upper() dat = dict() for s, n in itertools.izip(seqs, names): res = pyMatch.Match(precursor, str(s), 1, 3) ...
map sequences to precursors with franpr algorithm to avoid writting on disk
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/read.py#L82-L91
lpantano/seqcluster
seqcluster/libs/read.py
_align
def _align(x, y, local = False): """ https://medium.com/towards-data-science/pairwise-sequence-alignment-using-biopython-d1a9d0ba861f """ if local: aligned_x = pairwise2.align.localxx(x, y) else: aligned_x = pairwise2.align.globalms(x, y, 1, -1, -1, -0.5) if aligned_x: ...
python
def _align(x, y, local = False): """ https://medium.com/towards-data-science/pairwise-sequence-alignment-using-biopython-d1a9d0ba861f """ if local: aligned_x = pairwise2.align.localxx(x, y) else: aligned_x = pairwise2.align.globalms(x, y, 1, -1, -1, -0.5) if aligned_x: ...
https://medium.com/towards-data-science/pairwise-sequence-alignment-using-biopython-d1a9d0ba861f
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/read.py#L93-L106
lpantano/seqcluster
seqcluster/libs/read.py
map_to_precursor_biopython
def map_to_precursor_biopython(seqs, names, loci, args): """map the sequences using biopython package""" precursor = precursor_sequence(loci, args.ref).upper() dat = dict() for s, n in itertools.izip(seqs, names): res = _align(str(s), precursor) if res: dat[n] = res logge...
python
def map_to_precursor_biopython(seqs, names, loci, args): """map the sequences using biopython package""" precursor = precursor_sequence(loci, args.ref).upper() dat = dict() for s, n in itertools.izip(seqs, names): res = _align(str(s), precursor) if res: dat[n] = res logge...
map the sequences using biopython package
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/read.py#L108-L117
lpantano/seqcluster
seqcluster/libs/read.py
get_seqs_fasta
def get_seqs_fasta(seqs, names, out_fa): """get fasta from sequences""" with open(out_fa, 'w') as fa_handle: for s, n in itertools.izip(seqs, names): print(">cx{1}-{0}\n{0}".format(s, n), file=fa_handle) return out_fa
python
def get_seqs_fasta(seqs, names, out_fa): """get fasta from sequences""" with open(out_fa, 'w') as fa_handle: for s, n in itertools.izip(seqs, names): print(">cx{1}-{0}\n{0}".format(s, n), file=fa_handle) return out_fa
get fasta from sequences
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/read.py#L138-L143
lpantano/seqcluster
seqcluster/libs/read.py
get_loci_fasta
def get_loci_fasta(loci, out_fa, ref): """get fasta from precursor""" if not find_cmd("bedtools"): raise ValueError("Not bedtools installed") with make_temp_directory() as temp: bed_file = os.path.join(temp, "file.bed") for nc, loci in loci.iteritems(): for l in loci: ...
python
def get_loci_fasta(loci, out_fa, ref): """get fasta from precursor""" if not find_cmd("bedtools"): raise ValueError("Not bedtools installed") with make_temp_directory() as temp: bed_file = os.path.join(temp, "file.bed") for nc, loci in loci.iteritems(): for l in loci: ...
get fasta from precursor
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/read.py#L150-L163
lpantano/seqcluster
seqcluster/libs/read.py
read_alignment
def read_alignment(out_sam, loci, seqs, out_file): """read which seqs map to which loci and return a tab separated file""" hits = defaultdict(list) with open(out_file, "w") as out_handle: samfile = pysam.Samfile(out_sam, "r") for a in samfile.fetch(): if not a.is_unmapped: ...
python
def read_alignment(out_sam, loci, seqs, out_file): """read which seqs map to which loci and return a tab separated file""" hits = defaultdict(list) with open(out_file, "w") as out_handle: samfile = pysam.Samfile(out_sam, "r") for a in samfile.fetch(): if not a.is_unmapped: ...
read which seqs map to which loci and return a tab separated file
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/read.py#L165-L184
lpantano/seqcluster
seqcluster/seqbuster/__init__.py
_download_mirbase
def _download_mirbase(args, version="CURRENT"): """ Download files from mirbase """ if not args.hairpin or not args.mirna: logger.info("Working with version %s" % version) hairpin_fn = op.join(op.abspath(args.out), "hairpin.fa.gz") mirna_fn = op.join(op.abspath(args.out), "miRNA....
python
def _download_mirbase(args, version="CURRENT"): """ Download files from mirbase """ if not args.hairpin or not args.mirna: logger.info("Working with version %s" % version) hairpin_fn = op.join(op.abspath(args.out), "hairpin.fa.gz") mirna_fn = op.join(op.abspath(args.out), "miRNA....
Download files from mirbase
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/__init__.py#L23-L38
lpantano/seqcluster
seqcluster/seqbuster/__init__.py
_make_unique
def _make_unique(name, idx): """Make name unique in case only counts there""" p = re.compile(".[aA-zZ]+_x[0-9]+") if p.match(name): tags = name[1:].split("_x") return ">%s_%s_x%s" % (tags[0], idx, tags[1]) return name.replace("@", ">")
python
def _make_unique(name, idx): """Make name unique in case only counts there""" p = re.compile(".[aA-zZ]+_x[0-9]+") if p.match(name): tags = name[1:].split("_x") return ">%s_%s_x%s" % (tags[0], idx, tags[1]) return name.replace("@", ">")
Make name unique in case only counts there
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/__init__.py#L41-L47
lpantano/seqcluster
seqcluster/seqbuster/__init__.py
_filter_seqs
def _filter_seqs(fn): """Convert names of sequences to unique ids""" out_file = op.splitext(fn)[0] + "_unique.fa" idx = 0 if not file_exists(out_file): with open(out_file, 'w') as out_handle: with open(fn) as in_handle: for line in in_handle: if li...
python
def _filter_seqs(fn): """Convert names of sequences to unique ids""" out_file = op.splitext(fn)[0] + "_unique.fa" idx = 0 if not file_exists(out_file): with open(out_file, 'w') as out_handle: with open(fn) as in_handle: for line in in_handle: if li...
Convert names of sequences to unique ids
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/__init__.py#L50-L69
lpantano/seqcluster
seqcluster/seqbuster/__init__.py
_read_precursor
def _read_precursor(precursor, sps): """ Load precursor file for that species """ hairpin = defaultdict(str) name = None with open(precursor) as in_handle: for line in in_handle: if line.startswith(">"): if hairpin[name]: hairpin[name] = ha...
python
def _read_precursor(precursor, sps): """ Load precursor file for that species """ hairpin = defaultdict(str) name = None with open(precursor) as in_handle: for line in in_handle: if line.startswith(">"): if hairpin[name]: hairpin[name] = ha...
Load precursor file for that species
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/__init__.py#L112-L127
lpantano/seqcluster
seqcluster/seqbuster/__init__.py
_read_gtf
def _read_gtf(gtf): """ Load GTF file with precursor positions on genome """ if not gtf: return gtf db = defaultdict(list) with open(gtf) as in_handle: for line in in_handle: if line.startswith("#"): continue cols = line.strip().split("\t")...
python
def _read_gtf(gtf): """ Load GTF file with precursor positions on genome """ if not gtf: return gtf db = defaultdict(list) with open(gtf) as in_handle: for line in in_handle: if line.startswith("#"): continue cols = line.strip().split("\t")...
Load GTF file with precursor positions on genome
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/__init__.py#L130-L146
lpantano/seqcluster
seqcluster/seqbuster/__init__.py
_coord
def _coord(sequence, start, mirna, precursor, iso): """ Define t5 and t3 isomirs """ dif = abs(mirna[0] - start) if start < mirna[0]: iso.t5 = sequence[:dif].upper() elif start > mirna[0]: iso.t5 = precursor[mirna[0] - 1:mirna[0] - 1 + dif].lower() elif start == mirna[0]: ...
python
def _coord(sequence, start, mirna, precursor, iso): """ Define t5 and t3 isomirs """ dif = abs(mirna[0] - start) if start < mirna[0]: iso.t5 = sequence[:dif].upper() elif start > mirna[0]: iso.t5 = precursor[mirna[0] - 1:mirna[0] - 1 + dif].lower() elif start == mirna[0]: ...
Define t5 and t3 isomirs
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/__init__.py#L149-L180
lpantano/seqcluster
seqcluster/seqbuster/__init__.py
_annotate
def _annotate(reads, mirbase_ref, precursors): """ Using SAM/BAM coordinates, mismatches and realign to annotate isomiRs """ for r in reads: for p in reads[r].precursors: start = reads[r].precursors[p].start + 1 # convert to 1base end = start + len(reads[r].sequence) ...
python
def _annotate(reads, mirbase_ref, precursors): """ Using SAM/BAM coordinates, mismatches and realign to annotate isomiRs """ for r in reads: for p in reads[r].precursors: start = reads[r].precursors[p].start + 1 # convert to 1base end = start + len(reads[r].sequence) ...
Using SAM/BAM coordinates, mismatches and realign to annotate isomiRs
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/__init__.py#L183-L198
lpantano/seqcluster
seqcluster/seqbuster/__init__.py
_realign
def _realign(seq, precursor, start): """ The actual fn that will realign the sequence """ error = set() pattern_addition = [[1, 1, 0], [1, 0, 1], [0, 1, 0], [0, 1, 1], [0, 0, 1], [1, 1, 1]] for pos in range(0, len(seq)): if seq[pos] != precursor[(start + pos)]: error.add(pos)...
python
def _realign(seq, precursor, start): """ The actual fn that will realign the sequence """ error = set() pattern_addition = [[1, 1, 0], [1, 0, 1], [0, 1, 0], [0, 1, 1], [0, 0, 1], [1, 1, 1]] for pos in range(0, len(seq)): if seq[pos] != precursor[(start + pos)]: error.add(pos)...
The actual fn that will realign the sequence
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/__init__.py#L201-L231
lpantano/seqcluster
seqcluster/seqbuster/__init__.py
_clean_hits
def _clean_hits(reads): """ Select only best matches """ new_reads = defaultdict(realign) for r in reads: world = {} sc = 0 for p in reads[r].precursors: world[p] = reads[r].precursors[p].get_score(len(reads[r].sequence)) if sc < world[p]: ...
python
def _clean_hits(reads): """ Select only best matches """ new_reads = defaultdict(realign) for r in reads: world = {} sc = 0 for p in reads[r].precursors: world[p] = reads[r].precursors[p].get_score(len(reads[r].sequence)) if sc < world[p]: ...
Select only best matches
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/__init__.py#L234-L253
lpantano/seqcluster
seqcluster/seqbuster/__init__.py
_read_bam
def _read_bam(bam_fn, precursors): """ read bam file and perform realignment of hits """ mode = "r" if bam_fn.endswith("sam") else "rb" handle = pysam.Samfile(bam_fn, mode) reads = defaultdict(realign) for line in handle: chrom = handle.getrname(line.reference_id) # print("%s...
python
def _read_bam(bam_fn, precursors): """ read bam file and perform realignment of hits """ mode = "r" if bam_fn.endswith("sam") else "rb" handle = pysam.Samfile(bam_fn, mode) reads = defaultdict(realign) for line in handle: chrom = handle.getrname(line.reference_id) # print("%s...
read bam file and perform realignment of hits
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/__init__.py#L271-L291
lpantano/seqcluster
seqcluster/seqbuster/__init__.py
_collapse_fastq
def _collapse_fastq(in_fn): """ collapse reads into unique sequences """ args = argparse.Namespace() args.fastq = in_fn args.minimum = 1 args.out = op.dirname(in_fn) return collapse_fastq(args)
python
def _collapse_fastq(in_fn): """ collapse reads into unique sequences """ args = argparse.Namespace() args.fastq = in_fn args.minimum = 1 args.out = op.dirname(in_fn) return collapse_fastq(args)
collapse reads into unique sequences
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/__init__.py#L294-L302
lpantano/seqcluster
seqcluster/seqbuster/__init__.py
_read_pyMatch
def _read_pyMatch(fn, precursors): """ read pyMatch file and perform realignment of hits """ with open(fn) as handle: reads = defaultdict(realign) for line in handle: query_name, seq, chrom, reference_start, end, mism, add = line.split() reference_start = int(refe...
python
def _read_pyMatch(fn, precursors): """ read pyMatch file and perform realignment of hits """ with open(fn) as handle: reads = defaultdict(realign) for line in handle: query_name, seq, chrom, reference_start, end, mism, add = line.split() reference_start = int(refe...
read pyMatch file and perform realignment of hits
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/__init__.py#L305-L328
lpantano/seqcluster
seqcluster/seqbuster/__init__.py
_parse_mut
def _parse_mut(subs): """ Parse mutation tag from miraligner output """ if subs!="0": subs = [[subs.replace(subs[-2:], ""),subs[-2], subs[-1]]] return subs
python
def _parse_mut(subs): """ Parse mutation tag from miraligner output """ if subs!="0": subs = [[subs.replace(subs[-2:], ""),subs[-2], subs[-1]]] return subs
Parse mutation tag from miraligner output
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/__init__.py#L331-L337
lpantano/seqcluster
seqcluster/seqbuster/__init__.py
_read_miraligner
def _read_miraligner(fn): """Read ouput of miraligner and create compatible output.""" reads = defaultdict(realign) with open(fn) as in_handle: in_handle.next() for line in in_handle: cols = line.strip().split("\t") iso = isomir() query_name, seq = cols[1]...
python
def _read_miraligner(fn): """Read ouput of miraligner and create compatible output.""" reads = defaultdict(realign) with open(fn) as in_handle: in_handle.next() for line in in_handle: cols = line.strip().split("\t") iso = isomir() query_name, seq = cols[1]...
Read ouput of miraligner and create compatible output.
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/__init__.py#L340-L359
lpantano/seqcluster
seqcluster/seqbuster/__init__.py
_cmd_miraligner
def _cmd_miraligner(fn, out_file, species, hairpin, out): """ Run miraligner for miRNA annotation """ tool = _get_miraligner() path_db = op.dirname(op.abspath(hairpin)) cmd = "{tool} -freq -i {fn} -o {out_file} -s {species} -db {path_db} -sub 1 -trim 3 -add 3" if not file_exists(out_file): ...
python
def _cmd_miraligner(fn, out_file, species, hairpin, out): """ Run miraligner for miRNA annotation """ tool = _get_miraligner() path_db = op.dirname(op.abspath(hairpin)) cmd = "{tool} -freq -i {fn} -o {out_file} -s {species} -db {path_db} -sub 1 -trim 3 -add 3" if not file_exists(out_file): ...
Run miraligner for miRNA annotation
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/__init__.py#L362-L373
lpantano/seqcluster
seqcluster/seqbuster/__init__.py
_mirtop
def _mirtop(out_files, hairpin, gff3, species, out): """ Convert miraligner to mirtop format """ args = argparse.Namespace() args.hairpin = hairpin args.sps = species args.gtf = gff3 args.add_extra = True args.files = out_files args.format = "seqbuster" args.out_format = "gff...
python
def _mirtop(out_files, hairpin, gff3, species, out): """ Convert miraligner to mirtop format """ args = argparse.Namespace() args.hairpin = hairpin args.sps = species args.gtf = gff3 args.add_extra = True args.files = out_files args.format = "seqbuster" args.out_format = "gff...
Convert miraligner to mirtop format
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/__init__.py#L376-L389
lpantano/seqcluster
seqcluster/seqbuster/__init__.py
_merge
def _merge(dts): """ merge multiple samples in one matrix """ df = pd.concat(dts) ma = df.pivot(index='isomir', columns='sample', values='counts') ma_mirna = ma ma = ma.fillna(0) ma_mirna['mirna'] = [m.split(":")[0] for m in ma.index.values] ma_mirna = ma_mirna.groupby(['mirna']).su...
python
def _merge(dts): """ merge multiple samples in one matrix """ df = pd.concat(dts) ma = df.pivot(index='isomir', columns='sample', values='counts') ma_mirna = ma ma = ma.fillna(0) ma_mirna['mirna'] = [m.split(":")[0] for m in ma.index.values] ma_mirna = ma_mirna.groupby(['mirna']).su...
merge multiple samples in one matrix
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/__init__.py#L454-L466
lpantano/seqcluster
seqcluster/seqbuster/__init__.py
_create_counts
def _create_counts(out_dts, out_dir): """Summarize results into single files.""" ma, ma_mirna = _merge(out_dts) out_ma = op.join(out_dir, "counts.tsv") out_ma_mirna = op.join(out_dir, "counts_mirna.tsv") ma.to_csv(out_ma, sep="\t") ma_mirna.to_csv(out_ma_mirna, sep="\t") return out_ma_mirna,...
python
def _create_counts(out_dts, out_dir): """Summarize results into single files.""" ma, ma_mirna = _merge(out_dts) out_ma = op.join(out_dir, "counts.tsv") out_ma_mirna = op.join(out_dir, "counts_mirna.tsv") ma.to_csv(out_ma, sep="\t") ma_mirna.to_csv(out_ma_mirna, sep="\t") return out_ma_mirna,...
Summarize results into single files.
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/__init__.py#L469-L476
lpantano/seqcluster
seqcluster/seqbuster/__init__.py
miraligner
def miraligner(args): """ Realign BAM hits to miRBAse to get better accuracy and annotation """ hairpin, mirna = _download_mirbase(args) precursors = _read_precursor(args.hairpin, args.sps) matures = _read_mature(args.mirna, args.sps) gtf = _read_gtf(args.gtf) out_dts = [] out_files ...
python
def miraligner(args): """ Realign BAM hits to miRBAse to get better accuracy and annotation """ hairpin, mirna = _download_mirbase(args) precursors = _read_precursor(args.hairpin, args.sps) matures = _read_mature(args.mirna, args.sps) gtf = _read_gtf(args.gtf) out_dts = [] out_files ...
Realign BAM hits to miRBAse to get better accuracy and annotation
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/__init__.py#L479-L539
lpantano/seqcluster
seqcluster/install.py
chdir
def chdir(new_dir): """ stolen from bcbio. Context manager to temporarily change to a new directory. http://lucentbeing.com/blog/context-managers-and-the-with-statement-in-python/ """ cur_dir = os.getcwd() _mkdir(new_dir) os.chdir(new_dir) try: yield finally: os....
python
def chdir(new_dir): """ stolen from bcbio. Context manager to temporarily change to a new directory. http://lucentbeing.com/blog/context-managers-and-the-with-statement-in-python/ """ cur_dir = os.getcwd() _mkdir(new_dir) os.chdir(new_dir) try: yield finally: os....
stolen from bcbio. Context manager to temporarily change to a new directory. http://lucentbeing.com/blog/context-managers-and-the-with-statement-in-python/
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/install.py#L35-L48
lpantano/seqcluster
seqcluster/install.py
_get_flavor
def _get_flavor(): """ Download flavor from github """ target = op.join("seqcluster", "flavor") url = "https://github.com/lpantano/seqcluster.git" if not os.path.exists(target): # shutil.rmtree("seqcluster") subprocess.check_call(["git", "clone","-b", "flavor", "--single-branch", u...
python
def _get_flavor(): """ Download flavor from github """ target = op.join("seqcluster", "flavor") url = "https://github.com/lpantano/seqcluster.git" if not os.path.exists(target): # shutil.rmtree("seqcluster") subprocess.check_call(["git", "clone","-b", "flavor", "--single-branch", u...
Download flavor from github
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/install.py#L70-L79
lpantano/seqcluster
seqcluster/install.py
_install
def _install(path, args): """ small helper for installation in case outside bcbio """ try: from bcbio import install as bcb except: raise ImportError("It needs bcbio to do the quick installation.") path_flavor = _get_flavor() s = {"fabricrc_overrides": {"system_install": path...
python
def _install(path, args): """ small helper for installation in case outside bcbio """ try: from bcbio import install as bcb except: raise ImportError("It needs bcbio to do the quick installation.") path_flavor = _get_flavor() s = {"fabricrc_overrides": {"system_install": path...
small helper for installation in case outside bcbio
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/install.py#L81-L113
lpantano/seqcluster
seqcluster/install.py
_install_data
def _install_data(data_dir, path_flavor, args): """Upgrade required genome data files in place. """ try: from bcbio import install as bcb except: raise ImportError("It needs bcbio to do the quick installation.") bio_data = op.join(path_flavor, "../biodata.yaml") s = {"flavor": pa...
python
def _install_data(data_dir, path_flavor, args): """Upgrade required genome data files in place. """ try: from bcbio import install as bcb except: raise ImportError("It needs bcbio to do the quick installation.") bio_data = op.join(path_flavor, "../biodata.yaml") s = {"flavor": pa...
Upgrade required genome data files in place.
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/install.py#L115-L141
lpantano/seqcluster
seqcluster/make_predictions.py
predictions
def predictions(args): """ Create predictions of clusters """ logger.info(args) logger.info("reading sequeces") out_file = os.path.abspath(os.path.splitext(args.json)[0] + "_prediction.json") data = load_data(args.json) out_dir = os.path.abspath(safe_dirs(os.path.join(args.out, "predict...
python
def predictions(args): """ Create predictions of clusters """ logger.info(args) logger.info("reading sequeces") out_file = os.path.abspath(os.path.splitext(args.json)[0] + "_prediction.json") data = load_data(args.json) out_dir = os.path.abspath(safe_dirs(os.path.join(args.out, "predict...
Create predictions of clusters
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/make_predictions.py#L11-L29
lpantano/seqcluster
seqcluster/detect/description.py
sort_precursor
def sort_precursor(c, loci): """ Sort loci according to number of sequences mapped there. """ # Original Py 2.7 code #data_loci = map(lambda (x): [x, loci[x].chr, int(loci[x].start), int(loci[x].end), loci[x].strand, len(c.loci2seq[x])], c.loci2seq.keys()) # 2to3 suggested Py 3 rewrite data_...
python
def sort_precursor(c, loci): """ Sort loci according to number of sequences mapped there. """ # Original Py 2.7 code #data_loci = map(lambda (x): [x, loci[x].chr, int(loci[x].start), int(loci[x].end), loci[x].strand, len(c.loci2seq[x])], c.loci2seq.keys()) # 2to3 suggested Py 3 rewrite data_...
Sort loci according to number of sequences mapped there.
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/detect/description.py#L14-L23
lpantano/seqcluster
seqcluster/detect/description.py
best_precursor
def best_precursor(clus, loci): """ Select best precursor asuming size around 100 nt """ data_loci = sort_precursor(clus, loci) current_size = data_loci[0][5] best = 0 for item, locus in enumerate(data_loci): if locus[3] - locus[2] > 70: if locus[5] > current_size * 0.8: ...
python
def best_precursor(clus, loci): """ Select best precursor asuming size around 100 nt """ data_loci = sort_precursor(clus, loci) current_size = data_loci[0][5] best = 0 for item, locus in enumerate(data_loci): if locus[3] - locus[2] > 70: if locus[5] > current_size * 0.8: ...
Select best precursor asuming size around 100 nt
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/detect/description.py#L25-L40
lpantano/seqcluster
scripts/map_SNP_positions.py
_open_file
def _open_file(in_file): """From bcbio code""" _, ext = os.path.splitext(in_file) if ext == ".gz": return gzip.open(in_file, 'rb') if ext in [".fastq", ".fq"]: return open(in_file, 'r') # default to just opening it return open(in_file, "r")
python
def _open_file(in_file): """From bcbio code""" _, ext = os.path.splitext(in_file) if ext == ".gz": return gzip.open(in_file, 'rb') if ext in [".fastq", ".fq"]: return open(in_file, 'r') # default to just opening it return open(in_file, "r")
From bcbio code
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/scripts/map_SNP_positions.py#L8-L16
lpantano/seqcluster
scripts/map_SNP_positions.py
select_snps
def select_snps(mirna, snp, out): """ Use bedtools to intersect coordinates """ with open(out, 'w') as out_handle: print(_create_header(mirna, snp, out), file=out_handle, end="") snp_in_mirna = pybedtools.BedTool(snp).intersect(pybedtools.BedTool(mirna), wo=True) for single in sn...
python
def select_snps(mirna, snp, out): """ Use bedtools to intersect coordinates """ with open(out, 'w') as out_handle: print(_create_header(mirna, snp, out), file=out_handle, end="") snp_in_mirna = pybedtools.BedTool(snp).intersect(pybedtools.BedTool(mirna), wo=True) for single in sn...
Use bedtools to intersect coordinates
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/scripts/map_SNP_positions.py#L58-L78
lpantano/seqcluster
seqcluster/libs/mystats.py
up_threshold
def up_threshold(x, s, p): """function to decide if similarity is below cutoff""" if 1.0 * x/s >= p: return True elif stat.binom_test(x, s, p) > 0.01: return True return False
python
def up_threshold(x, s, p): """function to decide if similarity is below cutoff""" if 1.0 * x/s >= p: return True elif stat.binom_test(x, s, p) > 0.01: return True return False
function to decide if similarity is below cutoff
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/mystats.py#L6-L13
lpantano/seqcluster
seqcluster/libs/peaks.py
_scan
def _scan(positions): """get the region inside the vector with more expression""" scores = [] for start in range(0, len(positions) - 17, 5): end = start = 17 scores.add(_enrichment(positions[start:end], positions[:start], positions[end:]))
python
def _scan(positions): """get the region inside the vector with more expression""" scores = [] for start in range(0, len(positions) - 17, 5): end = start = 17 scores.add(_enrichment(positions[start:end], positions[:start], positions[end:]))
get the region inside the vector with more expression
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/peaks.py#L4-L9
lpantano/seqcluster
seqcluster/make_clusters.py
cluster
def cluster(args): """ Creating clusters """ args = _check_args(args) read_stats_file = op.join(args.dir_out, "read_stats.tsv") if file_exists(read_stats_file): os.remove(read_stats_file) bam_file, seq_obj = _clean_alignment(args) logger.info("Parsing matrix file") seqL, y...
python
def cluster(args): """ Creating clusters """ args = _check_args(args) read_stats_file = op.join(args.dir_out, "read_stats.tsv") if file_exists(read_stats_file): os.remove(read_stats_file) bam_file, seq_obj = _clean_alignment(args) logger.info("Parsing matrix file") seqL, y...
Creating clusters
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/make_clusters.py#L34-L104
lpantano/seqcluster
seqcluster/make_clusters.py
_check_args
def _check_args(args): """ check arguments before starting analysis. """ logger.info("Checking parameters and files") args.dir_out = args.out args.samplename = "pro" global decision_cluster global similar if not os.path.isdir(args.out): logger.warning("the output folder doens...
python
def _check_args(args): """ check arguments before starting analysis. """ logger.info("Checking parameters and files") args.dir_out = args.out args.samplename = "pro" global decision_cluster global similar if not os.path.isdir(args.out): logger.warning("the output folder doens...
check arguments before starting analysis.
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/make_clusters.py#L107-L145