INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Open the clust_database HDF5 array with seqs catg and filter data. Fill the remaining filters.
def filter_all_clusters(data, samples, ipyclient): """ Open the clust_database HDF5 array with seqs, catg, and filter data. Fill the remaining filters. """ ## create loadbalanced ipyclient lbview = ipyclient.load_balanced_view() ## get chunk size from the HD5 array and close with h5py....
pads names for loci output
def padnames(names): """ pads names for loci output """ ## get longest name longname_len = max(len(i) for i in names) ## Padding distance between name and seq. padding = 5 ## add pad to names pnames = [name + " " * (longname_len - len(name)+ padding) \ for name in names] s...
Makes the. loci file from h5 data base. Iterates by optim loci at a time and write to file. Also makes alleles file if requested.
def make_loci_and_stats(data, samples, ipyclient): """ Makes the .loci file from h5 data base. Iterates by optim loci at a time and write to file. Also makes alleles file if requested. """ ## start vcf progress bar start = time.time() printstr = " building loci/stats | {} | s7 |" elaps...
Function from make_loci to apply to chunks. smask is sample mask.
def locichunk(args): """ Function from make_loci to apply to chunks. smask is sample mask. """ ## parse args data, optim, pnames, snppad, smask, start, samplecov, locuscov, upper = args ## this slice hslice = [start, start+optim] ## get filter db info co5 = h5py.File(data.database,...
enters funcs for pairs
def enter_pairs(iloc, pnames, snppad, edg, aseqs, asnps, smask, samplecov, locuscov, start): """ enters funcs for pairs """ ## snps was created using only the selected samples. LOGGER.info("edges in enter_pairs %s", edg) seq1 = aseqs[iloc, :, edg[0]:edg[1]+1] snp1 = asnps[iloc, edg[0]:edg[1]+1, ] ...
enter funcs for SE or merged data
def enter_singles(iloc, pnames, snppad, edg, aseqs, asnps, smask, samplecov, locuscov, start): """ enter funcs for SE or merged data """ ## grab all seqs between edges seq = aseqs[iloc, :, edg[0]:edg[1]+1] ## snps was created using only the selected samples, and is edge masked. ## The mask is for c...
Create database file for storing final filtered snps data as hdf5 array. Copies splits and duplicates info from clust_database to database.
def init_arrays(data): """ Create database file for storing final filtered snps data as hdf5 array. Copies splits and duplicates info from clust_database to database. """ ## get stats from step6 h5 and create new h5 co5 = h5py.File(data.clust_database, 'r') io5 = h5py.File(data.database, 'w...
Grab a chunk of loci from the HDF5 database. Apply filters and fill the the filters boolean array.
def filter_stacks(data, sidx, hslice): """ Grab a chunk of loci from the HDF5 database. Apply filters and fill the the filters boolean array. The design of the filtering steps intentionally sacrifices some performance for an increase in readability, and extensibility. Calling multiple filter fu...
Gets edge trimming based on the overlap of sequences at the edges of alignments and the tuple arg passed in for edge_trimming. Trims as ( R1 left R1 right R2 left R2 right ). We also trim off the restriction site if it present. This modifies superints and so should be run on an engine so it doesn t affect local copy. I...
def get_edges(data, superints, splits): """ Gets edge trimming based on the overlap of sequences at the edges of alignments and the tuple arg passed in for edge_trimming. Trims as (R1 left, R1 right, R2 left, R2 right). We also trim off the restriction site if it present. This modifies superints, an...
Filter minimum # of samples per locus from superseqs [ chunk ]. The shape of superseqs is [ chunk sum ( sidx ) maxlen ]
def filter_minsamp(data, superints): """ Filter minimum # of samples per locus from superseqs[chunk]. The shape of superseqs is [chunk, sum(sidx), maxlen] """ ## global minsamp minsamp = data.paramsdict["min_samples_locus"] ## use population minsamps if data.populations: ## data...
Used to count the number of unique bases in a site for snpstring. returns as a spstring with * and -
def ucount(sitecol): """ Used to count the number of unique bases in a site for snpstring. returns as a spstring with * and - """ ## a list for only catgs catg = [i for i in sitecol if i in "CATG"] ## find sites that are ambigs where = [sitecol[sitecol == i] for i in "RSKYWM"] ## ...
Filter max # of SNPs per locus. Do R1 and R2 separately if PE. Also generate the snpsite line for the. loci format and save in the snp arr This uses the edge filters that have been built based on trimming and saves the snps array with edges filtered. ** Loci are not yet filtered. **
def filter_maxsnp(data, superints, edgearr): """ Filter max # of SNPs per locus. Do R1 and R2 separately if PE. Also generate the snpsite line for the .loci format and save in the snp arr This uses the edge filters that have been built based on trimming, and saves the snps array with edges filtered....
Used to count the number of unique bases in a site for snpstring.
def snpcount_numba(superints, snpsarr): """ Used to count the number of unique bases in a site for snpstring. """ ## iterate over all loci for iloc in xrange(superints.shape[0]): for site in xrange(superints.shape[2]): ## make new array catg = np.zeros(4, dtype=np.in...
Filter max shared heterozygosity per locus. The dimensions of superseqs are ( chunk sum ( sidx ) maxlen ). Don t need split info since it applies to entire loci based on site patterns ( i. e. location along the seq doesn t matter. ) Current implementation does ints but does not apply float diff to every loc based on co...
def filter_maxhet(data, superints, edgearr): """ Filter max shared heterozygosity per locus. The dimensions of superseqs are (chunk, sum(sidx), maxlen). Don't need split info since it applies to entire loci based on site patterns (i.e., location along the seq doesn't matter.) Current implementation ...
Filter max indels. Needs to split to apply to each read separately. The dimensions of superseqs are ( chunk sum ( sidx ) maxlen ).
def filter_indels(data, superints, edgearr): """ Filter max indels. Needs to split to apply to each read separately. The dimensions of superseqs are (chunk, sum(sidx), maxlen). """ maxinds = np.array(data.paramsdict["max_Indels_locus"]).astype(np.int64) ## an empty array to fill with failed lo...
filter for indels
def maxind_numba(block): """ filter for indels """ ## remove terminal edges inds = 0 for row in xrange(block.shape[0]): where = np.where(block[row] != 45)[0] if len(where) == 0: obs = 100 else: left = np.min(where) right = np.max(where) ...
Get desired formats from paramsdict and write files to outfiles directory.
def make_outfiles(data, samples, output_formats, ipyclient): """ Get desired formats from paramsdict and write files to outfiles directory. """ ## will iterate optim loci at a time with h5py.File(data.clust_database, 'r') as io5: optim = io5["seqs"].attrs["chunksize"][0] nloci =...
Parallelized worker to build array chunks for output files. One main goal here is to keep seqarr to less than ~1GB RAM.
def worker_make_arrays(data, sidx, hslice, optim, maxlen): """ Parallelized worker to build array chunks for output files. One main goal here is to keep seqarr to less than ~1GB RAM. """ ## big data arrays io5 = h5py.File(data.clust_database, 'r') co5 = h5py.File(data.database, 'r') ...
write the phylip output file from the tmparr [ seqarray ]
def write_phy(data, sidx, pnames): """ write the phylip output file from the tmparr[seqarray] """ ## grab seq data from tmparr start = time.time() tmparrs = os.path.join(data.dirs.outfiles, "tmp-{}.h5".format(data.name)) with h5py.File(tmparrs, 'r') as io5: seqarr = io5["seqarr"]...
write the nexus output file from the tmparr [ seqarray ] and tmparr [ maparr ]
def write_nex(data, sidx, pnames): """ write the nexus output file from the tmparr[seqarray] and tmparr[maparr] """ ## grab seq data from tmparr start = time.time() tmparrs = os.path.join(data.dirs.outfiles, "tmp-{}.h5".format(data.name)) with h5py.File(tmparrs, 'r') as io5: s...
write a map file with linkage information for SNPs file
def write_snps_map(data): """ write a map file with linkage information for SNPs file""" ## grab map data from tmparr start = time.time() tmparrs = os.path.join(data.dirs.outfiles, "tmp-{}.h5".format(data.name)) with h5py.File(tmparrs, 'r') as io5: maparr = io5["maparr"][:] ## get...
write the bisnp string
def write_usnps(data, sidx, pnames): """ write the bisnp string """ ## grab bis data from tmparr tmparrs = os.path.join(data.dirs.outfiles, "tmp-{}.h5".format(data.name)) with h5py.File(tmparrs, 'r') as io5: bisarr = io5["bisarr"] ## trim to size b/c it was made longer than actual ...
Write STRUCTURE format for all SNPs and unlinked SNPs
def write_str(data, sidx, pnames): """ Write STRUCTURE format for all SNPs and unlinked SNPs """ ## grab snp and bis data from tmparr start = time.time() tmparrs = os.path.join(data.dirs.outfiles, "tmp-{}.h5".format(data.name)) with h5py.File(tmparrs, 'r') as io5: snparr = io5["snparr"] ...
write the geno output formerly used by admixture still supported by adegenet perhaps. Also sNMF still likes. geno.
def write_geno(data, sidx): """ write the geno output formerly used by admixture, still supported by adegenet, perhaps. Also, sNMF still likes .geno. """ ## grab snp and bis data from tmparr start = time.time() tmparrs = os.path.join(data.dirs.outfiles, "tmp-{}.h5".format(data.name)) ...
write the g - phocs output. This code is hella ugly bcz it s copy/ pasted directly from the old loci2gphocs script from pyrad. I figure having it get done the stupid way is better than not having it done at all at least for the time being. This could probably be sped up significantly.
def write_gphocs(data, sidx): """ write the g-phocs output. This code is hella ugly bcz it's copy/pasted directly from the old loci2gphocs script from pyrad. I figure having it get done the stupid way is better than not having it done at all, at least for the time being. This could probably be sped ...
Write the full VCF for loci passing filtering. Other vcf formats are possible like SNPs - only or with filtered loci included but the filter explicitly labeled. These are not yet supported however.
def make_vcf(data, samples, ipyclient, full=0): """ Write the full VCF for loci passing filtering. Other vcf formats are possible, like SNPs-only, or with filtered loci included but the filter explicitly labeled. These are not yet supported, however. """ ## start vcf progress bar start = tim...
Sorts concatenates and gzips VCF chunks. Also cleans up chunks.
def concat_vcf(data, names, full): """ Sorts, concatenates, and gzips VCF chunks. Also cleans up chunks. """ ## open handle and write headers if not full: writer = open(data.outfiles.vcf, 'w') else: writer = gzip.open(data.outfiles.VCF, 'w') vcfheader(data, names, writer) ...
Function called within make_vcf to run chunks on separate engines.
def vcfchunk(data, optim, sidx, chunk, full): """ Function called within make_vcf to run chunks on separate engines. """ ## empty array to be filled before writing ## will not actually be optim*maxlen, extra needs to be trimmed maxlen = data._hackersonly["max_fragment_length"] + 20 ## get d...
Returns the most common base at each site in order.
def reftrick(iseq, consdict): """ Returns the most common base at each site in order. """ altrefs = np.zeros((iseq.shape[1], 4), dtype=np.uint8) altrefs[:, 1] = 46 for col in xrange(iseq.shape[1]): ## expand colums with ambigs and remove N- fcounts = np.zeros(111, dtype=np.int64) ...
Prints header for vcf files
def vcfheader(data, names, ofile): """ Prints header for vcf files """ ## choose reference string if data.paramsdict["reference_sequence"]: reference = data.paramsdict["reference_sequence"] else: reference = "pseudo-reference (most common base at site)" ##FILTER=<ID=minCov,...
Converts loci file format to bpp file format i. e. concatenated phylip - like format and produces imap and ctl input files for bpp.
def loci2bpp(name, locifile, imap, guidetree, minmap=None, maxloci=None, infer_sptree=0, infer_delimit=0, delimit_alg=(0, 5), seed=12345, burnin=1000, nsample=10000, sampfreq=2, thetaprior=(5, 5), tauprior=(4, 2, 1), traits_df=None, nu=0, kappa=0, useseqdata=1...
write outfile with any args in argdict
def write_ctl(name, imap, guidetree, nloci, infer_sptree, infer_delimit, delimit_alg, seed, burnin, nsample, sampfreq, thetaprior, tauprior, traits_df, nu0, kappa0, cleandata, useseqdata, usetraitdata, wdir, finetune, verbose): """ write outfile...
collapse outgroup in ete Tree for easier viewing
def _collapse_outgroup(tree, taxdicts): """ collapse outgroup in ete Tree for easier viewing """ ## check that all tests have the same outgroup outg = taxdicts[0]["p4"] if not all([i["p4"] == outg for i in taxdicts]): raise Exception("no good") ## prune tree, keep only one sample from ou...
decomposes tree into component parts for plotting
def _decompose_tree(ttree, orient='right', use_edge_lengths=True): """ decomposes tree into component parts for plotting """ ## set attributes ttree._orient = orient ttree._use_edge_lengths = use_edge_lengths ult = use_edge_lengths == False ## map numeric values to internal nodes from root to...
plot the tree using toyplot. graph.
def draw( self, show_tip_labels=True, show_node_support=False, use_edge_lengths=False, orient="right", print_args=False, *args, **kwargs): """ plot the tree using toyplot.graph. Parameters: ----------- show_...
signature...
def tree_panel_plot(ttree, print_args=False, *args, **kwargs): """ signature... """ ## create Panel plot object and set height & width panel = Panel(ttree) #tree, edges, verts, names) if not kwargs.get("width"): panel.kwargs["width"] = min(1000, 25*len(panel.tree))...
iterate over clustS files to get data
def get_quick_depths(data, sample): """ iterate over clustS files to get data """ ## use existing sample cluster path if it exists, since this ## func can be used in step 4 and that can occur after merging ## assemblies after step3, and if we then referenced by data.dirs.clusts ## the path would be...
stats cleanup and link to samples
def sample_cleanup(data, sample): """ stats, cleanup, and link to samples """ ## get maxlen and depths array from clusters maxlens, depths = get_quick_depths(data, sample) try: depths.max() except ValueError: ## If depths is an empty array max() will raise print(" no clu...
keeps a persistent bash shell open and feeds it muscle alignments
def persistent_popen_align3(clusts, maxseqs=200, is_gbs=False): """ keeps a persistent bash shell open and feeds it muscle alignments """ ## create a separate shell for running muscle in, this is much faster ## than spawning a separate subprocess for each muscle call proc = sps.Popen(["bash"], ...
No reads can go past the left of the seed or right of the least extended reverse complement match. Example below. m is a match. u is an area where lots of mismatches typically occur. The cut sites are shown. Original locus * Seed TGCAG ************************************ ----------------------- Forward - match TGCAGmm...
def gbs_trim(align1): """ No reads can go past the left of the seed, or right of the least extended reverse complement match. Example below. m is a match. u is an area where lots of mismatches typically occur. The cut sites are shown. Original locus* Seed TGCAG*******************...
much faster implementation for aligning chunks
def align_and_parse(handle, max_internal_indels=5, is_gbs=False): """ much faster implementation for aligning chunks """ ## data are already chunked, read in the whole thing. bail if no data. try: with open(handle, 'rb') as infile: clusts = infile.read().split("//\n//\n") ##...
checks for too many internal indels in muscle aligned clusters
def aligned_indel_filter(clust, max_internal_indels): """ checks for too many internal indels in muscle aligned clusters """ ## make into list lclust = clust.split() ## paired or not try: seq1 = [i.split("nnnn")[0] for i in lclust[1::2]] seq2 = [i.split("nnnn")[1] for i in lclu...
Combines information from. utemp and. htemp files to create. clust files which contain un - aligned clusters. Hits to seeds are only kept in the cluster if the number of internal indels is less than maxindels. By default we set maxindels = 6 for this step ( within - sample clustering ).
def build_clusters(data, sample, maxindels): """ Combines information from .utemp and .htemp files to create .clust files, which contain un-aligned clusters. Hits to seeds are only kept in the cluster if the number of internal indels is less than 'maxindels'. By default, we set maxindels=6 for this ...
sets up directories for step3 data
def setup_dirs(data): """ sets up directories for step3 data """ ## make output folder for clusters pdir = os.path.realpath(data.paramsdict["project_dir"]) data.dirs.clusts = os.path.join(pdir, "{}_clust_{}"\ .format(data.name, data.paramsdict["clust_threshold"])) if not os.pa...
Create a DAG of prealign jobs to be run in order for each sample. Track Progress report errors. Each assembly method has a slightly different DAG setup calling different functions.
def new_apply_jobs(data, samples, ipyclient, nthreads, maxindels, force): """ Create a DAG of prealign jobs to be run in order for each sample. Track Progress, report errors. Each assembly method has a slightly different DAG setup, calling different functions. """ ## is datatype gbs? used in al...
build a directed acyclic graph describing jobs to be run in order.
def build_dag(data, samples): """ build a directed acyclic graph describing jobs to be run in order. """ ## Create DAGs for the assembly method being used, store jobs in nodes snames = [i.name for i in samples] dag = nx.DiGraph() ## get list of pre-align jobs from globals based on assembly...
makes plot to help visualize the DAG setup. For developers only.
def _plot_dag(dag, results, snames): """ makes plot to help visualize the DAG setup. For developers only. """ try: import matplotlib.pyplot as plt from matplotlib.dates import date2num from matplotlib.cm import gist_rainbow ## first figure is dag layout plt.figur...
Blocks and prints progress for just the func being requested from a list of submitted engine jobs. Returns whether any of the jobs failed.
def trackjobs(func, results, spacer): """ Blocks and prints progress for just the func being requested from a list of submitted engine jobs. Returns whether any of the jobs failed. func = str results = dict of asyncs """ ## TODO: try to insert a better way to break on KBD here. LOGGER....
3rad uses random adapters to identify pcr duplicates. We will remove pcr dupes here. Basically append the radom adapter to each sequence do a regular old vsearch derep then trim off the adapter and push it down the pipeline. This will remove all identical seqs with identical random i5 adapters.
def declone_3rad(data, sample): """ 3rad uses random adapters to identify pcr duplicates. We will remove pcr dupes here. Basically append the radom adapter to each sequence, do a regular old vsearch derep, then trim off the adapter, and push it down the pipeline. This will remove all identical s...
Dereplicates reads and sorts so reads that were highly replicated are at the top and singletons at bottom writes output to derep file. Paired reads are dereplicated as one concatenated read and later split again. Updated this function to take infile and outfile to support the double dereplication that we need for 3rad ...
def derep_and_sort(data, infile, outfile, nthreads): """ Dereplicates reads and sorts so reads that were highly replicated are at the top, and singletons at bottom, writes output to derep file. Paired reads are dereplicated as one concatenated read and later split again. Updated this function to tak...
cleanup/ statswriting function for Assembly obj
def data_cleanup(data): """ cleanup / statswriting function for Assembly obj """ data.stats_dfs.s3 = data._build_stat("s3") data.stats_files.s3 = os.path.join(data.dirs.clusts, "s3_cluster_stats.txt") with io.open(data.stats_files.s3, 'w') as outfile: data.stats_dfs.s3.to_string( buf...
if multiple fastq files were appended into the list of fastqs for samples then we merge them here before proceeding.
def concat_multiple_edits(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.edits) > 1: ## create a cat command to append them all (doesn...
Calls vsearch for clustering. cov varies by data type values were chosen based on experience but could be edited by users
def cluster(data, sample, nthreads, force): """ Calls vsearch for clustering. cov varies by data type, values were chosen based on experience, but could be edited by users """ ## get the dereplicated reads if "reference" in data.paramsdict["assembly_method"]: derephandle = os.path.join(...
Splits the muscle alignment into chunks. Each chunk is run on a separate computing core. Because the largest clusters are at the beginning of the clusters file assigning equal clusters to each file would put all of the large cluster that take longer to align near the top. So instead we randomly distribute the clusters ...
def muscle_chunker(data, sample): """ Splits the muscle alignment into chunks. Each chunk is run on a separate computing core. Because the largest clusters are at the beginning of the clusters file, assigning equal clusters to each file would put all of the large cluster, that take longer to align...
takes aligned chunks ( usually 10 ) and concatenates them
def reconcat(data, sample): """ takes aligned chunks (usually 10) and concatenates them """ try: ## get chunks chunks = glob.glob(os.path.join(data.tmpdir, sample.name+"_chunk_[0-9].aligned")) ## sort by chunk number, cuts off last 8 =(aligned) chunks.sort(key=...
Running on remote Engine. Refmaps then merges then dereplicates then denovo clusters reads.
def derep_concat_split(data, sample, nthreads, force): """ Running on remote Engine. Refmaps, then merges, then dereplicates, then denovo clusters reads. """ ## report location for debugging LOGGER.info("INSIDE derep %s", sample.name) ## MERGED ASSEMBIES ONLY: ## concatenate edits file...
run the major functions for clustering within samples
def run(data, samples, noreverse, maxindels, force, ipyclient): """ run the major functions for clustering within samples """ ## list of samples to submit to queue subsamples = [] ## if sample is already done skip for sample in samples: ## If sample not in state 2 don't try to cluster it. ...
Parse the params file args create and return Assembly object.
def parse_params(args): """ Parse the params file args, create and return Assembly object.""" ## check that params.txt file is correctly formatted. try: with open(args.params) as paramsin: plines = paramsin.readlines() except IOError as _: sys.exit(" No params file found") ...
loads assembly or dies and print stats to screen
def showstats(parsedict): """ loads assembly or dies, and print stats to screen """ #project_dir = parsedict['1'] project_dir = parsedict["project_dir"] if not project_dir: project_dir = "./" ## Be nice if somebody also puts in the file extension #assembly_name = parsedict['0'] asse...
Load the passed in assembly and create a branch. Copy it to a new assembly and also write out the appropriate params. txt
def branch_assembly(args, parsedict): """ Load the passed in assembly and create a branch. Copy it to a new assembly, and also write out the appropriate params.txt """ ## Get the current assembly data = getassembly(args, parsedict) ## get arguments to branch command bargs = args.bran...
merge all given assemblies into a new assembly. Copies the params from the first passed in extant assembly. this function is called with the ipyrad - m flag. You must pass it at least 3 values the first is a new assembly name ( a new param - newname. txt will be created ). The second and third args must be params files...
def merge_assemblies(args): """ merge all given assemblies into a new assembly. Copies the params from the first passed in extant assembly. this function is called with the ipyrad -m flag. You must pass it at least 3 values, the first is a new assembly name (a new `param-newname.txt` will be creat...
loads assembly or creates a new one and set its params from parsedict. Does not launch ipcluster.
def getassembly(args, parsedict): """ loads assembly or creates a new one and set its params from parsedict. Does not launch ipcluster. """ ## Creating an assembly with a full path in the name will "work" ## but it is potentially dangerous, so here we have assembly_name ## and assembly_f...
Test if there s a newer version and nag the user to upgrade.
def _check_version(): """ Test if there's a newer version and nag the user to upgrade.""" import urllib2 from distutils.version import LooseVersion header = \ "\n -------------------------------------------------------------"+\ "\n ipyrad [v.{}]".format(ip.__version__)+\ "\n Interactive a...
main function
def main(): """ main function """ ## turn off traceback for the CLI ip.__interactive__ = 0 ## Check for a new version on anaconda _check_version() ## parse params file input (returns to stdout if --help or --version) args = parse_command_line() ## Turn the debug output written to ipyr...
return probability of base call
def get_binom(base1, base2, estE, estH): """ return probability of base call """ prior_homo = (1. - estH) / 2. prior_hete = estH ## calculate probs bsum = base1 + base2 hetprob = scipy.misc.comb(bsum, base1)/(2. **(bsum)) homoa = scipy.stats.binom.pmf(base2, bsum, estE)...
Checks for interior Ns in consensus seqs and removes those that are at low depth here defined as less than 1/ 3 of the average depth. The prop 1/ 3 is chosen so that mindepth = 6 requires 2 base calls that are not in [ N - ].
def removerepeats(consens, arrayed): """ Checks for interior Ns in consensus seqs and removes those that are at low depth, here defined as less than 1/3 of the average depth. The prop 1/3 is chosen so that mindepth=6 requires 2 base calls that are not in [N,-]. """ ## default trim no edges ...
new faster replacement to consensus
def newconsensus(data, sample, tmpchunk, optim): """ new faster replacement to consensus """ ## do reference map funcs? isref = "reference" in data.paramsdict["assembly_method"] ## temporarily store the mean estimates to Assembly data._este = data.stats.error_est.mean() data._esth = d...
call all sites in a locus array.
def basecaller(arrayed, mindepth_majrule, mindepth_statistical, estH, estE): """ call all sites in a locus array. """ ## an array to fill with consensus site calls cons = np.zeros(arrayed.shape[1], dtype=np.uint8) cons.fill(78) arr = arrayed.view(np.uint8) ## iterate over columns ...
applies read depths filter
def nfilter1(data, reps): """ applies read depths filter """ if sum(reps) >= data.paramsdict["mindepth_majrule"] and \ sum(reps) <= data.paramsdict["maxdepth"]: return 1 else: return 0
applies max haplotypes filter returns pass and consens
def nfilter4(consens, hidx, arrayed): """ applies max haplotypes filter returns pass and consens""" ## if less than two Hs then there is only one allele if len(hidx) < 2: return consens, 1 ## store base calls for hetero sites harray = arrayed[:, hidx] ## remove any reads that have N o...
store phased allele data for diploids
def storealleles(consens, hidx, alleles): """ store phased allele data for diploids """ ## find the first hetero site and choose the priority base ## example, if W: then priority base in A and not T. PRIORITY=(order: CATG) bigbase = PRIORITY[consens[hidx[0]]] ## find which allele has priority based...
cleaning up. optim is the size ( nloci ) of tmp arrays
def cleanup(data, sample, statsdicts): """ cleaning up. optim is the size (nloci) of tmp arrays """ LOGGER.info("in cleanup for: %s", sample.name) isref = 'reference' in data.paramsdict["assembly_method"] ## collect consens chunk files combs1 = glob.glob(os.path.join( ...
split job into bits and pass to the client
def chunk_clusters(data, sample): """ split job into bits and pass to the client """ ## counter for split job submission num = 0 ## set optim size for chunks in N clusters. The first few chunks take longer ## because they contain larger clusters, so we create 4X as many chunks as ## processors...
Apply state ncluster and force filters to select samples to be run.
def get_subsamples(data, samples, force): """ Apply state, ncluster, and force filters to select samples to be run. """ subsamples = [] for sample in samples: if not force: if sample.stats.state >= 5: print("""\ Skipping Sample {}; Already has consens reads. ...
checks if the sample should be run and passes the args
def run(data, samples, force, ipyclient): """ checks if the sample should be run and passes the args """ ## prepare dirs data.dirs.consens = os.path.join(data.dirs.project, data.name+"_consens") if not os.path.exists(data.dirs.consens): os.mkdir(data.dirs.consens) ## zap any tmp files that ...
check whether mindepth has changed and thus whether clusters_hidepth needs to be recalculated and get new maxlen for new highdepth clusts. if mindepth not changed then nothing changes.
def calculate_depths(data, samples, lbview): """ check whether mindepth has changed, and thus whether clusters_hidepth needs to be recalculated, and get new maxlen for new highdepth clusts. if mindepth not changed then nothing changes. """ ## send jobs to be processed on engines start = tim...
calls chunk_clusters and tracks progress.
def make_chunks(data, samples, lbview): """ calls chunk_clusters and tracks progress. """ ## first progress bar start = time.time() printstr = " chunking clusters | {} | s5 |" elapsed = datetime.timedelta(seconds=int(time.time()-start)) progressbar(10, 0, printstr.format(elapsed), sp...
submit chunks to consens func and...
def process_chunks(data, samples, lasyncs, lbview): """ submit chunks to consens func and ... """ ## send chunks to be processed start = time.time() asyncs = {sample.name:[] for sample in samples} printstr = " consens calling | {} | s5 |" ## get chunklist from results for sam...
reads in. loci and builds alleles from case characters
def make(data, samples): """ reads in .loci and builds alleles from case characters """ #read in loci file outfile = open(os.path.join(data.dirs.outfiles, data.name+".alleles"), 'w') lines = open(os.path.join(data.dirs.outfiles, data.name+".loci"), 'r') ## Get the longest sample name for prett...
builds snps output
def make(data, samples): """ builds snps output """ ## get attr ploidy = data.paramsdict["max_alleles_consens"] names = [i.name for i in samples] longname = max([len(i) for i in names]) ## TODO: use iter cuz of super huge files inloci = open(os.path.join(\ data.dirs.outf...
reports host and engine info for an ipyclient
def cluster_info(ipyclient, spacer=""): """ reports host and engine info for an ipyclient """ ## get engine data, skips busy engines. hosts = [] for eid in ipyclient.ids: engine = ipyclient[eid] if not engine.outstanding: hosts.append(engine.apply(_socket.gethostname)...
Turns on debugging by creating hidden tmp file This is only run by the __main__ engine.
def _debug_on(): """ Turns on debugging by creating hidden tmp file This is only run by the __main__ engine. """ ## make tmp file and set loglevel for top-level init with open(__debugflag__, 'w') as dfile: dfile.write("wat") __loglevel__ = "DEBUG" _LOGGER.info("debugging turned o...
set the debug dict
def _set_debug_dict(__loglevel__): """ set the debug dict """ _lconfig.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': "%(asctime)s \t"\ +"pid=%(process)d \t"\ +"[%(filename)s]\t"\ ...
turns off debugging by removing hidden tmp file
def _debug_off(): """ turns off debugging by removing hidden tmp file """ if _os.path.exists(__debugflag__): _os.remove(__debugflag__) __loglevel__ = "ERROR" _LOGGER.info("debugging turned off") _set_debug_dict(__loglevel__)
check if dependency program is there
def _cmd_exists(cmd): """ check if dependency program is there """ return _subprocess.call("type " + cmd, shell=True, stdout=_subprocess.PIPE, stderr=_subprocess.PIPE) == 0
gets the right version of vsearch muscle and smalt depending on linux vs osx
def _getbins(): """ gets the right version of vsearch, muscle, and smalt depending on linux vs osx """ # Return error if system is 32-bit arch. # This is straight from the python docs: # https://docs.python.org/2/library/platform.html#cross-platform if not _sys.maxsize > 2**32: _sys.exi...
Worker to distribute work to jit funcs. Wraps everything on an engine to run single - threaded to maximize efficiency for multi - processing.
def nworker(data, chunk): """ Worker to distribute work to jit funcs. Wraps everything on an engine to run single-threaded to maximize efficiency for multi-processing. """ ## set the thread limit on the remote engine oldlimit = set_mkl_thread_limit(1) ## open seqarray view, the modif...
Populate array with all possible quartets. This allows us to sample from the total and also to continue from a checkpoint
def store_all(self): """ Populate array with all possible quartets. This allows us to sample from the total, and also to continue from a checkpoint """ with h5py.File(self.database.input, 'a') as io5: fillsets = io5["quartets"] ## generator for all quartet sets qiter = ite...
Populate array with random quartets sampled from a generator. Holding all sets in memory might take a lot but holding a very large list of random numbers for which ones to sample will fit into memory for most reasonable sized sets. So we ll load a list of random numbers in the range of the length of total sets that can...
def store_random(self): """ Populate array with random quartets sampled from a generator. Holding all sets in memory might take a lot, but holding a very large list of random numbers for which ones to sample will fit into memory for most reasonable sized sets. So we'll load a list of random nu...
Takes a tetrad class object and populates array with random quartets sampled equally among splits of the tree so that deep splits are not overrepresented relative to rare splits like those near the tips.
def store_equal(self): """ Takes a tetrad class object and populates array with random quartets sampled equally among splits of the tree so that deep splits are not overrepresented relative to rare splits, like those near the tips. """ with h5py.File(self.database.input, 'a') as io5: ...
Returns nsets unique random quartet sets sampled from n - choose - k without replacement combinations.
def random_combination(nsets, n, k): """ Returns nsets unique random quartet sets sampled from n-choose-k without replacement combinations. """ sets = set() while len(sets) < nsets: newset = tuple(sorted(np.random.choice(n, k, replace=False))) sets.add(newset) return tuple(se...
Random sampler for equal_splits functions
def random_product(iter1, iter2): """ Random sampler for equal_splits functions """ iter4 = np.concatenate([ np.random.choice(iter1, 2, replace=False), np.random.choice(iter2, 2, replace=False) ]) return iter4
Randomly resolve ambiguous bases. This is applied to each boot replicate so that over reps the random resolutions don t matter. Sites are randomly resolved so best for unlinked SNPs since otherwise linked SNPs are losing their linkage information... though it s not like we re using it anyways.
def resolve_ambigs(tmpseq): """ Randomly resolve ambiguous bases. This is applied to each boot replicate so that over reps the random resolutions don't matter. Sites are randomly resolved, so best for unlinked SNPs since otherwise linked SNPs are losing their linkage information... though it'...
set mkl thread limit and return old value so we can reset when finished.
def set_mkl_thread_limit(cores): """ set mkl thread limit and return old value so we can reset when finished. """ if "linux" in sys.platform: mkl_rt = ctypes.CDLL('libmkl_rt.so') else: mkl_rt = ctypes.CDLL('libmkl_rt.dylib') oldlimit = mkl_rt.mkl_get_max_threads() mkl_rt...
get total number of quartets possible for a split
def get_total(tots, node): """ get total number of quartets possible for a split""" if (node.is_leaf() or node.is_root()): return 0 else: ## Get counts on down edges. ## How to treat polytomies here? if len(node.children) > 2: down_r = node.children[0] ...
get total number of quartets sampled for a split
def get_sampled(data, totn, node): """ get total number of quartets sampled for a split""" ## convert tip names to ints names = sorted(totn) cdict = {name: idx for idx, name in enumerate(names)} ## skip some nodes if (node.is_leaf() or node.is_root()): return 0 else: ## ...
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 (). Traverses trees to count clade occurrences. Names are ordered by names else they are in the order of the first tree.
def find_clades(trees, names): """ A subfunc of consensus_tree(). Traverses trees to count clade occurrences. Names are ordered by names, else they are in the order of the first tree. """ ## index names from the first tree if not names: names = trees[0].get_leaf_names() ndict =...
A subfunc of consensus_tree (). Build an unrooted consensus tree from filtered clade counts.
def build_trees(fclade_counts, namedict): """ A subfunc of consensus_tree(). Build an unrooted consensus tree from filtered clade counts. """ ## storage nodes = {} idxarr = np.arange(len(fclade_counts[0][0])) queue = [] ## create dict of clade counts and set keys countdict =...
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...