INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Concatenate chunks. If multiple chunk files match to the same sample name but with different barcodes ( i. e. they are technical replicates ) then this will assign all the files to the same sample name file. | def concat_chunks(data, ipyclient):
"""
Concatenate chunks. If multiple chunk files match to the same sample name
but with different barcodes (i.e., they are technical replicates) then this
will assign all the files to the same sample name file.
"""
## collate files progress bar
start = ti... |
Submit chunks to be sorted by the barmatch () function then calls putstats (). | def demux2(data, chunkfiles, cutters, longbar, matchdict, ipyclient):
"""
Submit chunks to be sorted by the barmatch() function then
calls putstats().
"""
## parallel stuff, limit to 1/4 of available cores for RAM limits.
start = time.time()
printstr = ' sorting reads | {} | s1 |'... |
submit chunks to be sorted | def demux(data, chunkfiles, cutters, longbar, matchdict, ipyclient):
""" submit chunks to be sorted """
## parallel stuff
start = time.time()
printstr = ' sorting reads | {} | s1 |'
lbview = ipyclient.load_balanced_view()
## store statcounters and async results in dicts
perfile = {... |
puts stats from pickles into a dictionary | def putstats(pfile, handle, statdicts):
""" puts stats from pickles into a dictionary """
## load in stats
with open(pfile, 'r') as infile:
filestats, samplestats = pickle.load(infile)
## get dicts from statdicts tuple
perfile, fsamplehits, fbarhits, fmisses, fdbars = statdicts
## pul... |
Call bash command cat and split to split large files. The goal is to create N splitfiles where N is a multiple of the number of processors so that each processor can work on a file in parallel. | def zcat_make_temps(data, raws, num, tmpdir, optim, njobs, start):
"""
Call bash command 'cat' and 'split' to split large files. The goal
is to create N splitfiles where N is a multiple of the number of processors
so that each processor can work on a file in parallel.
"""
printstr = ' chunking... |
make toyplot matrix fig | def _plotshare(share, names, **kwargs):
""" make toyplot matrix fig"""
## set the colormap
colormap = toyplot.color.LinearMap(toyplot.color.brewer.palette("Spectral"),
domain_min=share.min(), domain_max=share.max())
## set up canvas
if not kwargs.get('width'):
... |
parse the loci file list and return presence/ absence matrix ordered by the tips on the tree | def _getarray(loci, tree):
"""
parse the loci file list and return presence/absence matrix
ordered by the tips on the tree
"""
## order tips
tree.ladderize()
## get tip names
snames = tree.get_leaf_names()
## make an empty matrix
lxs = np.zeros((len(snames), len(loci)), dtype... |
fill a matrix with pairwise data sharing | def _countmatrix(lxs):
""" fill a matrix with pairwise data sharing """
## an empty matrix
share = np.zeros((lxs.shape[0], lxs.shape[0]))
## fill above
names = range(lxs.shape[0])
for row in lxs:
for samp1, samp2 in itertools.combinations(names, 2):
shared = lxs[samp1, ... |
Get the param name from the dict index value. | def paramname(param=""):
""" Get the param name from the dict index value.
"""
try:
name = pinfo[str(param)][0].strip().split(" ")[1]
except (KeyError, ValueError) as err:
## TODO: paramsinfo get description by param string not working.
## It would be cool to have an assembly o... |
Returns detailed information for the numbered parameter. Further information is available in the tutorial. Unlike params () this function doesn t deal well with * It only takes one parameter at a time and returns the desc | def paraminfo(param="", short=False):
""" Returns detailed information for the numbered parameter.
Further information is available in the tutorial.
Unlike params() this function doesn't deal well with *
It only takes one parameter at a time and returns the desc
"""
## If the short... |
This is the human readable version of the paramsinfo () function. You give it a param and it prints to stdout. | def paramsinfo(param="", short=False):
""" This is the human readable version of the paramsinfo() function.
You give it a param and it prints to stdout.
"""
if short:
desc = 1
else:
desc = 0
if param == "*":
for key in pinfo:
print(pinfo[str(key)][desc])
... |
Create a new Assembly () and convert as many of our old params to the new version as we can. Also report out any parameters that are removed and what their values are. | def update_assembly(data):
"""
Create a new Assembly() and convert as many of our old params to the new
version as we can. Also report out any parameters that are removed
and what their values are.
"""
print("##############################################################")
print("Updating... |
save to json. | def save_json2(data):
""" save to json."""
## convert everything to dicts
## skip _ipcluster cuz it's made new.
datadict = OrderedDict([
("outfiles", data.__dict__["outfiles"]),
("stats_files", dict(data.__dict__["stats_files"])),
("stats_dfs", data.__dict__["stats_dfs"])
... |
Save assembly and samples as json | def save_json(data):
""" Save assembly and samples as json """
## data as dict
#### skip _ipcluster because it's made new
#### skip _headers because it's loaded new
#### statsfiles save only keys
#### samples save only keys
datadict = OrderedDict([
("_version", data.__dict__["_versi... |
Load a json serialized object and ensure it matches to the current Assembly object format | def load_json(path, quiet=False, cli=False):
"""
Load a json serialized object and ensure it matches to the current
Assembly object format
"""
## load the JSON string and try with name+.json
checkfor = [path+".json", path]
for inpath in checkfor:
inpath = inpath.replace("~", os.p... |
wat | def _tup_and_byte(obj):
""" wat """
# if this is a unicode string, return its string representation
if isinstance(obj, unicode):
return obj.encode('utf-8')
# if this is a list of values, return list of byteified values
if isinstance(obj, list):
return [_tup_and_byte(item) for item i... |
function to encode json string | def encode(self, obj):
""" function to encode json string"""
def hint_tuples(item):
""" embeds __tuple__ hinter in json strings """
if isinstance(item, tuple):
return {'__tuple__': True, 'items': item}
if isinstance(item, list):
return ... |
signature... | def baba_panel_plot(
ttree,
tests,
boots,
show_tip_labels=True,
show_test_labels=True,
use_edge_lengths=False,
collapse_outgroup=False,
pct_tree_x=0.4,
pct_tree_y=0.2,
alpha=3.0,
*args,
**kwargs):
"""
signature...
"""
## create Panel plot object an... |
plots histogram of coverages across clusters | def depthplot(data, samples=None, dims=(None,None), canvas=(None,None),
xmax=50, log=False, outprefix=None, use_maxdepth=False):
""" plots histogram of coverages across clusters"""
## select samples to be plotted, requires depths info
if not samples:
samples = data.samples.keys()
... |
return 00 outfile as a pandas DataFrame | def _parse_00(ofile):
"""
return 00 outfile as a pandas DataFrame
"""
with open(ofile) as infile:
## read in the results summary from the end of the outfile
arr = np.array(
[" "] + infile.read().split("Summary of MCMC results\n\n\n")[1:][0]\
.strip().split())
... |
a subfunction for summarizing results | def _parse_01(ofiles, individual=False):
"""
a subfunction for summarizing results
"""
## parse results from outfiles
cols = []
dats = []
for ofile in ofiles:
## parse file
with open(ofile) as infile:
dat = infile.read()
lastbits = dat.split(".mcmc.txt... |
Load existing results files for an object with this workdir and name. This does NOT reload the parameter settings for the object... | def _load_existing_results(self, name, workdir):
"""
Load existing results files for an object with this workdir and name.
This does NOT reload the parameter settings for the object...
"""
## get mcmcs
path = os.path.realpath(os.path.join(self.workdir, self.name))
... |
Submits bpp jobs to run on a cluster ( ipyparallel Client ). The seed for the random number generator if not set is randomly drawn and if multiple reps are submitted ( nreps > 1 ) then each will draw a subsequent random seeds after that. An ipyclient connection is required. Asynchronous result objects are stored in the... | def run(self,
ipyclient,
nreps=1,
quiet=False,
randomize_order=False,
force=False,
):
"""
Submits bpp jobs to run on a cluster (ipyparallel Client).
The seed for the random number generator if not set is randomly
drawn, and if multiple ... |
Writes bpp files (. ctl. seq. imap ) to the working directory. | def write_bpp_files(self, randomize_order=False, quiet=False):
"""
Writes bpp files (.ctl, .seq, .imap) to the working directory.
Parameters:
------------
randomize_order (bool):
whether to randomize the locus order, this will allow you to
sample diffe... |
write outfile with any args in argdict | def _write_ctlfile(self):#, rep=None):
""" write outfile with any args in argdict """
## A string to store ctl info
ctl = []
## write the top header info
ctl.append("seed = {}".format(self.params.seed))
ctl.append("seqfile = {}".format(self.seqfile))
ctl.append(... |
Returns a copy of the bpp object with the same parameter settings but with the files. mcmcfiles and files. outfiles attributes cleared and with a new name attribute. Parameters ---------- name ( str ): A name for the new copied bpp object that will be used for the output files created by the object. | def copy(self, name, load_existing_results=False):
"""
Returns a copy of the bpp object with the same parameter settings
but with the files.mcmcfiles and files.outfiles attributes cleared,
and with a new 'name' attribute.
Parameters
----------
name (st... |
Prints a summarized table of results from replicate runs or if individual_result = True then returns a list of separate dataframes for each replicate run. | def summarize_results(self, individual_results=False):
"""
Prints a summarized table of results from replicate runs, or,
if individual_result=True, then returns a list of separate
dataframes for each replicate run.
"""
## return results depending on algorithm
... |
notes | def persistent_popen_align3(data, samples, chunk):
""" notes """
## data are already chunked, read in the whole thing
with open(chunk, 'rb') as infile:
clusts = infile.read().split("//\n//\n")[:-1]
## snames to ensure sorted order
samples.sort(key=lambda x: x.name)
snames = [sampl... |
Sends the cluster bits to nprocessors for muscle alignment. They return with indel. h5 handles to be concatenated into a joint h5. | def multi_muscle_align(data, samples, ipyclient):
"""
Sends the cluster bits to nprocessors for muscle alignment. They return
with indel.h5 handles to be concatenated into a joint h5.
"""
LOGGER.info("starting alignments")
## get client
lbview = ipyclient.load_balanced_view()
start = ti... |
concatenates sorted aligned cluster tmpfiles and removes them. | def concatclusts(outhandle, alignbits):
""" concatenates sorted aligned cluster tmpfiles and removes them."""
with gzip.open(outhandle, 'wb') as out:
for fname in alignbits:
with open(fname) as infile:
out.write(infile.read()+"//\n//\n") |
Builds the indels array and catclust. gz file from the aligned clusters. Building catclust is very fast. Entering indels into h5 array is a bit slow but can probably be sped up. ( todo ). NOT currently parallelized. | def build_indels(data, samples, ipyclient):
"""
Builds the indels array and catclust.gz file from the aligned clusters.
Building catclust is very fast. Entering indels into h5 array is a bit
slow but can probably be sped up. (todo). NOT currently parallelized.
"""
## progress bars
lbview = ... |
sub func in build_indels (). | def sub_build_indels(data, samples):
""" sub func in `build_indels()`. """
## get file handles
indelfiles = glob.glob(os.path.join(data.tmpdir, "indels_*.tmp.npy"))
alignbits = glob.glob(os.path.join(data.tmpdir, "align_*.fa"))
## sort into input order by chunk names
indelfiles.sort(key=lambda... |
distributes cluster () function to an ipyclient to make sure it runs on a high memory node. | def call_cluster(data, noreverse, ipyclient):
"""
distributes 'cluster()' function to an ipyclient to make sure it runs
on a high memory node.
"""
## Find host with the most engines, for now just using first.
lbview = ipyclient.load_balanced_view()
## request engine data, skips busy engine... |
Calls vsearch for clustering across samples. | def cluster(data, noreverse, nthreads):
"""
Calls vsearch for clustering across samples.
"""
## input and output file handles
cathaplos = os.path.join(data.dirs.across, data.name+"_catshuf.tmp")
uhaplos = os.path.join(data.dirs.across, data.name+".utemp")
hhaplos = os.path.join(data.dirs.ac... |
Sets up all of the h5 arrays that we will fill. The catg array of prefiltered loci is 4 - dimensional ( Big ) so one big array would overload memory we need to fill it in slices. This will be done in multicat ( singlecat ) and fill_superseqs. | def build_h5_array(data, samples, nloci):
"""
Sets up all of the h5 arrays that we will fill.
The catg array of prefiltered loci is 4-dimensional (Big), so one big
array would overload memory, we need to fill it in slices.
This will be done in multicat (singlecat) and fill_superseqs.
"""
... |
fills the duplicates array from the multi_muscle_align tmp files | def fill_dups_arr(data):
"""
fills the duplicates array from the multi_muscle_align tmp files
"""
## build the duplicates array
duplefiles = glob.glob(os.path.join(data.tmpdir, "duples_*.tmp.npy"))
duplefiles.sort(key=lambda x: int(x.rsplit("_", 1)[-1][:-8]))
## enter the duplicates filter ... |
build tmp h5 arrays that can return quick access for nloci | def build_tmp_h5(data, samples):
""" build tmp h5 arrays that can return quick access for nloci"""
## get samples and names, sorted
snames = [i.name for i in samples]
snames.sort()
## Build an array for quickly indexing consens reads from catg files.
## save as a npy int binary file.
uhandl... |
return nloci from the tmp h5 arr | def get_nloci(data):
""" return nloci from the tmp h5 arr"""
bseeds = os.path.join(data.dirs.across, data.name+".tmparrs.h5")
with h5py.File(bseeds) as io5:
return io5["seedsarr"].shape[0] |
builds a seeds and hits ( uarr ) array of ints from the utemp. sort file. Saves outputs to files... | def get_seeds_and_hits(uhandle, bseeds, snames):
"""
builds a seeds and hits (uarr) array of ints from the utemp.sort file.
Saves outputs to files ...
"""
## Get max name length. Allow for trailing _ + up to 9 digits
## of numbers of loci (an astronomical number of unique loci)
maxlen_names ... |
Calls singlecat () for all samples to build index files. | def new_multicat(data, samples, ipyclient):
"""
Calls 'singlecat()' for all samples to build index files.
"""
## track progress
LOGGER.info("in the multicat")
start = time.time()
printstr = " indexing clusters | {} | s6 |"
## Build the large h5 array. This will write a new HDF5 fil... |
Runs singlecat and cleanup jobs for each sample. For each sample this fills its own hdf5 array with catg data & indels. This is messy could use simplifiying. | def multicat(data, samples, ipyclient):
"""
Runs singlecat and cleanup jobs for each sample.
For each sample this fills its own hdf5 array with catg data & indels.
This is messy, could use simplifiying.
"""
## progress ticker
start = time.time()
printstr = " indexing clusters | {} |... |
Orders catg data for each sample into the final locus order. This allows all of the individual catgs to simply be combined later. They are also in the same order as the indels array so indels are inserted from the indel array that is passed in. | def singlecat(data, sample, bseeds, sidx, nloci):
"""
Orders catg data for each sample into the final locus order. This allows
all of the individual catgs to simply be combined later. They are also in
the same order as the indels array, so indels are inserted from the indel
array that is passed in.
... |
writes arrays to h5 disk | def write_to_fullarr(data, sample, sidx):
""" writes arrays to h5 disk """
## enter ref data?
#isref = 'reference' in data.paramsdict["assembly_method"]
LOGGER.info("writing fullarr %s %s", sample.name, sidx)
## save big arrays to disk temporarily
with h5py.File(data.clust_database, 'r+') as i... |
A dask relay function to fill chroms for all samples | def dask_chroms(data, samples):
"""
A dask relay function to fill chroms for all samples
"""
## example concatenating with dask
h5s = [os.path.join(data.dirs.across, s.name+".tmp.h5") for s in samples]
handles = [h5py.File(i) for i in h5s]
dsets = [i['/ichrom'] for i in handles]
arr... |
inserts indels into the catg array | def inserted_indels(indels, ocatg):
"""
inserts indels into the catg array
"""
## return copy with indels inserted
newcatg = np.zeros(ocatg.shape, dtype=np.uint32)
## iterate over loci and make extensions for indels
for iloc in xrange(ocatg.shape[0]):
## get indels indices
i... |
Fills the superseqs array with seq data from cat. clust and fill the edges array with information about paired split locations. | def fill_superseqs(data, samples):
"""
Fills the superseqs array with seq data from cat.clust
and fill the edges array with information about paired split locations.
"""
## load super to get edges
io5 = h5py.File(data.clust_database, 'r+')
superseqs = io5["seqs"]
splits = io5["splits"]
... |
uses bash commands to quickly count N seeds from utemp file | def count_seeds(usort):
"""
uses bash commands to quickly count N seeds from utemp file
"""
with open(usort, 'r') as insort:
cmd1 = ["cut", "-f", "2"]
cmd2 = ["uniq"]
cmd3 = ["wc"]
proc1 = sps.Popen(cmd1, stdin=insort, stdout=sps.PIPE, close_fds=True)
proc2 = sps.... |
sort seeds from cluster results | def sort_seeds(uhandle, usort):
""" sort seeds from cluster results"""
cmd = ["sort", "-k", "2", uhandle, "-o", usort]
proc = sps.Popen(cmd, close_fds=True)
proc.communicate() |
Reconstitutes clusters from. utemp and htemp files and writes them to chunked files for aligning in muscle. | def build_clustbits(data, ipyclient, force):
"""
Reconstitutes clusters from .utemp and htemp files and writes them
to chunked files for aligning in muscle.
"""
## If you run this step then we clear all tmp .fa and .indel.h5 files
if os.path.exists(data.tmpdir):
shutil.rmtree(data.tmpdi... |
A subfunction of build_clustbits to allow progress tracking. This func splits the unaligned clusters into bits for aligning on separate cores. | def sub_build_clustbits(data, usort, nseeds):
"""
A subfunction of build_clustbits to allow progress tracking. This func
splits the unaligned clusters into bits for aligning on separate cores.
"""
## load FULL concat fasta file into a dict. This could cause RAM issues.
## this file has iupac co... |
[ This is run on an ipengine ] Make a concatenated consens file with sampled alleles ( no RSWYMK/ rswymk ). Orders reads by length and shuffles randomly within length classes | def build_input_file(data, samples, randomseed):
"""
[This is run on an ipengine]
Make a concatenated consens file with sampled alleles (no RSWYMK/rswymk).
Orders reads by length and shuffles randomly within length classes
"""
## get all of the consens handles for samples that have consens read... |
STEP 6 - 1: Clears dirs and databases and calls build_input_file () | def clean_and_build_concat(data, samples, randomseed, ipyclient):
"""
STEP 6-1:
Clears dirs and databases and calls 'build_input_file()'
"""
## but check for new clust database name if this is a new branch
cleanup_tempfiles(data)
catclust = os.path.join(data.dirs.across, data.name+"_catclus... |
For step 6 the run function is sub divided a bit so that users with really difficult assemblies can possibly interrupt and restart the step from a checkpoint. | def run(data, samples, noreverse, force, randomseed, ipyclient, **kwargs):
"""
For step 6 the run function is sub divided a bit so that users with really
difficult assemblies can possibly interrupt and restart the step from a
checkpoint.
Substeps that are run:
1. build concat consens file,
... |
Function to remove older files. This is called either in substep 1 or after the final substep so that tempfiles are retained for restarting interrupted jobs until we re sure they re no longer needed. | def cleanup_tempfiles(data):
"""
Function to remove older files. This is called either in substep 1 or after
the final substep so that tempfiles are retained for restarting interrupted
jobs until we're sure they're no longer needed.
"""
## remove align-related tmp files
tmps1 = glob.glob(... |
cleanup for assembly object | def assembly_cleanup(data):
""" cleanup for assembly object """
## build s2 results data frame
data.stats_dfs.s2 = data._build_stat("s2")
data.stats_files.s2 = os.path.join(data.dirs.edits, 's2_rawedit_stats.txt')
## write stats for all samples
with io.open(data.stats_files.s2, 'w', encoding='... |
parse results from cutadapt into sample data | def parse_single_results(data, sample, res1):
""" parse results from cutadapt into sample data"""
## set default values
#sample.stats_dfs.s2["reads_raw"] = 0
sample.stats_dfs.s2["trim_adapter_bp_read1"] = 0
sample.stats_dfs.s2["trim_quality_bp_read1"] = 0
sample.stats_dfs.s2["reads_filtered_by... |
parse results from cutadapt for paired data | def parse_pair_results(data, sample, res):
""" parse results from cutadapt for paired data"""
LOGGER.info("in parse pair mod results\n%s", res)
## set default values
sample.stats_dfs.s2["trim_adapter_bp_read1"] = 0
sample.stats_dfs.s2["trim_adapter_bp_read2"] = 0
sample.stats_dfs.s2["trim... |
Applies quality and adapter filters to reads using cutadapt. If the ipyrad filter param is set to 0 then it only filters to hard trim edges and uses mintrimlen. If filter = 1 we add quality filters. If filter = 2 we add adapter filters. | def cutadaptit_single(data, sample):
"""
Applies quality and adapter filters to reads using cutadapt. If the ipyrad
filter param is set to 0 then it only filters to hard trim edges and uses
mintrimlen. If filter=1, we add quality filters. If filter=2 we add
adapter filters.
"""
sname = sa... |
Applies trim & filters to pairs including adapter detection. If we have barcode information then we use it to trim reversecut + bcode + adapter from reverse read if not then we have to apply a more general cut to make sure we remove the barcode this uses wildcards and so will have more false positives that trim a littl... | def cutadaptit_pairs(data, sample):
"""
Applies trim & filters to pairs, including adapter detection. If we have
barcode information then we use it to trim reversecut+bcode+adapter from
reverse read, if not then we have to apply a more general cut to make sure
we remove the barcode, this uses wild... |
Filter for samples that are already finished with this step allow others to run pass them to parallel client function to filter with cutadapt. | def run2(data, samples, force, ipyclient):
"""
Filter for samples that are already finished with this step, allow others
to run, pass them to parallel client function to filter with cutadapt.
"""
## create output directories
data.dirs.edits = os.path.join(os.path.realpath(
... |
concatenate if multiple input files for a single samples | def concat_reads(data, subsamples, ipyclient):
""" concatenate if multiple input files for a single samples """
## concatenate reads if they come from merged assemblies.
if any([len(i.files.fastqs) > 1 for i in subsamples]):
## run on single engine for now
start = time.time()
prints... |
sends fastq files to cutadapt | def run_cutadapt(data, subsamples, lbview):
"""
sends fastq files to cutadapt
"""
## choose cutadapt function based on datatype
start = time.time()
printstr = " processing reads | {} | s2 |"
finished = 0
rawedits = {}
## sort subsamples so that the biggest files get submitted f... |
filter out samples that are already done with this step unless force | def choose_samples(samples, force):
""" filter out samples that are already done with this step, unless force"""
## hold samples that pass
subsamples = []
## filter the samples again
if not force:
for sample in samples:
if sample.stats.state >= 2:
print("""\
... |
If multiple fastq files were appended into the list of fastqs for samples then we merge them here before proceeding. | def concat_multiple_inputs(data, sample):
"""
If multiple fastq files were appended into the list of fastqs for samples
then we merge them here before proceeding.
"""
## if more than one tuple in fastq list
if len(sample.files.fastqs) > 1:
## create a cat command to append them all (d... |
Convert vcf from step6 to. loci format to facilitate downstream format conversion | def make( data, samples ):
""" Convert vcf from step6 to .loci format to facilitate downstream format conversion """
invcffile = os.path.join( data.dirs.consens, data.name+".vcf" )
outlocifile = os.path.join( data.dirs.outfiles, data.name+".loci" )
importvcf( invcffile, outlocifile ) |
Function for importing a vcf file into loci format. Arguments are the input vcffile and the loci file to write out. | def importvcf( vcffile, locifile ):
""" Function for importing a vcf file into loci format. Arguments
are the input vcffile and the loci file to write out. """
try:
## Get names of all individuals in the vcf
with open( invcffile, 'r' ) as invcf:
for line in invcf:
... |
A function to find 2 engines per hostname on the ipyclient. We ll assume that the CPUs are hyperthreaded which is why we grab two. If they are not then no foul. Two multi - threaded jobs will be run on each of the 2 engines per host. | def get_targets(ipyclient):
"""
A function to find 2 engines per hostname on the ipyclient.
We'll assume that the CPUs are hyperthreaded, which is why
we grab two. If they are not then no foul. Two multi-threaded
jobs will be run on each of the 2 engines per host.
"""
## fill hosts with asy... |
compute stats for stats file and NHX tree features | def compute_tree_stats(self, ipyclient):
"""
compute stats for stats file and NHX tree features
"""
## get name indices
names = self.samples
## get majority rule consensus tree of weighted Q bootstrap trees
if self.params.nboots:
## Tree object
fulltre = ete3.Tree... |
Random selection from itertools. combinations ( iterable r ). Use this if not sampling all possible quartets. | def random_combination(iterable, nquartets):
"""
Random selection from itertools.combinations(iterable, r).
Use this if not sampling all possible quartets.
"""
pool = tuple(iterable)
size = len(pool)
indices = random.sample(xrange(size), nquartets)
return tuple(pool[i] for i in indices) |
random sampler for equal_splits func | def random_product(iter1, iter2):
""" random sampler for equal_splits func"""
pool1 = tuple(iter1)
pool2 = tuple(iter2)
ind1 = random.sample(pool1, 2)
ind2 = random.sample(pool2, 2)
return tuple(ind1+ind2) |
get the number of quartets as n - choose - k. This is used in equal splits to decide whether a split should be exhaustively sampled or randomly sampled. Edges near tips can be exhaustive while highly nested edges probably have too many quartets | def n_choose_k(n, k):
""" get the number of quartets as n-choose-k. This is used
in equal splits to decide whether a split should be exhaustively sampled
or randomly sampled. Edges near tips can be exhaustive while highly nested
edges probably have too many quartets
"""
return int(reduce(MUL, (F... |
get dstats from the count array and return as a float tuple | def count_snps(mat):
"""
get dstats from the count array and return as a float tuple
"""
## get [aabb, baba, abba, aaab]
snps = np.zeros(4, dtype=np.uint32)
## get concordant (aabb) pis sites
snps[0] = np.uint32(\
mat[0, 5] + mat[0, 10] + mat[0, 15] + \
mat[5, 0] +... |
removes ncolumns from snparray prior to matrix calculation and subsamples linked snps ( those from the same RAD locus ) such that for these four samples only 1 SNP per locus is kept. This information comes from the map array ( map file ). | def subsample_snps_map(seqchunk, nmask, maparr):
"""
removes ncolumns from snparray prior to matrix calculation, and
subsamples 'linked' snps (those from the same RAD locus) such that
for these four samples only 1 SNP per locus is kept. This information
comes from the 'map' array (map file).
... |
numba compiled code to get matrix fast. arr is a 4 x N seq matrix converted to np. int8 I convert the numbers for ATGC into their respective index for the MAT matrix and leave all others as high numbers i. e. - == 45 N == 78. | def chunk_to_matrices(narr, mapcol, nmask):
"""
numba compiled code to get matrix fast.
arr is a 4 x N seq matrix converted to np.int8
I convert the numbers for ATGC into their respective index for the MAT
matrix, and leave all others as high numbers, i.e., -==45, N==78.
"""
## get seq al... |
groups together several numba compiled funcs | def calculate(seqnon, mapcol, nmask, tests):
""" groups together several numba compiled funcs """
## create empty matrices
#LOGGER.info("tests[0] %s", tests[0])
#LOGGER.info('seqnon[[tests[0]]] %s', seqnon[[tests[0]]])
mats = chunk_to_matrices(seqnon, mapcol, nmask)
## empty svdscores for each... |
The workhorse function. Not numba. | def nworker(data, smpchunk, tests):
""" The workhorse function. Not numba. """
## tell engines to limit threads
#numba.config.NUMBA_DEFAULT_NUM_THREADS = 1
## open the seqarray view, the modified array is in bootsarr
with h5py.File(data.database.input, 'r') as io5:
seqview = io5["b... |
used in bootstrap resampling without a map file | def shuffle_cols(seqarr, newarr, cols):
""" used in bootstrap resampling without a map file """
for idx in xrange(cols.shape[0]):
newarr[:, idx] = seqarr[:, cols[idx]]
return newarr |
returns a seq array with RSKYWM randomly replaced with resolved bases | def resolve_ambigs(tmpseq):
""" returns a seq array with 'RSKYWM' randomly replaced with resolved bases"""
## iterate over the bases 'RSKWYM': [82, 83, 75, 87, 89, 77]
for ambig in np.uint8([82, 83, 75, 87, 89, 77]):
## get all site in this ambig
idx, idy = np.where(tmpseq == ambig)
... |
get span distance for each locus in original seqarray | def get_spans(maparr, spans):
""" get span distance for each locus in original seqarray """
## start at 0, finds change at 1-index of map file
bidx = 1
spans = np.zeros((maparr[-1, 0], 2), np.uint64)
## read through marr and record when locus id changes
for idx in xrange(1, maparr.shape[0]):
... |
get shape of new bootstrap resampled locus array | def get_shape(spans, loci):
""" get shape of new bootstrap resampled locus array """
width = 0
for idx in xrange(loci.shape[0]):
width += spans[loci[idx], 1] - spans[loci[idx], 0]
return width |
fills the new bootstrap resampled array | def fill_boot(seqarr, newboot, newmap, spans, loci):
""" fills the new bootstrap resampled array """
## column index
cidx = 0
## resample each locus
for i in xrange(loci.shape[0]):
## grab a random locus's columns
x1 = spans[loci[i]][0]
x2 = spans[loci[i]][1]
... |
converts unicode to utf - 8 when reading in json files | def _byteify(data, ignore_dicts=False):
"""
converts unicode to utf-8 when reading in json files
"""
if isinstance(data, unicode):
return data.encode("utf-8")
if isinstance(data, list):
return [_byteify(item, ignore_dicts=True) for item in data]
if isinstance(data, dict) and no... |
An extended majority rule consensus function for ete3. Modelled on the similar function from scikit - bio tree module. If cutoff = 0. 5 then it is a normal majority rule consensus while if cutoff = 0. 0 then subsequent non - conflicting clades are added to the tree. | def consensus_tree(trees, names=None, cutoff=0.0):
"""
An extended majority rule consensus function for ete3.
Modelled on the similar function from scikit-bio tree module. If
cutoff=0.5 then it is a normal majority rule consensus, while if
cutoff=0.0 then subsequent non-conflicting clades are ad... |
A subfunc of consensus_tree (). Removes clades that occur with freq < cutoff. | def _filter_clades(clade_counts, cutoff):
"""
A subfunc of consensus_tree(). Removes clades that occur
with freq < cutoff.
"""
## store clades that pass filter
passed = []
clades = np.array([list(i[0]) for i in clade_counts], dtype=np.int8)
counts = np.array([i[1] for i in clade_count... |
Remove all existing results files and reinit the h5 arrays so that the tetrad object is just like fresh from a CLI start. | def refresh(self):
"""
Remove all existing results files and reinit the h5 arrays
so that the tetrad object is just like fresh from a CLI start.
"""
## clear any existing results files
oldfiles = [self.files.qdump] + \
self.database.__dict__.values(... |
parse sample names from the sequence file | def _parse_names(self):
""" parse sample names from the sequence file"""
self.samples = []
with iter(open(self.files.data, 'r')) as infile:
infile.next().strip().split()
while 1:
try:
self.samples.append(infile.next().split()[0])
... |
Fills the seqarr with the full data set and creates a bootsarr copy with the following modifications: | def _init_seqarray(self, quiet=False):
"""
Fills the seqarr with the full data set, and creates a bootsarr copy
with the following modifications:
1) converts "-" into "N"s, since they are similarly treated as missing.
2) randomly resolve ambiguities (RSKWYM)
3) convert... |
Find all quartets of samples and store in a large array Create a chunk size for sampling from the array of quartets. This should be relatively large so that we don t spend a lot of time doing I/ O but small enough that jobs finish often for checkpointing. | def _store_N_samples(self, ncpus):
"""
Find all quartets of samples and store in a large array
Create a chunk size for sampling from the array of quartets.
This should be relatively large so that we don't spend a lot of time
doing I/O, but small enough that jobs finish often f... |
sample quartets evenly across splits of the starting tree and fills in remaining samples with random quartet samples. Uses a hash dict to not sample the same quartet twice so for very large trees this can take a few minutes to find millions of possible quartet samples. | def _store_equal_samples(self, ncpus):
"""
sample quartets evenly across splits of the starting tree, and fills
in remaining samples with random quartet samples. Uses a hash dict to
not sample the same quartet twice, so for very large trees this can
take a few minutes to find ... |
runs quartet max - cut on a quartets file | def _run_qmc(self, boot):
""" runs quartet max-cut on a quartets file """
## convert to txt file for wQMC
self._tmp = os.path.join(self.dirs, ".tmpwtre")
cmd = [ip.bins.qmc, "qrtt="+self.files.qdump, "otre="+self._tmp]
## run them
proc = subprocess.Popen(cmd, stderr=su... |
Makes a reduced array that excludes quartets with no information and prints the quartets and weights to a file formatted for wQMC | def _dump_qmc(self):
"""
Makes a reduced array that excludes quartets with no information and
prints the quartets and weights to a file formatted for wQMC
"""
## open the h5 database
io5 = h5py.File(self.database.output, 'r')
## create an output file for writi... |
renames newick from numbers to sample names | def _renamer(self, tre):
""" renames newick from numbers to sample names"""
## get the tre with numbered tree tip labels
names = tre.get_leaves()
## replace numbered names with snames
for name in names:
name.name = self.samples[int(name.name)]
## return with... |
write final tree files | def _finalize_stats(self, ipyclient):
""" write final tree files """
## print stats file location:
#print(STATSOUT.format(opr(self.files.stats)))
## print finished tree information ---------------------
print(FINALTREES.format(opr(self.trees.tree)))
## print bootstrap ... |
save a JSON file representation of Tetrad Class for checkpoint | def _save(self):
""" save a JSON file representation of Tetrad Class for checkpoint"""
## save each attribute as dict
fulldict = copy.deepcopy(self.__dict__)
for i, j in fulldict.items():
if isinstance(j, Params):
fulldict[i] = j.__dict__
fulldumps = ... |
inputs results from workers into hdf4 array | def _insert_to_array(self, start, results):
""" inputs results from workers into hdf4 array """
qrts, wgts, qsts = results
#qrts, wgts = results
#print(qrts)
with h5py.File(self.database.output, 'r+') as out:
chunk = self._chunksize
out['quartets'][start:... |
Run quartet inference on a SNP alignment and distribute work across an ipyparallel cluster ( ipyclient ). Unless passed an ipyclient explicitly it looks for a running ipcluster instance running from the defautl ( ) profile and will raise an exception if one is not found within a set time limit. If not using the default... | def run(self, force=0, verbose=2, ipyclient=None):
"""
Run quartet inference on a SNP alignment and distribute work
across an ipyparallel cluster (ipyclient). Unless passed an
ipyclient explicitly, it looks for a running ipcluster instance
running from the defautl ("") profile,... |
Inference sends slices of jobs to the parallel engines for computing and collects the results into the output hdf5 array as they finish. | def _inference(self, start, lbview, quiet=False):
"""
Inference sends slices of jobs to the parallel engines for computing
and collects the results into the output hdf5 array as they finish.
"""
## an iterator to distribute sampled quartets in chunks
gen = xrange(self.... |
Check all samples requested have been clustered ( state = 6 ) make output directory then create the requested outfiles. Excluded samples are already removed from samples. | def run(data, samples, force, ipyclient):
"""
Check all samples requested have been clustered (state=6), make output
directory, then create the requested outfiles. Excluded samples are already
removed from samples.
"""
## prepare dirs
data.dirs.outfiles = os.path.join(data.dirs.project, dat... |
write the output stats file and save to Assembly obj. | def make_stats(data, samples, samplecounts, locuscounts):
""" write the output stats file and save to Assembly obj."""
## get meta info
with h5py.File(data.clust_database, 'r') as io5:
anames = io5["seqs"].attrs["samples"]
nloci = io5["seqs"].shape[0]
optim = io5["seqs"].attrs["chun... |
Get the row index of samples that are included. If samples are in the excluded they were already filtered out of samples during _get_samples. | def select_samples(dbsamples, samples, pidx=None):
"""
Get the row index of samples that are included. If samples are in the
'excluded' they were already filtered out of 'samples' during _get_samples.
"""
## get index from dbsamples
samples = [i.name for i in samples]
if pidx:
sidx =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.