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
bxlab/bx-python
lib/bx_extras/pstat.py
colex
def colex (listoflists,cnums): """ Extracts from listoflists the columns specified in the list 'cnums' (cnums can be an integer, a sequence of integers, or a string-expression that corresponds to a slice operation on the variable x ... e.g., 'x[3:]' will colex columns 3 onward from the listoflists). Usage: colex...
python
def colex (listoflists,cnums): """ Extracts from listoflists the columns specified in the list 'cnums' (cnums can be an integer, a sequence of integers, or a string-expression that corresponds to a slice operation on the variable x ... e.g., 'x[3:]' will colex columns 3 onward from the listoflists). Usage: colex...
Extracts from listoflists the columns specified in the list 'cnums' (cnums can be an integer, a sequence of integers, or a string-expression that corresponds to a slice operation on the variable x ... e.g., 'x[3:]' will colex columns 3 onward from the listoflists). Usage: colex (listoflists,cnums) Returns: a list-of...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L205-L230
bxlab/bx-python
lib/bx_extras/pstat.py
collapse
def collapse (listoflists,keepcols,collapsecols,fcn1=None,fcn2=None,cfcn=None): """ Averages data in collapsecol, keeping all unique items in keepcols (using unique, which keeps unique LISTS of column numbers), retaining the unique sets of values in keepcols, the mean for each. Setting fcn1 and/or fcn2 to point t...
python
def collapse (listoflists,keepcols,collapsecols,fcn1=None,fcn2=None,cfcn=None): """ Averages data in collapsecol, keeping all unique items in keepcols (using unique, which keeps unique LISTS of column numbers), retaining the unique sets of values in keepcols, the mean for each. Setting fcn1 and/or fcn2 to point t...
Averages data in collapsecol, keeping all unique items in keepcols (using unique, which keeps unique LISTS of column numbers), retaining the unique sets of values in keepcols, the mean for each. Setting fcn1 and/or fcn2 to point to a function rather than None (e.g., stats.sterr, len) will append those results (e.g., t...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L233-L308
bxlab/bx-python
lib/bx_extras/pstat.py
flat
def flat(l): """ Returns the flattened version of a '2D' list. List-correlate to the a.flat() method of NumPy arrays. Usage: flat(l) """ newl = [] for i in range(len(l)): for j in range(len(l[i])): newl.append(l[i][j]) return newl
python
def flat(l): """ Returns the flattened version of a '2D' list. List-correlate to the a.flat() method of NumPy arrays. Usage: flat(l) """ newl = [] for i in range(len(l)): for j in range(len(l[i])): newl.append(l[i][j]) return newl
Returns the flattened version of a '2D' list. List-correlate to the a.flat() method of NumPy arrays. Usage: flat(l)
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L326-L337
bxlab/bx-python
lib/bx_extras/pstat.py
linexand
def linexand (listoflists,columnlist,valuelist): """ Returns the rows of a list of lists where col (from columnlist) = val (from valuelist) for EVERY pair of values (columnlist[i],valuelists[i]). len(columnlist) must equal len(valuelist). Usage: linexand (listoflists,columnlist,valuelist) Returns: the rows of li...
python
def linexand (listoflists,columnlist,valuelist): """ Returns the rows of a list of lists where col (from columnlist) = val (from valuelist) for EVERY pair of values (columnlist[i],valuelists[i]). len(columnlist) must equal len(valuelist). Usage: linexand (listoflists,columnlist,valuelist) Returns: the rows of li...
Returns the rows of a list of lists where col (from columnlist) = val (from valuelist) for EVERY pair of values (columnlist[i],valuelists[i]). len(columnlist) must equal len(valuelist). Usage: linexand (listoflists,columnlist,valuelist) Returns: the rows of listoflists where columnlist[i]=valuelist[i] for ALL i
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L340-L363
bxlab/bx-python
lib/bx_extras/pstat.py
linedelimited
def linedelimited (inlist,delimiter): """ Returns a string composed of elements in inlist, with each element separated by 'delimiter.' Used by function writedelimited. Use '\t' for tab-delimiting. Usage: linedelimited (inlist,delimiter) """ outstr = '' for item in inlist: if type(item) != Strin...
python
def linedelimited (inlist,delimiter): """ Returns a string composed of elements in inlist, with each element separated by 'delimiter.' Used by function writedelimited. Use '\t' for tab-delimiting. Usage: linedelimited (inlist,delimiter) """ outstr = '' for item in inlist: if type(item) != Strin...
Returns a string composed of elements in inlist, with each element separated by 'delimiter.' Used by function writedelimited. Use '\t' for tab-delimiting. Usage: linedelimited (inlist,delimiter)
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L396-L410
bxlab/bx-python
lib/bx_extras/pstat.py
lineincols
def lineincols (inlist,colsize): """ Returns a string composed of elements in inlist, with each element right-aligned in columns of (fixed) colsize. Usage: lineincols (inlist,colsize) where colsize is an integer """ outstr = '' for item in inlist: if type(item) != StringType: item =...
python
def lineincols (inlist,colsize): """ Returns a string composed of elements in inlist, with each element right-aligned in columns of (fixed) colsize. Usage: lineincols (inlist,colsize) where colsize is an integer """ outstr = '' for item in inlist: if type(item) != StringType: item =...
Returns a string composed of elements in inlist, with each element right-aligned in columns of (fixed) colsize. Usage: lineincols (inlist,colsize) where colsize is an integer
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L413-L431
bxlab/bx-python
lib/bx_extras/pstat.py
lineincustcols
def lineincustcols (inlist,colsizes): """ Returns a string composed of elements in inlist, with each element right-aligned in a column of width specified by a sequence colsizes. The length of colsizes must be greater than or equal to the number of columns in inlist. Usage: lineincustcols (inlist,colsizes) Retur...
python
def lineincustcols (inlist,colsizes): """ Returns a string composed of elements in inlist, with each element right-aligned in a column of width specified by a sequence colsizes. The length of colsizes must be greater than or equal to the number of columns in inlist. Usage: lineincustcols (inlist,colsizes) Retur...
Returns a string composed of elements in inlist, with each element right-aligned in a column of width specified by a sequence colsizes. The length of colsizes must be greater than or equal to the number of columns in inlist. Usage: lineincustcols (inlist,colsizes) Returns: formatted string created from inlist
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L434-L457
bxlab/bx-python
lib/bx_extras/pstat.py
list2string
def list2string (inlist,delimit=' '): """ Converts a 1D list to a single long string for file output, using the string.join function. Usage: list2string (inlist,delimit=' ') Returns: the string created from inlist """ stringlist = [makestr(_) for _ in inlist] return string.join(stringlist,delimit)
python
def list2string (inlist,delimit=' '): """ Converts a 1D list to a single long string for file output, using the string.join function. Usage: list2string (inlist,delimit=' ') Returns: the string created from inlist """ stringlist = [makestr(_) for _ in inlist] return string.join(stringlist,delimit)
Converts a 1D list to a single long string for file output, using the string.join function. Usage: list2string (inlist,delimit=' ') Returns: the string created from inlist
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L460-L469
bxlab/bx-python
lib/bx_extras/pstat.py
printcc
def printcc (lst,extra=2): """ Prints a list of lists in columns, customized by the max size of items within the columns (max size of items in col, plus 'extra' number of spaces). Use 'dashes' or '\\n' in the list-of-lists to print dashes or blank lines, respectively. Usage: printcc (lst,extra=2) Returns: None "...
python
def printcc (lst,extra=2): """ Prints a list of lists in columns, customized by the max size of items within the columns (max size of items in col, plus 'extra' number of spaces). Use 'dashes' or '\\n' in the list-of-lists to print dashes or blank lines, respectively. Usage: printcc (lst,extra=2) Returns: None "...
Prints a list of lists in columns, customized by the max size of items within the columns (max size of items in col, plus 'extra' number of spaces). Use 'dashes' or '\\n' in the list-of-lists to print dashes or blank lines, respectively. Usage: printcc (lst,extra=2) Returns: None
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L492-L527
bxlab/bx-python
lib/bx_extras/pstat.py
pl
def pl (listoflists): """ Prints a list of lists, 1 list (row) at a time. Usage: pl(listoflists) Returns: None """ for row in listoflists: if row[-1] == '\n': print(row, end=' ') else: print(row) return None
python
def pl (listoflists): """ Prints a list of lists, 1 list (row) at a time. Usage: pl(listoflists) Returns: None """ for row in listoflists: if row[-1] == '\n': print(row, end=' ') else: print(row) return None
Prints a list of lists, 1 list (row) at a time. Usage: pl(listoflists) Returns: None
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L543-L555
bxlab/bx-python
lib/bx_extras/pstat.py
replace
def replace (inlst,oldval,newval): """ Replaces all occurrences of 'oldval' with 'newval', recursively. Usage: replace (inlst,oldval,newval) """ lst = inlst*1 for i in range(len(lst)): if type(lst[i]) not in [ListType,TupleType]: if lst[i]==oldval: lst[i]=newval else: ...
python
def replace (inlst,oldval,newval): """ Replaces all occurrences of 'oldval' with 'newval', recursively. Usage: replace (inlst,oldval,newval) """ lst = inlst*1 for i in range(len(lst)): if type(lst[i]) not in [ListType,TupleType]: if lst[i]==oldval: lst[i]=newval else: ...
Replaces all occurrences of 'oldval' with 'newval', recursively. Usage: replace (inlst,oldval,newval)
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L564-L576
bxlab/bx-python
lib/bx_extras/pstat.py
recode
def recode (inlist,listmap,cols=None): """ Changes the values in a list to a new set of values (useful when you need to recode data from (e.g.) strings to numbers. cols defaults to None (meaning all columns are recoded). Usage: recode (inlist,listmap,cols=None) cols=recode cols, listmap=2D list Returns: inlist...
python
def recode (inlist,listmap,cols=None): """ Changes the values in a list to a new set of values (useful when you need to recode data from (e.g.) strings to numbers. cols defaults to None (meaning all columns are recoded). Usage: recode (inlist,listmap,cols=None) cols=recode cols, listmap=2D list Returns: inlist...
Changes the values in a list to a new set of values (useful when you need to recode data from (e.g.) strings to numbers. cols defaults to None (meaning all columns are recoded). Usage: recode (inlist,listmap,cols=None) cols=recode cols, listmap=2D list Returns: inlist with the appropriate values replaced with new ...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L579-L607
bxlab/bx-python
lib/bx_extras/pstat.py
roundlist
def roundlist (inlist,digits): """ Goes through each element in a 1D or 2D inlist, and applies the following function to all elements of FloatType ... round(element,digits). Usage: roundlist(inlist,digits) Returns: list with rounded floats """ if type(inlist[0]) in [IntType, FloatType]: inlist = [inl...
python
def roundlist (inlist,digits): """ Goes through each element in a 1D or 2D inlist, and applies the following function to all elements of FloatType ... round(element,digits). Usage: roundlist(inlist,digits) Returns: list with rounded floats """ if type(inlist[0]) in [IntType, FloatType]: inlist = [inl...
Goes through each element in a 1D or 2D inlist, and applies the following function to all elements of FloatType ... round(element,digits). Usage: roundlist(inlist,digits) Returns: list with rounded floats
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L624-L639
bxlab/bx-python
lib/bx_extras/pstat.py
sortby
def sortby(listoflists,sortcols): """ Sorts a list of lists on the column(s) specified in the sequence sortcols. Usage: sortby(listoflists,sortcols) Returns: sorted list, unchanged column ordering """ newlist = abut(colex(listoflists,sortcols),listoflists) newlist.sort() try: numcols = len(so...
python
def sortby(listoflists,sortcols): """ Sorts a list of lists on the column(s) specified in the sequence sortcols. Usage: sortby(listoflists,sortcols) Returns: sorted list, unchanged column ordering """ newlist = abut(colex(listoflists,sortcols),listoflists) newlist.sort() try: numcols = len(so...
Sorts a list of lists on the column(s) specified in the sequence sortcols. Usage: sortby(listoflists,sortcols) Returns: sorted list, unchanged column ordering
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L642-L658
bxlab/bx-python
lib/bx_extras/pstat.py
unique
def unique (inlist): """ Returns all unique items in the passed list. If the a list-of-lists is passed, unique LISTS are found (i.e., items in the first dimension are compared). Usage: unique (inlist) Returns: the unique elements (or rows) in inlist """ uniques = [] for item in inlist: if item n...
python
def unique (inlist): """ Returns all unique items in the passed list. If the a list-of-lists is passed, unique LISTS are found (i.e., items in the first dimension are compared). Usage: unique (inlist) Returns: the unique elements (or rows) in inlist """ uniques = [] for item in inlist: if item n...
Returns all unique items in the passed list. If the a list-of-lists is passed, unique LISTS are found (i.e., items in the first dimension are compared). Usage: unique (inlist) Returns: the unique elements (or rows) in inlist
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L661-L674
bxlab/bx-python
lib/bx_extras/pstat.py
duplicates
def duplicates(inlist): """ Returns duplicate items in the FIRST dimension of the passed list. Usage: duplicates (inlist) """ dups = [] for i in range(len(inlist)): if inlist[i] in inlist[i+1:]: dups.append(inlist[i]) return dups
python
def duplicates(inlist): """ Returns duplicate items in the FIRST dimension of the passed list. Usage: duplicates (inlist) """ dups = [] for i in range(len(inlist)): if inlist[i] in inlist[i+1:]: dups.append(inlist[i]) return dups
Returns duplicate items in the FIRST dimension of the passed list. Usage: duplicates (inlist)
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L676-L686
bxlab/bx-python
lib/bx_extras/pstat.py
nonrepeats
def nonrepeats(inlist): """ Returns items that are NOT duplicated in the first dim of the passed list. Usage: nonrepeats (inlist) """ nonrepeats = [] for i in range(len(inlist)): if inlist.count(inlist[i]) == 1: nonrepeats.append(inlist[i]) return nonrepeats
python
def nonrepeats(inlist): """ Returns items that are NOT duplicated in the first dim of the passed list. Usage: nonrepeats (inlist) """ nonrepeats = [] for i in range(len(inlist)): if inlist.count(inlist[i]) == 1: nonrepeats.append(inlist[i]) return nonrepeats
Returns items that are NOT duplicated in the first dim of the passed list. Usage: nonrepeats (inlist)
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L689-L699
bxlab/bx-python
lib/bx_extras/stats.py
lgeometricmean
def lgeometricmean (inlist): """ Calculates the geometric mean of the values in the passed list. That is: n-th root of (x1 * x2 * ... * xn). Assumes a '1D' list. Usage: lgeometricmean(inlist) """ mult = 1.0 one_over_n = 1.0/len(inlist) for item in inlist: mult = mult * pow(item,one_over_n) ...
python
def lgeometricmean (inlist): """ Calculates the geometric mean of the values in the passed list. That is: n-th root of (x1 * x2 * ... * xn). Assumes a '1D' list. Usage: lgeometricmean(inlist) """ mult = 1.0 one_over_n = 1.0/len(inlist) for item in inlist: mult = mult * pow(item,one_over_n) ...
Calculates the geometric mean of the values in the passed list. That is: n-th root of (x1 * x2 * ... * xn). Assumes a '1D' list. Usage: lgeometricmean(inlist)
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L271-L282
bxlab/bx-python
lib/bx_extras/stats.py
lharmonicmean
def lharmonicmean (inlist): """ Calculates the harmonic mean of the values in the passed list. That is: n / (1/x1 + 1/x2 + ... + 1/xn). Assumes a '1D' list. Usage: lharmonicmean(inlist) """ sum = 0 for item in inlist: sum = sum + 1.0/item return len(inlist) / sum
python
def lharmonicmean (inlist): """ Calculates the harmonic mean of the values in the passed list. That is: n / (1/x1 + 1/x2 + ... + 1/xn). Assumes a '1D' list. Usage: lharmonicmean(inlist) """ sum = 0 for item in inlist: sum = sum + 1.0/item return len(inlist) / sum
Calculates the harmonic mean of the values in the passed list. That is: n / (1/x1 + 1/x2 + ... + 1/xn). Assumes a '1D' list. Usage: lharmonicmean(inlist)
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L285-L295
bxlab/bx-python
lib/bx_extras/stats.py
lmean
def lmean (inlist): """ Returns the arithematic mean of the values in the passed list. Assumes a '1D' list, but will function on the 1st dim of an array(!). Usage: lmean(inlist) """ sum = 0 for item in inlist: sum = sum + item return sum/float(len(inlist))
python
def lmean (inlist): """ Returns the arithematic mean of the values in the passed list. Assumes a '1D' list, but will function on the 1st dim of an array(!). Usage: lmean(inlist) """ sum = 0 for item in inlist: sum = sum + item return sum/float(len(inlist))
Returns the arithematic mean of the values in the passed list. Assumes a '1D' list, but will function on the 1st dim of an array(!). Usage: lmean(inlist)
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L298-L308
bxlab/bx-python
lib/bx_extras/stats.py
lmedian
def lmedian (inlist,numbins=1000): """ Returns the computed median value of a list of numbers, given the number of bins to use for the histogram (more bins brings the computed value closer to the median score, default number of bins = 1000). See G.W. Heiman's Basic Stats (1st Edition), or CRC Probability & Statist...
python
def lmedian (inlist,numbins=1000): """ Returns the computed median value of a list of numbers, given the number of bins to use for the histogram (more bins brings the computed value closer to the median score, default number of bins = 1000). See G.W. Heiman's Basic Stats (1st Edition), or CRC Probability & Statist...
Returns the computed median value of a list of numbers, given the number of bins to use for the histogram (more bins brings the computed value closer to the median score, default number of bins = 1000). See G.W. Heiman's Basic Stats (1st Edition), or CRC Probability & Statistics. Usage: lmedian (inlist, numbins=100...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L311-L330
bxlab/bx-python
lib/bx_extras/stats.py
litemfreq
def litemfreq(inlist): """ Returns a list of pairs. Each pair consists of one of the scores in inlist and it's frequency count. Assumes a 1D list is passed. Usage: litemfreq(inlist) Returns: a 2D frequency table (col [0:n-1]=scores, col n=frequencies) """ scores = pstat.unique(inlist) scores.sort() ...
python
def litemfreq(inlist): """ Returns a list of pairs. Each pair consists of one of the scores in inlist and it's frequency count. Assumes a 1D list is passed. Usage: litemfreq(inlist) Returns: a 2D frequency table (col [0:n-1]=scores, col n=frequencies) """ scores = pstat.unique(inlist) scores.sort() ...
Returns a list of pairs. Each pair consists of one of the scores in inlist and it's frequency count. Assumes a 1D list is passed. Usage: litemfreq(inlist) Returns: a 2D frequency table (col [0:n-1]=scores, col n=frequencies)
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L454-L467
bxlab/bx-python
lib/bx_extras/stats.py
lhistogram
def lhistogram (inlist,numbins=10,defaultreallimits=None,printextras=0): """ Returns (i) a list of histogram bin counts, (ii) the smallest value of the histogram binning, and (iii) the bin width (the last 2 are not necessarily integers). Default number of bins is 10. If no sequence object is given for defaultreal...
python
def lhistogram (inlist,numbins=10,defaultreallimits=None,printextras=0): """ Returns (i) a list of histogram bin counts, (ii) the smallest value of the histogram binning, and (iii) the bin width (the last 2 are not necessarily integers). Default number of bins is 10. If no sequence object is given for defaultreal...
Returns (i) a list of histogram bin counts, (ii) the smallest value of the histogram binning, and (iii) the bin width (the last 2 are not necessarily integers). Default number of bins is 10. If no sequence object is given for defaultreallimits, the routine picks (usually non-pretty) bins spanning all the numbers in t...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L505-L541
bxlab/bx-python
lib/bx_extras/stats.py
lsem
def lsem (inlist): """ Returns the estimated standard error of the mean (sx-bar) of the values in the passed list. sem = stdev / sqrt(n) Usage: lsem(inlist) """ sd = stdev(inlist) n = len(inlist) return sd/math.sqrt(n)
python
def lsem (inlist): """ Returns the estimated standard error of the mean (sx-bar) of the values in the passed list. sem = stdev / sqrt(n) Usage: lsem(inlist) """ sd = stdev(inlist) n = len(inlist) return sd/math.sqrt(n)
Returns the estimated standard error of the mean (sx-bar) of the values in the passed list. sem = stdev / sqrt(n) Usage: lsem(inlist)
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L669-L678
bxlab/bx-python
lib/bx_extras/stats.py
lz
def lz (inlist, score): """ Returns the z-score for a given input score, given that score and the list from which that score came. Not appropriate for population calculations. Usage: lz(inlist, score) """ z = (score-mean(inlist))/samplestdev(inlist) return z
python
def lz (inlist, score): """ Returns the z-score for a given input score, given that score and the list from which that score came. Not appropriate for population calculations. Usage: lz(inlist, score) """ z = (score-mean(inlist))/samplestdev(inlist) return z
Returns the z-score for a given input score, given that score and the list from which that score came. Not appropriate for population calculations. Usage: lz(inlist, score)
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L681-L689
bxlab/bx-python
lib/bx_extras/stats.py
lzs
def lzs (inlist): """ Returns a list of z-scores, one for each score in the passed list. Usage: lzs(inlist) """ zscores = [] for item in inlist: zscores.append(z(inlist,item)) return zscores
python
def lzs (inlist): """ Returns a list of z-scores, one for each score in the passed list. Usage: lzs(inlist) """ zscores = [] for item in inlist: zscores.append(z(inlist,item)) return zscores
Returns a list of z-scores, one for each score in the passed list. Usage: lzs(inlist)
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L692-L701
bxlab/bx-python
lib/bx_extras/stats.py
ltrimboth
def ltrimboth (l,proportiontocut): """ Slices off the passed proportion of items from BOTH ends of the passed list (i.e., with proportiontocut=0.1, slices 'leftmost' 10% AND 'rightmost' 10% of scores. Assumes list is sorted by magnitude. Slices off LESS if proportion results in a non-integer slice index (i.e., co...
python
def ltrimboth (l,proportiontocut): """ Slices off the passed proportion of items from BOTH ends of the passed list (i.e., with proportiontocut=0.1, slices 'leftmost' 10% AND 'rightmost' 10% of scores. Assumes list is sorted by magnitude. Slices off LESS if proportion results in a non-integer slice index (i.e., co...
Slices off the passed proportion of items from BOTH ends of the passed list (i.e., with proportiontocut=0.1, slices 'leftmost' 10% AND 'rightmost' 10% of scores. Assumes list is sorted by magnitude. Slices off LESS if proportion results in a non-integer slice index (i.e., conservatively slices off proportiontocut). ...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L708-L721
bxlab/bx-python
lib/bx_extras/stats.py
ltrim1
def ltrim1 (l,proportiontocut,tail='right'): """ Slices off the passed proportion of items from ONE end of the passed list (i.e., if proportiontocut=0.1, slices off 'leftmost' or 'rightmost' 10% of scores). Slices off LESS if proportion results in a non-integer slice index (i.e., conservatively slices off proporti...
python
def ltrim1 (l,proportiontocut,tail='right'): """ Slices off the passed proportion of items from ONE end of the passed list (i.e., if proportiontocut=0.1, slices off 'leftmost' or 'rightmost' 10% of scores). Slices off LESS if proportion results in a non-integer slice index (i.e., conservatively slices off proporti...
Slices off the passed proportion of items from ONE end of the passed list (i.e., if proportiontocut=0.1, slices off 'leftmost' or 'rightmost' 10% of scores). Slices off LESS if proportion results in a non-integer slice index (i.e., conservatively slices off proportiontocut). Usage: ltrim1 (l,proportiontocut,tail='r...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L724-L740
bxlab/bx-python
lib/bx_extras/stats.py
lpearsonr
def lpearsonr(x,y): """ Calculates a Pearson correlation coefficient and the associated probability value. Taken from Heiman's Basic Statistics for the Behav. Sci (2nd), p.195. Usage: lpearsonr(x,y) where x and y are equal-length lists Returns: Pearson's r value, two-tailed p-value """ TINY = 1.0e-30 ...
python
def lpearsonr(x,y): """ Calculates a Pearson correlation coefficient and the associated probability value. Taken from Heiman's Basic Statistics for the Behav. Sci (2nd), p.195. Usage: lpearsonr(x,y) where x and y are equal-length lists Returns: Pearson's r value, two-tailed p-value """ TINY = 1.0e-30 ...
Calculates a Pearson correlation coefficient and the associated probability value. Taken from Heiman's Basic Statistics for the Behav. Sci (2nd), p.195. Usage: lpearsonr(x,y) where x and y are equal-length lists Returns: Pearson's r value, two-tailed p-value
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L811-L834
bxlab/bx-python
lib/bx_extras/stats.py
lspearmanr
def lspearmanr(x,y): """ Calculates a Spearman rank-order correlation coefficient. Taken from Heiman's Basic Statistics for the Behav. Sci (1st), p.192. Usage: lspearmanr(x,y) where x and y are equal-length lists Returns: Spearman's r, two-tailed p-value """ TINY = 1e-30 if len(x) != len(y): ...
python
def lspearmanr(x,y): """ Calculates a Spearman rank-order correlation coefficient. Taken from Heiman's Basic Statistics for the Behav. Sci (1st), p.192. Usage: lspearmanr(x,y) where x and y are equal-length lists Returns: Spearman's r, two-tailed p-value """ TINY = 1e-30 if len(x) != len(y): ...
Calculates a Spearman rank-order correlation coefficient. Taken from Heiman's Basic Statistics for the Behav. Sci (1st), p.192. Usage: lspearmanr(x,y) where x and y are equal-length lists Returns: Spearman's r, two-tailed p-value
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L837-L858
bxlab/bx-python
lib/bx_extras/stats.py
lpointbiserialr
def lpointbiserialr(x,y): """ Calculates a point-biserial correlation coefficient and the associated probability value. Taken from Heiman's Basic Statistics for the Behav. Sci (1st), p.194. Usage: lpointbiserialr(x,y) where x,y are equal-length lists Returns: Point-biserial r, two-tailed p-value """ TI...
python
def lpointbiserialr(x,y): """ Calculates a point-biserial correlation coefficient and the associated probability value. Taken from Heiman's Basic Statistics for the Behav. Sci (1st), p.194. Usage: lpointbiserialr(x,y) where x,y are equal-length lists Returns: Point-biserial r, two-tailed p-value """ TI...
Calculates a point-biserial correlation coefficient and the associated probability value. Taken from Heiman's Basic Statistics for the Behav. Sci (1st), p.194. Usage: lpointbiserialr(x,y) where x,y are equal-length lists Returns: Point-biserial r, two-tailed p-value
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L861-L890
bxlab/bx-python
lib/bx_extras/stats.py
lkendalltau
def lkendalltau(x,y): """ Calculates Kendall's tau ... correlation of ordinal data. Adapted from function kendl1 in Numerical Recipies. Needs good test-routine.@@@ Usage: lkendalltau(x,y) Returns: Kendall's tau, two-tailed p-value """ n1 = 0 n2 = 0 iss = 0 for j in range(len(x)-1): for ...
python
def lkendalltau(x,y): """ Calculates Kendall's tau ... correlation of ordinal data. Adapted from function kendl1 in Numerical Recipies. Needs good test-routine.@@@ Usage: lkendalltau(x,y) Returns: Kendall's tau, two-tailed p-value """ n1 = 0 n2 = 0 iss = 0 for j in range(len(x)-1): for ...
Calculates Kendall's tau ... correlation of ordinal data. Adapted from function kendl1 in Numerical Recipies. Needs good test-routine.@@@ Usage: lkendalltau(x,y) Returns: Kendall's tau, two-tailed p-value
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L893-L925
bxlab/bx-python
lib/bx_extras/stats.py
llinregress
def llinregress(x,y): """ Calculates a regression line on x,y pairs. Usage: llinregress(x,y) x,y are equal-length lists of x-y coordinates Returns: slope, intercept, r, two-tailed prob, sterr-of-estimate """ TINY = 1.0e-20 if len(x) != len(y): raise ValueError('Input values not paired in l...
python
def llinregress(x,y): """ Calculates a regression line on x,y pairs. Usage: llinregress(x,y) x,y are equal-length lists of x-y coordinates Returns: slope, intercept, r, two-tailed prob, sterr-of-estimate """ TINY = 1.0e-20 if len(x) != len(y): raise ValueError('Input values not paired in l...
Calculates a regression line on x,y pairs. Usage: llinregress(x,y) x,y are equal-length lists of x-y coordinates Returns: slope, intercept, r, two-tailed prob, sterr-of-estimate
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L928-L953
bxlab/bx-python
lib/bx_extras/stats.py
lchisquare
def lchisquare(f_obs,f_exp=None): """ Calculates a one-way chi square for list of observed frequencies and returns the result. If no expected frequencies are given, the total N is assumed to be equally distributed across all groups. Usage: lchisquare(f_obs, f_exp=None) f_obs = list of observed cell freq. Retu...
python
def lchisquare(f_obs,f_exp=None): """ Calculates a one-way chi square for list of observed frequencies and returns the result. If no expected frequencies are given, the total N is assumed to be equally distributed across all groups. Usage: lchisquare(f_obs, f_exp=None) f_obs = list of observed cell freq. Retu...
Calculates a one-way chi square for list of observed frequencies and returns the result. If no expected frequencies are given, the total N is assumed to be equally distributed across all groups. Usage: lchisquare(f_obs, f_exp=None) f_obs = list of observed cell freq. Returns: chisquare-statistic, associated p-val...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1054-L1069
bxlab/bx-python
lib/bx_extras/stats.py
lks_2samp
def lks_2samp (data1,data2): """ Computes the Kolmogorov-Smirnof statistic on 2 samples. From Numerical Recipies in C, page 493. Usage: lks_2samp(data1,data2) data1&2 are lists of values for 2 conditions Returns: KS D-value, associated p-value """ j1 = 0 j2 = 0 fn1 = 0.0 fn2 = 0.0 n1 = len...
python
def lks_2samp (data1,data2): """ Computes the Kolmogorov-Smirnof statistic on 2 samples. From Numerical Recipies in C, page 493. Usage: lks_2samp(data1,data2) data1&2 are lists of values for 2 conditions Returns: KS D-value, associated p-value """ j1 = 0 j2 = 0 fn1 = 0.0 fn2 = 0.0 n1 = len...
Computes the Kolmogorov-Smirnof statistic on 2 samples. From Numerical Recipies in C, page 493. Usage: lks_2samp(data1,data2) data1&2 are lists of values for 2 conditions Returns: KS D-value, associated p-value
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1072-L1108
bxlab/bx-python
lib/bx_extras/stats.py
lmannwhitneyu
def lmannwhitneyu(x,y): """ Calculates a Mann-Whitney U statistic on the provided scores and returns the result. Use only when the n in each condition is < 20 and you have 2 independent samples of ranks. NOTE: Mann-Whitney U is significant if the u-obtained is LESS THAN or equal to the critical value of U found i...
python
def lmannwhitneyu(x,y): """ Calculates a Mann-Whitney U statistic on the provided scores and returns the result. Use only when the n in each condition is < 20 and you have 2 independent samples of ranks. NOTE: Mann-Whitney U is significant if the u-obtained is LESS THAN or equal to the critical value of U found i...
Calculates a Mann-Whitney U statistic on the provided scores and returns the result. Use only when the n in each condition is < 20 and you have 2 independent samples of ranks. NOTE: Mann-Whitney U is significant if the u-obtained is LESS THAN or equal to the critical value of U found in the tables. Equivalent to Kru...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1111-L1137
bxlab/bx-python
lib/bx_extras/stats.py
ltiecorrect
def ltiecorrect(rankvals): """ Corrects for ties in Mann Whitney U and Kruskal Wallis H tests. See Siegel, S. (1956) Nonparametric Statistics for the Behavioral Sciences. New York: McGraw-Hill. Code adapted from |Stat rankind.c code. Usage: ltiecorrect(rankvals) Returns: T correction factor for U or H """ ...
python
def ltiecorrect(rankvals): """ Corrects for ties in Mann Whitney U and Kruskal Wallis H tests. See Siegel, S. (1956) Nonparametric Statistics for the Behavioral Sciences. New York: McGraw-Hill. Code adapted from |Stat rankind.c code. Usage: ltiecorrect(rankvals) Returns: T correction factor for U or H """ ...
Corrects for ties in Mann Whitney U and Kruskal Wallis H tests. See Siegel, S. (1956) Nonparametric Statistics for the Behavioral Sciences. New York: McGraw-Hill. Code adapted from |Stat rankind.c code. Usage: ltiecorrect(rankvals) Returns: T correction factor for U or H
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1140-L1162
bxlab/bx-python
lib/bx_extras/stats.py
lranksums
def lranksums(x,y): """ Calculates the rank sums statistic on the provided scores and returns the result. Use only when the n in each condition is > 20 and you have 2 independent samples of ranks. Usage: lranksums(x,y) Returns: a z-statistic, two-tailed p-value """ n1 = len(x) n2 = len(y) alldata = ...
python
def lranksums(x,y): """ Calculates the rank sums statistic on the provided scores and returns the result. Use only when the n in each condition is > 20 and you have 2 independent samples of ranks. Usage: lranksums(x,y) Returns: a z-statistic, two-tailed p-value """ n1 = len(x) n2 = len(y) alldata = ...
Calculates the rank sums statistic on the provided scores and returns the result. Use only when the n in each condition is > 20 and you have 2 independent samples of ranks. Usage: lranksums(x,y) Returns: a z-statistic, two-tailed p-value
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1165-L1184
bxlab/bx-python
lib/bx_extras/stats.py
lkruskalwallish
def lkruskalwallish(*args): """ The Kruskal-Wallis H-test is a non-parametric ANOVA for 3 or more groups, requiring at least 5 subjects in each group. This function calculates the Kruskal-Wallis H-test for 3 or more independent samples and returns the result. Usage: lkruskalwallish(*args) Returns: H-statistic...
python
def lkruskalwallish(*args): """ The Kruskal-Wallis H-test is a non-parametric ANOVA for 3 or more groups, requiring at least 5 subjects in each group. This function calculates the Kruskal-Wallis H-test for 3 or more independent samples and returns the result. Usage: lkruskalwallish(*args) Returns: H-statistic...
The Kruskal-Wallis H-test is a non-parametric ANOVA for 3 or more groups, requiring at least 5 subjects in each group. This function calculates the Kruskal-Wallis H-test for 3 or more independent samples and returns the result. Usage: lkruskalwallish(*args) Returns: H-statistic (corrected for ties), associated p-...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1220-L1252
bxlab/bx-python
lib/bx_extras/stats.py
lfriedmanchisquare
def lfriedmanchisquare(*args): """ Friedman Chi-Square is a non-parametric, one-way within-subjects ANOVA. This function calculates the Friedman Chi-square test for repeated measures and returns the result, along with the associated probability value. It assumes 3 or more repeated measures. Only 3 levels require...
python
def lfriedmanchisquare(*args): """ Friedman Chi-Square is a non-parametric, one-way within-subjects ANOVA. This function calculates the Friedman Chi-square test for repeated measures and returns the result, along with the associated probability value. It assumes 3 or more repeated measures. Only 3 levels require...
Friedman Chi-Square is a non-parametric, one-way within-subjects ANOVA. This function calculates the Friedman Chi-square test for repeated measures and returns the result, along with the associated probability value. It assumes 3 or more repeated measures. Only 3 levels requires a minimum of 10 subjects in the study...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1255-L1278
bxlab/bx-python
lib/bx_extras/stats.py
lchisqprob
def lchisqprob(chisq,df): """ Returns the (1-tailed) probability value associated with the provided chi-square value and df. Adapted from chisq.c in Gary Perlman's |Stat. Usage: lchisqprob(chisq,df) """ BIG = 20.0 def ex(x): BIG = 20.0 if x < -BIG: return 0.0 else: ...
python
def lchisqprob(chisq,df): """ Returns the (1-tailed) probability value associated with the provided chi-square value and df. Adapted from chisq.c in Gary Perlman's |Stat. Usage: lchisqprob(chisq,df) """ BIG = 20.0 def ex(x): BIG = 20.0 if x < -BIG: return 0.0 else: ...
Returns the (1-tailed) probability value associated with the provided chi-square value and df. Adapted from chisq.c in Gary Perlman's |Stat. Usage: lchisqprob(chisq,df)
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1285-L1342
bxlab/bx-python
lib/bx_extras/stats.py
lerfcc
def lerfcc(x): """ Returns the complementary error function erfc(x) with fractional error everywhere less than 1.2e-7. Adapted from Numerical Recipies. Usage: lerfcc(x) """ z = abs(x) t = 1.0 / (1.0+0.5*z) ans = t * math.exp(-z*z-1.26551223 + t*(1.00002368+t*(0.37409196+t*(0.09678418+t*(-0.18628806+...
python
def lerfcc(x): """ Returns the complementary error function erfc(x) with fractional error everywhere less than 1.2e-7. Adapted from Numerical Recipies. Usage: lerfcc(x) """ z = abs(x) t = 1.0 / (1.0+0.5*z) ans = t * math.exp(-z*z-1.26551223 + t*(1.00002368+t*(0.37409196+t*(0.09678418+t*(-0.18628806+...
Returns the complementary error function erfc(x) with fractional error everywhere less than 1.2e-7. Adapted from Numerical Recipies. Usage: lerfcc(x)
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1345-L1358
bxlab/bx-python
lib/bx_extras/stats.py
lzprob
def lzprob(z): """ Returns the area under the normal curve 'to the left of' the given z value. Thus, for z<0, zprob(z) = 1-tail probability for z>0, 1.0-zprob(z) = 1-tail probability for any z, 2.0*(1.0-zprob(abs(z))) = 2-tail probability Adapted from z.c in Gary Perlman's |Stat. Usage: lzprob(z) ""...
python
def lzprob(z): """ Returns the area under the normal curve 'to the left of' the given z value. Thus, for z<0, zprob(z) = 1-tail probability for z>0, 1.0-zprob(z) = 1-tail probability for any z, 2.0*(1.0-zprob(abs(z))) = 2-tail probability Adapted from z.c in Gary Perlman's |Stat. Usage: lzprob(z) ""...
Returns the area under the normal curve 'to the left of' the given z value. Thus, for z<0, zprob(z) = 1-tail probability for z>0, 1.0-zprob(z) = 1-tail probability for any z, 2.0*(1.0-zprob(abs(z))) = 2-tail probability Adapted from z.c in Gary Perlman's |Stat. Usage: lzprob(z)
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1361-L1400
bxlab/bx-python
lib/bx_extras/stats.py
lksprob
def lksprob(alam): """ Computes a Kolmolgorov-Smirnov t-test significance level. Adapted from Numerical Recipies. Usage: lksprob(alam) """ fac = 2.0 sum = 0.0 termbf = 0.0 a2 = -2.0*alam*alam for j in range(1,201): term = fac*math.exp(a2*j*j) sum = sum + term if math....
python
def lksprob(alam): """ Computes a Kolmolgorov-Smirnov t-test significance level. Adapted from Numerical Recipies. Usage: lksprob(alam) """ fac = 2.0 sum = 0.0 termbf = 0.0 a2 = -2.0*alam*alam for j in range(1,201): term = fac*math.exp(a2*j*j) sum = sum + term if math....
Computes a Kolmolgorov-Smirnov t-test significance level. Adapted from Numerical Recipies. Usage: lksprob(alam)
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1403-L1421
bxlab/bx-python
lib/bx_extras/stats.py
lfprob
def lfprob (dfnum, dfden, F): """ Returns the (1-tailed) significance level (p-value) of an F statistic given the degrees of freedom for the numerator (dfR-dfF) and the degrees of freedom for the denominator (dfF). Usage: lfprob(dfnum, dfden, F) where usually dfnum=dfbn, dfden=dfwn """ p = betai(0.5*dfden,...
python
def lfprob (dfnum, dfden, F): """ Returns the (1-tailed) significance level (p-value) of an F statistic given the degrees of freedom for the numerator (dfR-dfF) and the degrees of freedom for the denominator (dfF). Usage: lfprob(dfnum, dfden, F) where usually dfnum=dfbn, dfden=dfwn """ p = betai(0.5*dfden,...
Returns the (1-tailed) significance level (p-value) of an F statistic given the degrees of freedom for the numerator (dfR-dfF) and the degrees of freedom for the denominator (dfF). Usage: lfprob(dfnum, dfden, F) where usually dfnum=dfbn, dfden=dfwn
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1424-L1433
bxlab/bx-python
lib/bx_extras/stats.py
lgammln
def lgammln(xx): """ Returns the gamma function of xx. Gamma(z) = Integral(0,infinity) of t^(z-1)exp(-t) dt. (Adapted from: Numerical Recipies in C.) Usage: lgammln(xx) """ coeff = [76.18009173, -86.50532033, 24.01409822, -1.231739516, 0.120858003e-2, -0.536382e-5] x = xx - 1.0 tmp ...
python
def lgammln(xx): """ Returns the gamma function of xx. Gamma(z) = Integral(0,infinity) of t^(z-1)exp(-t) dt. (Adapted from: Numerical Recipies in C.) Usage: lgammln(xx) """ coeff = [76.18009173, -86.50532033, 24.01409822, -1.231739516, 0.120858003e-2, -0.536382e-5] x = xx - 1.0 tmp ...
Returns the gamma function of xx. Gamma(z) = Integral(0,infinity) of t^(z-1)exp(-t) dt. (Adapted from: Numerical Recipies in C.) Usage: lgammln(xx)
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1470-L1488
bxlab/bx-python
lib/bx_extras/stats.py
lbetai
def lbetai(a,b,x): """ Returns the incomplete beta function: I-sub-x(a,b) = 1/B(a,b)*(Integral(0,x) of t^(a-1)(1-t)^(b-1) dt) where a,b>0 and B(a,b) = G(a)*G(b)/(G(a+b)) where G(a) is the gamma function of a. The continued fraction formulation is implemented here, using the betacf function. (Adapted from: N...
python
def lbetai(a,b,x): """ Returns the incomplete beta function: I-sub-x(a,b) = 1/B(a,b)*(Integral(0,x) of t^(a-1)(1-t)^(b-1) dt) where a,b>0 and B(a,b) = G(a)*G(b)/(G(a+b)) where G(a) is the gamma function of a. The continued fraction formulation is implemented here, using the betacf function. (Adapted from: N...
Returns the incomplete beta function: I-sub-x(a,b) = 1/B(a,b)*(Integral(0,x) of t^(a-1)(1-t)^(b-1) dt) where a,b>0 and B(a,b) = G(a)*G(b)/(G(a+b)) where G(a) is the gamma function of a. The continued fraction formulation is implemented here, using the betacf function. (Adapted from: Numerical Recipies in C.) U...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1491-L1513
bxlab/bx-python
lib/bx_extras/stats.py
lF_oneway
def lF_oneway(*lists): """ Performs a 1-way ANOVA, returning an F-value and probability given any number of groups. From Heiman, pp.394-7. Usage: F_oneway(*lists) where *lists is any number of lists, one per treatment group Returns: F value, one-tailed p-value """ a = le...
python
def lF_oneway(*lists): """ Performs a 1-way ANOVA, returning an F-value and probability given any number of groups. From Heiman, pp.394-7. Usage: F_oneway(*lists) where *lists is any number of lists, one per treatment group Returns: F value, one-tailed p-value """ a = le...
Performs a 1-way ANOVA, returning an F-value and probability given any number of groups. From Heiman, pp.394-7. Usage: F_oneway(*lists) where *lists is any number of lists, one per treatment group Returns: F value, one-tailed p-value
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1520-L1554
bxlab/bx-python
lib/bx_extras/stats.py
lF_value
def lF_value (ER,EF,dfnum,dfden): """ Returns an F-statistic given the following: ER = error associated with the null hypothesis (the Restricted model) EF = error associated with the alternate hypothesis (the Full model) dfR-dfF = degrees of freedom of the numerator dfF = degrees o...
python
def lF_value (ER,EF,dfnum,dfden): """ Returns an F-statistic given the following: ER = error associated with the null hypothesis (the Restricted model) EF = error associated with the alternate hypothesis (the Full model) dfR-dfF = degrees of freedom of the numerator dfF = degrees o...
Returns an F-statistic given the following: ER = error associated with the null hypothesis (the Restricted model) EF = error associated with the alternate hypothesis (the Full model) dfR-dfF = degrees of freedom of the numerator dfF = degrees of freedom associated with the denominator/...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1557-L1567
bxlab/bx-python
lib/bx_extras/stats.py
writecc
def writecc (listoflists,file,writetype='w',extra=2): """ Writes a list of lists to a file in columns, customized by the max size of items within the columns (max size of items in col, +2 characters) to specified file. File-overwrite is the default. Usage: writecc (listoflists,file,writetype='w',extra=2) Return...
python
def writecc (listoflists,file,writetype='w',extra=2): """ Writes a list of lists to a file in columns, customized by the max size of items within the columns (max size of items in col, +2 characters) to specified file. File-overwrite is the default. Usage: writecc (listoflists,file,writetype='w',extra=2) Return...
Writes a list of lists to a file in columns, customized by the max size of items within the columns (max size of items in col, +2 characters) to specified file. File-overwrite is the default. Usage: writecc (listoflists,file,writetype='w',extra=2) Returns: None
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1574-L1611
bxlab/bx-python
lib/bx_extras/stats.py
lincr
def lincr(l,cap): # to increment a list up to a max-list of 'cap' """ Simulate a counting system from an n-dimensional list. Usage: lincr(l,cap) l=list to increment, cap=max values for each list pos'n Returns: next set of values for list l, OR -1 (if overflow) """ l[0] = l[0] + 1 # e.g., [0,0,0]...
python
def lincr(l,cap): # to increment a list up to a max-list of 'cap' """ Simulate a counting system from an n-dimensional list. Usage: lincr(l,cap) l=list to increment, cap=max values for each list pos'n Returns: next set of values for list l, OR -1 (if overflow) """ l[0] = l[0] + 1 # e.g., [0,0,0]...
Simulate a counting system from an n-dimensional list. Usage: lincr(l,cap) l=list to increment, cap=max values for each list pos'n Returns: next set of values for list l, OR -1 (if overflow)
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1614-L1628
bxlab/bx-python
lib/bx_extras/stats.py
lcumsum
def lcumsum (inlist): """ Returns a list consisting of the cumulative sum of the items in the passed list. Usage: lcumsum(inlist) """ newlist = copy.deepcopy(inlist) for i in range(1,len(newlist)): newlist[i] = newlist[i] + newlist[i-1] return newlist
python
def lcumsum (inlist): """ Returns a list consisting of the cumulative sum of the items in the passed list. Usage: lcumsum(inlist) """ newlist = copy.deepcopy(inlist) for i in range(1,len(newlist)): newlist[i] = newlist[i] + newlist[i-1] return newlist
Returns a list consisting of the cumulative sum of the items in the passed list. Usage: lcumsum(inlist)
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1643-L1653
bxlab/bx-python
lib/bx_extras/stats.py
lss
def lss(inlist): """ Squares each value in the passed list, adds up these squares and returns the result. Usage: lss(inlist) """ ss = 0 for item in inlist: ss = ss + item*item return ss
python
def lss(inlist): """ Squares each value in the passed list, adds up these squares and returns the result. Usage: lss(inlist) """ ss = 0 for item in inlist: ss = ss + item*item return ss
Squares each value in the passed list, adds up these squares and returns the result. Usage: lss(inlist)
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1656-L1666
bxlab/bx-python
lib/bx_extras/stats.py
lsummult
def lsummult (list1,list2): """ Multiplies elements in list1 and list2, element by element, and returns the sum of all resulting multiplications. Must provide equal length lists. Usage: lsummult(list1,list2) """ if len(list1) != len(list2): raise ValueError("Lists not equal length in summult.") ...
python
def lsummult (list1,list2): """ Multiplies elements in list1 and list2, element by element, and returns the sum of all resulting multiplications. Must provide equal length lists. Usage: lsummult(list1,list2) """ if len(list1) != len(list2): raise ValueError("Lists not equal length in summult.") ...
Multiplies elements in list1 and list2, element by element, and returns the sum of all resulting multiplications. Must provide equal length lists. Usage: lsummult(list1,list2)
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1669-L1682
bxlab/bx-python
lib/bx_extras/stats.py
lsumdiffsquared
def lsumdiffsquared(x,y): """ Takes pairwise differences of the values in lists x and y, squares these differences, and returns the sum of these squares. Usage: lsumdiffsquared(x,y) Returns: sum[(x[i]-y[i])**2] """ sds = 0 for i in range(len(x)): sds = sds + (x[i]-y[i])**2 return sds
python
def lsumdiffsquared(x,y): """ Takes pairwise differences of the values in lists x and y, squares these differences, and returns the sum of these squares. Usage: lsumdiffsquared(x,y) Returns: sum[(x[i]-y[i])**2] """ sds = 0 for i in range(len(x)): sds = sds + (x[i]-y[i])**2 return sds
Takes pairwise differences of the values in lists x and y, squares these differences, and returns the sum of these squares. Usage: lsumdiffsquared(x,y) Returns: sum[(x[i]-y[i])**2]
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1685-L1696
bxlab/bx-python
lib/bx_extras/stats.py
outputpairedstats
def outputpairedstats(fname,writemode,name1,n1,m1,se1,min1,max1,name2,n2,m2,se2,min2,max2,statname,stat,prob): """ Prints or write to a file stats for two groups, using the name, n, mean, sterr, min and max for each group, as well as the statistic name, its value, and the associated p-value. Usage: outputpaireds...
python
def outputpairedstats(fname,writemode,name1,n1,m1,se1,min1,max1,name2,n2,m2,se2,min2,max2,statname,stat,prob): """ Prints or write to a file stats for two groups, using the name, n, mean, sterr, min and max for each group, as well as the statistic name, its value, and the associated p-value. Usage: outputpaireds...
Prints or write to a file stats for two groups, using the name, n, mean, sterr, min and max for each group, as well as the statistic name, its value, and the associated p-value. Usage: outputpairedstats(fname,writemode, name1,n1,mean1,stderr1,min1,max1, name2,n2,...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1762-L1816
bxlab/bx-python
lib/bx/gene_reader.py
GeneReader
def GeneReader( fh, format='gff' ): """ yield chrom, strand, gene_exons, name """ 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': ...
python
def GeneReader( fh, format='gff' ): """ yield chrom, strand, gene_exons, name """ 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
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/gene_reader.py#L19-L79
bxlab/bx-python
lib/bx/gene_reader.py
CDSReader
def CDSReader( fh, format='gff' ): """ yield chrom, strand, cds_exons, name """ 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': f...
python
def CDSReader( fh, format='gff' ): """ yield chrom, strand, cds_exons, name """ 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': f...
yield chrom, strand, cds_exons, name
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/gene_reader.py#L81-L155
bxlab/bx-python
lib/bx/gene_reader.py
FeatureReader
def FeatureReader( fh, format='gff', alt_introns_subtract="exons", gtf_parse=None): """ yield chrom, strand, cds_exons, introns, exons, name gtf_parse Example: # parse gene_id from transcript_id "AC073130.2-001"; gene_id "TES"; gene_name = lambda s: s.split(';')[1].split()[1].strip('"') for c...
python
def FeatureReader( fh, format='gff', alt_introns_subtract="exons", gtf_parse=None): """ yield chrom, strand, cds_exons, introns, exons, name gtf_parse Example: # parse gene_id from transcript_id "AC073130.2-001"; gene_id "TES"; gene_name = lambda s: s.split(';')[1].split()[1].strip('"') for c...
yield chrom, strand, cds_exons, introns, exons, name gtf_parse Example: # parse gene_id from transcript_id "AC073130.2-001"; gene_id "TES"; gene_name = lambda s: s.split(';')[1].split()[1].strip('"') for chrom, strand, cds_exons, introns, exons, name in FeatureReader( sys.stdin, format='gtf', gtf_pars...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/gene_reader.py#L157-L284
bxlab/bx-python
lib/bx/intervals/random_intervals.py
throw_random_gap_list
def throw_random_gap_list( lengths, mask, save_interval_func, allow_overlap=False ): """ Generates a set of non-overlapping random intervals from a length distribution. `lengths`: list containing the length of each interval to be generated. We expect this to be sorted by decreasing ...
python
def throw_random_gap_list( lengths, mask, save_interval_func, allow_overlap=False ): """ Generates a set of non-overlapping random intervals from a length distribution. `lengths`: list containing the length of each interval to be generated. We expect this to be sorted by decreasing ...
Generates a set of non-overlapping random intervals from a length distribution. `lengths`: list containing the length of each interval to be generated. We expect this to be sorted by decreasing length to minimize the chance of failure (MaxtriesException) and for some ...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/intervals/random_intervals.py#L25-L54
bxlab/bx-python
lib/bx/intervals/random_intervals.py
throw_random_intervals
def throw_random_intervals( lengths, regions, save_interval_func=None, allow_overlap=False ): """ Generates a set of non-overlapping random intervals from a length distribution. `lengths`: list containing the length of each interval to be generated. We expect this to be sorted by de...
python
def throw_random_intervals( lengths, regions, save_interval_func=None, allow_overlap=False ): """ Generates a set of non-overlapping random intervals from a length distribution. `lengths`: list containing the length of each interval to be generated. We expect this to be sorted by de...
Generates a set of non-overlapping random intervals from a length distribution. `lengths`: list containing the length of each interval to be generated. We expect this to be sorted by decreasing length to minimize the chance of failure (MaxtriesException) and for some ...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/intervals/random_intervals.py#L56-L89
bxlab/bx-python
lib/bx/intervals/random_intervals.py
throw_random_private
def throw_random_private( lengths, regions, save_interval_func, allow_overlap=False, three_args=True ): """ (Internal function; we expect calls only through the interface functions above) `lengths`: A list containing the length of each interval to be generated. `regions`: A list of regions in ...
python
def throw_random_private( lengths, regions, save_interval_func, allow_overlap=False, three_args=True ): """ (Internal function; we expect calls only through the interface functions above) `lengths`: A list containing the length of each interval to be generated. `regions`: A list of regions in ...
(Internal function; we expect calls only through the interface functions above) `lengths`: A list containing the length of each interval to be generated. `regions`: A list of regions in which intervals can be placed, sorted by decreasing length. Elements are triples of the form (length...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/intervals/random_intervals.py#L98-L212
bxlab/bx-python
lib/bx/seq/seq.py
SeqFile.get
def get(self, start, length): """ Fetch subsequence starting at position `start` with length `length`. This method is picky about parameters, the requested interval must have non-negative length and fit entirely inside the NIB sequence, the returned string will contain exactly ...
python
def get(self, start, length): """ Fetch subsequence starting at position `start` with length `length`. This method is picky about parameters, the requested interval must have non-negative length and fit entirely inside the NIB sequence, the returned string will contain exactly ...
Fetch subsequence starting at position `start` with length `length`. This method is picky about parameters, the requested interval must have non-negative length and fit entirely inside the NIB sequence, the returned string will contain exactly 'length' characters, or an AssertionError ...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/seq/seq.py#L74-L94
bxlab/bx-python
lib/bx/align/score.py
read_scoring_scheme
def read_scoring_scheme( f, gap_open, gap_extend, gap1="-", gap2=None, **kwargs ): """ Initialize scoring scheme from a file containint a blastz style text blob. f can be either a file or the name of a file. """ close_it = False if (type(f) == str): f = file(f,"rt") close_it = Tr...
python
def read_scoring_scheme( f, gap_open, gap_extend, gap1="-", gap2=None, **kwargs ): """ Initialize scoring scheme from a file containint a blastz style text blob. f can be either a file or the name of a file. """ close_it = False if (type(f) == str): f = file(f,"rt") close_it = Tr...
Initialize scoring scheme from a file containint a blastz style text blob. f can be either a file or the name of a file.
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/score.py#L91-L103
bxlab/bx-python
lib/bx/align/score.py
build_scoring_scheme
def build_scoring_scheme( s, gap_open, gap_extend, gap1="-", gap2=None, **kwargs ): """ Initialize scoring scheme from a blastz style text blob, first line specifies the bases for each row/col, subsequent lines contain the corresponding scores. Slaw extensions allow for unusual and/or asymmetric al...
python
def build_scoring_scheme( s, gap_open, gap_extend, gap1="-", gap2=None, **kwargs ): """ Initialize scoring scheme from a blastz style text blob, first line specifies the bases for each row/col, subsequent lines contain the corresponding scores. Slaw extensions allow for unusual and/or asymmetric al...
Initialize scoring scheme from a blastz style text blob, first line specifies the bases for each row/col, subsequent lines contain the corresponding scores. Slaw extensions allow for unusual and/or asymmetric alphabets. Symbols can be two digit hex, and each row begins with symbol. Note that a row co...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/score.py#L105-L196
bxlab/bx-python
lib/bx/align/score.py
accumulate_scores
def accumulate_scores( scoring_scheme, text1, text2, skip_ref_gaps=False ): """ Return cumulative scores for each position in alignment as a 1d array. If `skip_ref_gaps` is False positions in returned array correspond to each column in alignment, if True they correspond to each non-gap position (ea...
python
def accumulate_scores( scoring_scheme, text1, text2, skip_ref_gaps=False ): """ Return cumulative scores for each position in alignment as a 1d array. If `skip_ref_gaps` is False positions in returned array correspond to each column in alignment, if True they correspond to each non-gap position (ea...
Return cumulative scores for each position in alignment as a 1d array. If `skip_ref_gaps` is False positions in returned array correspond to each column in alignment, if True they correspond to each non-gap position (each base) in text1.
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/score.py#L245-L287
bxlab/bx-python
lib/bx/align/core.py
shuffle_columns
def shuffle_columns( a ): """Randomize the columns of an alignment""" mask = range( a.text_size ) random.shuffle( mask ) for c in a.components: c.text = ''.join( [ c.text[i] for i in mask ] )
python
def shuffle_columns( a ): """Randomize the columns of an alignment""" 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
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/core.py#L403-L408
bxlab/bx-python
lib/bx/align/core.py
Alignment.slice_by_component
def slice_by_component( self, component_index, start, end ): """ Return a slice of the alignment, corresponding to an coordinate interval in a specific component. component_index is one of an integer offset into the components list a string indicating the src of the desi...
python
def slice_by_component( self, component_index, start, end ): """ Return a slice of the alignment, corresponding to an coordinate interval in a specific component. component_index is one of an integer offset into the components list a string indicating the src of the desi...
Return a slice of the alignment, corresponding to an coordinate interval in a specific component. component_index is one of an integer offset into the components list a string indicating the src of the desired component a component start and end are relative to the ...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/core.py#L122-L146
bxlab/bx-python
lib/bx/align/core.py
Alignment.remove_all_gap_columns
def remove_all_gap_columns( self ): """ Remove any columns containing only gaps from alignment components, text of components is modified IN PLACE. """ seqs = [] for c in self.components: try: seqs.append( list( c.text ) ) except Ty...
python
def remove_all_gap_columns( self ): """ Remove any columns containing only gaps from alignment components, text of components is modified IN PLACE. """ seqs = [] for c in self.components: try: seqs.append( list( c.text ) ) except Ty...
Remove any columns containing only gaps from alignment components, text of components is modified IN PLACE.
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/core.py#L160-L188
bxlab/bx-python
lib/bx/align/core.py
Component.slice_by_coord
def slice_by_coord( self, start, end ): """ Return the slice of the component corresponding to a coordinate interval. start and end are relative to the + strand, regardless of the component's strand. """ start_col = self.coord_to_col( start ) end_col = self.coord_to_col...
python
def slice_by_coord( self, start, end ): """ Return the slice of the component corresponding to a coordinate interval. start and end are relative to the + strand, regardless of the component's strand. """ start_col = self.coord_to_col( start ) end_col = self.coord_to_col...
Return the slice of the component corresponding to a coordinate interval. start and end are relative to the + strand, regardless of the component's strand.
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/core.py#L307-L318
bxlab/bx-python
lib/bx/align/core.py
Component.coord_to_col
def coord_to_col( self, pos ): """ Return the alignment column index corresponding to coordinate pos. pos is relative to the + strand, regardless of the component's strand. """ start,end = self.get_forward_strand_start(),self.get_forward_strand_end() if pos < start or p...
python
def coord_to_col( self, pos ): """ Return the alignment column index corresponding to coordinate pos. pos is relative to the + strand, regardless of the component's strand. """ start,end = self.get_forward_strand_start(),self.get_forward_strand_end() if pos < start or p...
Return the alignment column index corresponding to coordinate pos. pos is relative to the + strand, regardless of the component's strand.
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/core.py#L320-L351
bxlab/bx-python
lib/bx/align/tools/thread.py
thread
def thread( mafs, species ): """ Restrict an list of alignments to a given list of species by: 1) Removing components for any other species 2) Remove any columns containing all gaps Example: >>> import bx.align.maf >>> block1 = bx.align.maf.from_string( '''...
python
def thread( mafs, species ): """ Restrict an list of alignments to a given list of species by: 1) Removing components for any other species 2) Remove any columns containing all gaps Example: >>> import bx.align.maf >>> block1 = bx.align.maf.from_string( '''...
Restrict an list of alignments to a given list of species by: 1) Removing components for any other species 2) Remove any columns containing all gaps Example: >>> import bx.align.maf >>> block1 = bx.align.maf.from_string( ''' ... a score=4964.0 ... s hg18.ch...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/tools/thread.py#L10-L66
bxlab/bx-python
lib/bx/align/tools/thread.py
get_components_for_species
def get_components_for_species( alignment, species ): """Return the component for each species in the list `species` or None""" # 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 No...
python
def get_components_for_species( alignment, species ): """Return the component for each species in the list `species` or None""" # 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 No...
Return the component for each species in the list `species` or None
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/tools/thread.py#L68-L76
bxlab/bx-python
lib/bx/align/tools/thread.py
remove_all_gap_columns
def remove_all_gap_columns( components ): """ Remove any columns containing only gaps from a set of alignment components, text of components is modified IN PLACE. TODO: Optimize this with Pyrex. """ seqs = [ list( c.text ) for c in components ] i = 0 text_size = len( seqs[0]...
python
def remove_all_gap_columns( components ): """ Remove any columns containing only gaps from a set of alignment components, text of components is modified IN PLACE. TODO: Optimize this with Pyrex. """ seqs = [ list( c.text ) for c in components ] i = 0 text_size = len( seqs[0]...
Remove any columns containing only gaps from a set of alignment components, text of components is modified IN PLACE. TODO: Optimize this with Pyrex.
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/tools/thread.py#L78-L98
bxlab/bx-python
lib/bx/align/maf.py
read_next_maf
def read_next_maf( file, species_to_lengths=None, parse_e_rows=False ): """ Read the next MAF block from `file` and return as an `Alignment` instance. If `parse_i_rows` is true, empty components will be created when e rows are encountered. """ alignment = Alignment(species_to_lengths=species_t...
python
def read_next_maf( file, species_to_lengths=None, parse_e_rows=False ): """ Read the next MAF block from `file` and return as an `Alignment` instance. If `parse_i_rows` is true, empty components will be created when e rows are encountered. """ alignment = Alignment(species_to_lengths=species_t...
Read the next MAF block from `file` and return as an `Alignment` instance. If `parse_i_rows` is true, empty components will be created when e rows are encountered.
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/maf.py#L133-L201
bxlab/bx-python
lib/bx/align/maf.py
readline
def readline( file, skip_blank=False ): """Read a line from provided file, skipping any blank or comment lines""" 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() ): retu...
python
def readline( file, skip_blank=False ): """Read a line from provided file, skipping any blank or comment lines""" 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() ): retu...
Read a line from provided file, skipping any blank or comment lines
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/maf.py#L203-L210
bxlab/bx-python
lib/bx/align/maf.py
parse_attributes
def parse_attributes( fields ): """Parse list of key=value strings into a dict""" attributes = {} for field in fields: pair = field.split( '=' ) attributes[ pair[0] ] = pair[1] return attributes
python
def parse_attributes( fields ): """Parse list of key=value strings into a dict""" attributes = {} for field in fields: pair = field.split( '=' ) attributes[ pair[0] ] = pair[1] return attributes
Parse list of key=value strings into a dict
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/maf.py#L212-L218
bxlab/bx-python
lib/bx/motif/io/transfac.py
TransfacReader.as_dict
def as_dict( self, key="id" ): """ Return a dictionary containing all remaining motifs, using `key` as the dictionary key. """ rval = {} for motif in self: rval[ getattr( motif, key ) ] = motif return rval
python
def as_dict( self, key="id" ): """ Return a dictionary containing all remaining motifs, using `key` as the dictionary key. """ rval = {} for motif in self: rval[ getattr( motif, key ) ] = motif return rval
Return a dictionary containing all remaining motifs, using `key` as the dictionary key.
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/motif/io/transfac.py#L52-L60
bxlab/bx-python
lib/bx/motif/io/transfac.py
TransfacReader.parse_record
def parse_record( self, lines ): """ Parse a TRANSFAC record out of `lines` and return a motif. """ # Break lines up temp_lines = [] for line in lines: fields = line.rstrip( "\r\n" ).split( None, 1 ) if len( fields ) == 1: fields.ap...
python
def parse_record( self, lines ): """ Parse a TRANSFAC record out of `lines` and return a motif. """ # Break lines up temp_lines = [] for line in lines: fields = line.rstrip( "\r\n" ).split( None, 1 ) if len( fields ) == 1: fields.ap...
Parse a TRANSFAC record out of `lines` and return a motif.
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/motif/io/transfac.py#L90-L174
bxlab/bx-python
scripts/bed_rand_intersect.py
bit_clone
def bit_clone( bits ): """ Clone a bitset """ new = BitSet( bits.size ) new.ior( bits ) return new
python
def bit_clone( bits ): """ Clone a bitset """ new = BitSet( bits.size ) new.ior( bits ) return new
Clone a bitset
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/bed_rand_intersect.py#L35-L41
bxlab/bx-python
scripts/bed_rand_intersect.py
throw_random
def throw_random( lengths, mask ): """ Try multiple times to run 'throw_random' """ saved = None for i in range( maxtries ): try: return throw_random_bits( lengths, mask ) except MaxtriesException as e: saved = e continue raise e
python
def throw_random( lengths, mask ): """ Try multiple times to run 'throw_random' """ saved = None for i in range( maxtries ): try: return throw_random_bits( lengths, mask ) except MaxtriesException as e: saved = e continue raise e
Try multiple times to run 'throw_random'
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/bed_rand_intersect.py#L43-L54
bxlab/bx-python
scripts/bed_rand_intersect.py
as_bits
def as_bits( region_start, region_length, intervals ): """ Convert a set of intervals overlapping a region of a chromosome into a bitset for just that region with the bits covered by the intervals set. """ bits = BitSet( region_length ) for chr, start, stop in intervals: bits.set_r...
python
def as_bits( region_start, region_length, intervals ): """ Convert a set of intervals overlapping a region of a chromosome into a bitset for just that region with the bits covered by the intervals set. """ bits = BitSet( region_length ) for chr, start, stop in intervals: bits.set_r...
Convert a set of intervals overlapping a region of a chromosome into a bitset for just that region with the bits covered by the intervals set.
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/bed_rand_intersect.py#L56-L65
bxlab/bx-python
scripts/bed_rand_intersect.py
interval_lengths
def interval_lengths( bits ): """ Get the length distribution of all contiguous runs of set bits from """ end = 0 while 1: start = bits.next_set( end ) if start == bits.size: break end = bits.next_clear( start ) yield end - start
python
def interval_lengths( bits ): """ Get the length distribution of all contiguous runs of set bits from """ end = 0 while 1: start = bits.next_set( end ) if start == bits.size: break end = bits.next_clear( start ) yield end - start
Get the length distribution of all contiguous runs of set bits from
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/bed_rand_intersect.py#L67-L76
bxlab/bx-python
scripts/bed_rand_intersect.py
count_overlap
def count_overlap( bits1, bits2 ): """ Count the number of bits that overlap between two sets """ b = BitSet( bits1.size ) b |= bits1 b &= bits2 return b.count_range( 0, b.size )
python
def count_overlap( bits1, bits2 ): """ Count the number of bits that overlap between two sets """ b = BitSet( bits1.size ) b |= bits1 b &= bits2 return b.count_range( 0, b.size )
Count the number of bits that overlap between two sets
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/bed_rand_intersect.py#L78-L85
bxlab/bx-python
scripts/bed_rand_intersect.py
overlapping_in_bed
def overlapping_in_bed( fname, r_chr, r_start, r_stop ): """ Get from a bed all intervals that overlap the region defined by r_chr, r_start, r_stop. """ rval = [] for line in open( fname ): if line.startswith( "#" ) or line.startswith( "track" ): continue fields = lin...
python
def overlapping_in_bed( fname, r_chr, r_start, r_stop ): """ Get from a bed all intervals that overlap the region defined by r_chr, r_start, r_stop. """ rval = [] for line in open( fname ): if line.startswith( "#" ) or line.startswith( "track" ): continue fields = lin...
Get from a bed all intervals that overlap the region defined by r_chr, r_start, r_stop.
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/bed_rand_intersect.py#L87-L100
bxlab/bx-python
lib/bx/align/tools/tile.py
tile_interval
def tile_interval( sources, index, ref_src, start, end, seq_db=None ): """ Tile maf blocks onto an interval. The resulting block will span the interval exactly and contain the column from the highest scoring alignment at each position. `sources`: list of sequence source names to include in final bl...
python
def tile_interval( sources, index, ref_src, start, end, seq_db=None ): """ Tile maf blocks onto an interval. The resulting block will span the interval exactly and contain the column from the highest scoring alignment at each position. `sources`: list of sequence source names to include in final bl...
Tile maf blocks onto an interval. The resulting block will span the interval exactly and contain the column from the highest scoring alignment at each position. `sources`: list of sequence source names to include in final block `index`: an instnace that can return maf blocks overlapping intervals `...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/tools/tile.py#L13-L71
bxlab/bx-python
lib/bx/pwm/pwm_score_maf.py
MafMotifSelect
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( alignlist ) nrows,ncols = align.dims ...
python
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( alignlist ) nrows,ncols = align.dims ...
for ir in range(nrows): # scan alignment row for motif subsequences for start in range(ncols): if align.rows[ir][start] == '-': continue elif align.rows[ir][start] == 'n': continue elif align.rows[ir][start] == 'N': continue # gather enough subseq for moti...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/pwm/pwm_score_maf.py#L79-L170
bxlab/bx-python
lib/bx/phylo/newick.py
create_parser
def create_parser(): """ Create a 'pyparsing' parser for newick format trees roughly based on the grammar here: http://evolution.genetics.washington.edu/phylip/newick_doc.html Problems: - Is a single leaf a valid tree? - Branch length on root? Doesn't make sense to me, and force...
python
def create_parser(): """ Create a 'pyparsing' parser for newick format trees roughly based on the grammar here: http://evolution.genetics.washington.edu/phylip/newick_doc.html Problems: - Is a single leaf a valid tree? - Branch length on root? Doesn't make sense to me, and force...
Create a 'pyparsing' parser for newick format trees roughly based on the grammar here: http://evolution.genetics.washington.edu/phylip/newick_doc.html Problems: - Is a single leaf a valid tree? - Branch length on root? Doesn't make sense to me, and forces the root to be an edg...
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/phylo/newick.py#L52-L89
bxlab/bx-python
scripts/maf_tile_2bit.py
get_fill_char
def get_fill_char( maf_status ): """ Return the character that should be used to fill between blocks having a given status """ ## assert maf_status not in ( maf.MAF_CONTIG_NESTED_STATUS, maf.MAF_NEW_NESTED_STATUS, ## maf.MAF_MAYBE_NEW_NESTED_STATUS ), \ ## "Ne...
python
def get_fill_char( maf_status ): """ Return the character that should be used to fill between blocks having a given status """ ## assert maf_status not in ( maf.MAF_CONTIG_NESTED_STATUS, maf.MAF_NEW_NESTED_STATUS, ## maf.MAF_MAYBE_NEW_NESTED_STATUS ), \ ## "Ne...
Return the character that should be used to fill between blocks having a given status
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/maf_tile_2bit.py#L72-L90
bxlab/bx-python
scripts/maf_tile_2bit.py
guess_fill_char
def guess_fill_char( left_comp, right_comp ): """ For the case where there is no annotated synteny we will try to guess it """ # 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_co...
python
def guess_fill_char( left_comp, right_comp ): """ For the case where there is no annotated synteny we will try to guess it """ # 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_co...
For the case where there is no annotated synteny we will try to guess it
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/maf_tile_2bit.py#L92-L107
bxlab/bx-python
scripts/maf_tile_2bit.py
remove_all_gap_columns
def remove_all_gap_columns( texts ): """ Remove any columns containing only gaps from alignment 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 ( '-', '#', '*', '...
python
def remove_all_gap_columns( texts ): """ Remove any columns containing only gaps from alignment 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 ( '-', '#', '*', '...
Remove any columns containing only gaps from alignment texts
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/maf_tile_2bit.py#L109-L127
bxlab/bx-python
lib/bx/cookbook/__init__.py
cross_lists
def cross_lists(*sets): """Return the cross product of the arguments""" 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]) br...
python
def cross_lists(*sets): """Return the cross product of the arguments""" 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]) br...
Return the cross product of the arguments
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/cookbook/__init__.py#L16-L30
bxlab/bx-python
lib/bx/misc/readlengths.py
read_lengths_file
def read_lengths_file( name ): """ Returns a hash from sequence name to length. """ 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)...
python
def read_lengths_file( name ): """ Returns a hash from sequence name to length. """ 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)...
Returns a hash from sequence name to length.
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/misc/readlengths.py#L7-L28
bxlab/bx-python
lib/bx/wiggle.py
IntervalReader
def IntervalReader( f ): """ Iterator yielding chrom, start, end, strand, value. Values are zero-based, half-open. Regions which lack a score are ignored. """ current_chrom = None current_pos = None current_step = None # always for wiggle data strand = '+' mode = "bed" ...
python
def IntervalReader( f ): """ Iterator yielding chrom, start, end, strand, value. Values are zero-based, half-open. Regions which lack a score are ignored. """ current_chrom = None current_pos = None current_step = None # always for wiggle data strand = '+' mode = "bed" ...
Iterator yielding chrom, start, end, strand, value. Values are zero-based, half-open. Regions which lack a score are ignored.
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/wiggle.py#L14-L63
bxlab/bx-python
lib/bx/misc/binary_file.py
BinaryFileReader.read_and_unpack
def read_and_unpack( self, format, byte_count=None ): """ Read enough bytes to unpack according to `format` and return the tuple of unpacked values. """ pattern = "%s%s" % ( self.endian_code, format ) if byte_count is None: byte_count = struct.calcsize( patter...
python
def read_and_unpack( self, format, byte_count=None ): """ Read enough bytes to unpack according to `format` and return the tuple of unpacked values. """ pattern = "%s%s" % ( self.endian_code, format ) if byte_count is None: byte_count = struct.calcsize( patter...
Read enough bytes to unpack according to `format` and return the tuple of unpacked values.
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/misc/binary_file.py#L59-L67
bxlab/bx-python
lib/bx/misc/binary_file.py
BinaryFileReader.read_c_string
def read_c_string( self ): """ Read a zero terminated (C style) string """ rval = [] while 1: ch = self.file.read(1) assert len( ch ) == 1, "Unexpected end of file" if ch == b'\0': break rval.append( ch ) ret...
python
def read_c_string( self ): """ Read a zero terminated (C style) string """ rval = [] while 1: ch = self.file.read(1) assert len( ch ) == 1, "Unexpected end of file" if ch == b'\0': break rval.append( ch ) ret...
Read a zero terminated (C style) string
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/misc/binary_file.py#L69-L80
bxlab/bx-python
lib/bx/misc/binary_file.py
BinaryFileWriter.pack_and_write
def pack_and_write( self, format, value ): """ Read enough bytes to unpack according to `format` and return the tuple of unpacked values. """ pattern = "%s%s" % ( self.endian_code, format ) return self.file.write( struct.pack( pattern, value ) )
python
def pack_and_write( self, format, value ): """ Read enough bytes to unpack according to `format` and return the tuple of unpacked values. """ pattern = "%s%s" % ( self.endian_code, format ) return self.file.write( struct.pack( pattern, value ) )
Read enough bytes to unpack according to `format` and return the tuple of unpacked values.
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/misc/binary_file.py#L137-L143
bxlab/bx-python
lib/bx/misc/binary_file.py
BinaryFileWriter.write_c_string
def write_c_string( self, value ): """ Read a zero terminated (C style) string """ self.file.write( value ) self.file.write( b'\0' )
python
def write_c_string( self, value ): """ Read a zero terminated (C style) string """ self.file.write( value ) self.file.write( b'\0' )
Read a zero terminated (C style) string
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/misc/binary_file.py#L145-L150
bxlab/bx-python
lib/bx/align/tools/fuse.py
fuse_list
def fuse_list( mafs ): """ Try to fuse a list of blocks by progressively fusing each adjacent pair. """ last = None for m in mafs: if last is None: last = m else: fused = fuse( last, m ) if fused: last = fused else: ...
python
def fuse_list( mafs ): """ Try to fuse a list of blocks by progressively fusing each adjacent pair. """ last = None for m in mafs: if last is None: last = m else: fused = fuse( last, m ) if fused: last = fused else: ...
Try to fuse a list of blocks by progressively fusing each adjacent pair.
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/tools/fuse.py#L8-L24
bxlab/bx-python
lib/bx/align/tools/fuse.py
fuse
def fuse( m1, m2 ): """ Attempt to fuse two blocks. If they can be fused returns a new block, otherwise returns None. Example: >>> import bx.align.maf >>> block1 = bx.align.maf.from_string( ''' ... a score=0.0 ... s hg18.chr10 52686 44 + 135374737 GTGCTAACTTACTGCTCC...
python
def fuse( m1, m2 ): """ Attempt to fuse two blocks. If they can be fused returns a new block, otherwise returns None. Example: >>> import bx.align.maf >>> block1 = bx.align.maf.from_string( ''' ... a score=0.0 ... s hg18.chr10 52686 44 + 135374737 GTGCTAACTTACTGCTCC...
Attempt to fuse two blocks. If they can be fused returns a new block, otherwise returns None. Example: >>> import bx.align.maf >>> block1 = bx.align.maf.from_string( ''' ... a score=0.0 ... s hg18.chr10 52686 44 + 135374737 GTGCTAACTTACTGCTCCACAGAAAACATCAATTCTGCTCATGC ....
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/tools/fuse.py#L26-L67