_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q259300
sub_build_clustbits
validation
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...
python
{ "resource": "" }
q259301
cleanup_tempfiles
validation
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(...
python
{ "resource": "" }
q259302
assembly_cleanup
validation
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='...
python
{ "resource": "" }
q259303
parse_single_results
validation
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...
python
{ "resource": "" }
q259304
run2
validation
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( ...
python
{ "resource": "" }
q259305
concat_reads
validation
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...
python
{ "resource": "" }
q259306
run_cutadapt
validation
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...
python
{ "resource": "" }
q259307
concat_multiple_inputs
validation
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...
python
{ "resource": "" }
q259308
make
validation
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 )
python
{ "resource": "" }
q259309
importvcf
validation
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: ...
python
{ "resource": "" }
q259310
get_targets
validation
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...
python
{ "resource": "" }
q259311
compute_tree_stats
validation
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...
python
{ "resource": "" }
q259312
random_product
validation
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)
python
{ "resource": "" }
q259313
n_choose_k
validation
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...
python
{ "resource": "" }
q259314
count_snps
validation
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] +...
python
{ "resource": "" }
q259315
chunk_to_matrices
validation
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...
python
{ "resource": "" }
q259316
calculate
validation
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...
python
{ "resource": "" }
q259317
nworker
validation
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...
python
{ "resource": "" }
q259318
shuffle_cols
validation
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
python
{ "resource": "" }
q259319
resolve_ambigs
validation
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) ...
python
{ "resource": "" }
q259320
get_spans
validation
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]): ...
python
{ "resource": "" }
q259321
get_shape
validation
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
python
{ "resource": "" }
q259322
fill_boot
validation
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] ...
python
{ "resource": "" }
q259323
_byteify
validation
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...
python
{ "resource": "" }
q259324
Tetrad._parse_names
validation
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]) ...
python
{ "resource": "" }
q259325
Tetrad._run_qmc
validation
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...
python
{ "resource": "" }
q259326
Tetrad._dump_qmc
validation
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...
python
{ "resource": "" }
q259327
Tetrad._renamer
validation
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...
python
{ "resource": "" }
q259328
Tetrad._finalize_stats
validation
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 ...
python
{ "resource": "" }
q259329
Tetrad._save
validation
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 = ...
python
{ "resource": "" }
q259330
Tetrad._insert_to_array
validation
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:...
python
{ "resource": "" }
q259331
select_samples
validation
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 =...
python
{ "resource": "" }
q259332
padnames
validation
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...
python
{ "resource": "" }
q259333
locichunk
validation
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,...
python
{ "resource": "" }
q259334
enter_pairs
validation
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, ] ...
python
{ "resource": "" }
q259335
enter_singles
validation
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...
python
{ "resource": "" }
q259336
init_arrays
validation
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...
python
{ "resource": "" }
q259337
snpcount_numba
validation
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...
python
{ "resource": "" }
q259338
maxind_numba
validation
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) ...
python
{ "resource": "" }
q259339
write_snps_map
validation
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...
python
{ "resource": "" }
q259340
write_usnps
validation
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 ...
python
{ "resource": "" }
q259341
write_str
validation
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"] ...
python
{ "resource": "" }
q259342
concat_vcf
validation
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) ...
python
{ "resource": "" }
q259343
reftrick
validation
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) ...
python
{ "resource": "" }
q259344
_collapse_outgroup
validation
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...
python
{ "resource": "" }
q259345
Tree.draw
validation
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_...
python
{ "resource": "" }
q259346
get_quick_depths
validation
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...
python
{ "resource": "" }
q259347
align_and_parse
validation
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") ##...
python
{ "resource": "" }
q259348
aligned_indel_filter
validation
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...
python
{ "resource": "" }
q259349
setup_dirs
validation
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...
python
{ "resource": "" }
q259350
build_dag
validation
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...
python
{ "resource": "" }
q259351
_plot_dag
validation
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...
python
{ "resource": "" }
q259352
trackjobs
validation
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....
python
{ "resource": "" }
q259353
concat_multiple_edits
validation
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...
python
{ "resource": "" }
q259354
cluster
validation
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(...
python
{ "resource": "" }
q259355
muscle_chunker
validation
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...
python
{ "resource": "" }
q259356
derep_concat_split
validation
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...
python
{ "resource": "" }
q259357
branch_assembly
validation
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...
python
{ "resource": "" }
q259358
getassembly
validation
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...
python
{ "resource": "" }
q259359
get_binom
validation
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)...
python
{ "resource": "" }
q259360
basecaller
validation
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 ...
python
{ "resource": "" }
q259361
nfilter1
validation
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
python
{ "resource": "" }
q259362
storealleles
validation
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...
python
{ "resource": "" }
q259363
chunk_clusters
validation
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...
python
{ "resource": "" }
q259364
run
validation
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 ...
python
{ "resource": "" }
q259365
calculate_depths
validation
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...
python
{ "resource": "" }
q259366
make_chunks
validation
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...
python
{ "resource": "" }
q259367
make
validation
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...
python
{ "resource": "" }
q259368
cluster_info
validation
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)...
python
{ "resource": "" }
q259369
_set_debug_dict
validation
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"\ ...
python
{ "resource": "" }
q259370
_debug_off
validation
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__)
python
{ "resource": "" }
q259371
_cmd_exists
validation
def _cmd_exists(cmd): """ check if dependency program is there """ return _subprocess.call("type " + cmd, shell=True, stdout=_subprocess.PIPE, stderr=_subprocess.PIPE) == 0
python
{ "resource": "" }
q259372
_getbins
validation
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...
python
{ "resource": "" }
q259373
nworker
validation
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...
python
{ "resource": "" }
q259374
store_all
validation
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...
python
{ "resource": "" }
q259375
store_random
validation
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...
python
{ "resource": "" }
q259376
random_combination
validation
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...
python
{ "resource": "" }
q259377
random_product
validation
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
python
{ "resource": "" }
q259378
resolve_ambigs
validation
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'...
python
{ "resource": "" }
q259379
set_mkl_thread_limit
validation
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...
python
{ "resource": "" }
q259380
get_total
validation
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] ...
python
{ "resource": "" }
q259381
get_sampled
validation
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: ## ...
python
{ "resource": "" }
q259382
Tetrad._run_qmc
validation
def _run_qmc(self, boot): """ Runs quartet max-cut QMC on the quartets qdump file. """ ## build command self._tmp = os.path.join(self.dirs, ".tmptre") cmd = [ip.bins.qmc, "qrtt="+self.files.qdump, "otre="+self._tmp] ## run it proc = subprocess.Popen(cmd,...
python
{ "resource": "" }
q259383
Tetrad._insert_to_array
validation
def _insert_to_array(self, chunk, results): """ Enters results arrays into the HDF5 database. """ ## two result arrs chunksize = self._chunksize qrts, invs = results ## enter into db with h5py.File(self.database.output, 'r+') as io5: io5['qua...
python
{ "resource": "" }
q259384
get_client
validation
def get_client(cluster_id, profile, engines, timeout, cores, quiet, spacer, **kwargs): """ Creates a client to view ipcluster engines for a given profile and returns it with at least one engine spun up and ready to go. If no engines are found after nwait amount of time then an error is raised. If...
python
{ "resource": "" }
q259385
memoize
validation
def memoize(func): """ Memoization decorator for a function taking one or more arguments. """ class Memodict(dict): """ just a dict""" def __getitem__(self, *key): return dict.__getitem__(self, key) def __missing__(self, key): """ this makes it faster """ ...
python
{ "resource": "" }
q259386
ambigcutters
validation
def ambigcutters(seq): """ Returns both resolutions of a cut site that has an ambiguous base in it, else the single cut site """ resos = [] if any([i in list("RKSYWM") for i in seq]): for base in list("RKSYWM"): if base in seq: resos.append(seq.replace(base, A...
python
{ "resource": "" }
q259387
splitalleles
validation
def splitalleles(consensus): """ takes diploid consensus alleles with phase data stored as a mixture of upper and lower case characters and splits it into 2 alleles """ ## store two alleles, allele1 will start with bigbase allele1 = list(consensus) allele2 = list(consensus) hidx = [i for (i, j)...
python
{ "resource": "" }
q259388
comp
validation
def comp(seq): """ returns a seq with complement. Preserves little n's for splitters.""" ## makes base to its small complement then makes upper return seq.replace("A", 't')\ .replace('T', 'a')\ .replace('C', 'g')\ .replace('G', 'c')\ .replace('n', 'Z')...
python
{ "resource": "" }
q259389
fullcomp
validation
def fullcomp(seq): """ returns complement of sequence including ambiguity characters, and saves lower case info for multiple hetero sequences""" ## this is surely not the most efficient... seq = seq.replace("A", 'u')\ .replace('T', 'v')\ .replace('C', 'p')\ .replac...
python
{ "resource": "" }
q259390
fastq_touchup_for_vsearch_merge
validation
def fastq_touchup_for_vsearch_merge(read, outfile, reverse=False): """ option to change orientation of reads and sets Qscore to B """ counts = 0 with open(outfile, 'w') as out: ## read in paired end read files 4 lines at a time if read.endswith(".gz"): fr1 = gzip.open(read, ...
python
{ "resource": "" }
q259391
revcomp
validation
def revcomp(sequence): "returns reverse complement of a string" sequence = sequence[::-1].strip()\ .replace("A", "t")\ .replace("T", "a")\ .replace("C", "g")\ .replace("G", "c").upper() return...
python
{ "resource": "" }
q259392
clustdealer
validation
def clustdealer(pairdealer, optim): """ return optim clusters given iterators, and whether it got all or not""" ccnt = 0 chunk = [] while ccnt < optim: ## try refreshing taker, else quit try: taker = itertools.takewhile(lambda x: x[0] != "//\n", pairdealer) oneclu...
python
{ "resource": "" }
q259393
progressbar
validation
def progressbar(njobs, finished, msg="", spacer=" "): """ prints a progress bar """ if njobs: progress = 100*(finished / float(njobs)) else: progress = 100 hashes = '#'*int(progress/5.) nohash = ' '*int(20-len(hashes)) if not ipyrad.__interactive__: msg = msg.rs...
python
{ "resource": "" }
q259394
get_threaded_view
validation
def get_threaded_view(ipyclient, split=True): """ gets optimum threaded view of ids given the host setup """ ## engine ids ## e.g., [0, 1, 2, 3, 4, 5, 6, 7, 8] eids = ipyclient.ids ## get host names ## e.g., ['a', 'a', 'b', 'b', 'a', 'c', 'c', 'c', 'c'] dview = ipyclient.direct_view() h...
python
{ "resource": "" }
q259395
detect_cpus
validation
def detect_cpus(): """ Detects the number of CPUs on a system. This is better than asking ipyparallel since ipp has to wait for Engines to spin up. """ # Linux, Unix and MacOS: if hasattr(os, "sysconf"): if os.sysconf_names.has_key("SC_NPROCESSORS_ONLN"): # Linux & Unix: ...
python
{ "resource": "" }
q259396
_call_structure
validation
def _call_structure(mname, ename, sname, name, workdir, seed, ntaxa, nsites, kpop, rep): """ make the subprocess call to structure """ ## create call string outname = os.path.join(workdir, "{}-K-{}-rep-{}".format(name, kpop, rep)) cmd = ["structure", "-m", mname, "-e", ename, ...
python
{ "resource": "" }
q259397
_get_clumpp_table
validation
def _get_clumpp_table(self, kpop, max_var_multiple, quiet): """ private function to clumpp results""" ## concat results for k=x reps, excluded = _concat_reps(self, kpop, max_var_multiple, quiet) if reps: ninds = reps[0].inds nreps = len(reps) else: ninds = nreps = 0 if n...
python
{ "resource": "" }
q259398
_get_evanno_table
validation
def _get_evanno_table(self, kpops, max_var_multiple, quiet): """ Calculates Evanno method K value scores for a series of permuted clumpp results. """ ## iterate across k-vals kpops = sorted(kpops) replnliks = [] for kpop in kpops: ## concat results for k=x reps, exclud...
python
{ "resource": "" }
q259399
Structure.result_files
validation
def result_files(self): """ returns a list of files that have finished structure """ reps = OPJ(self.workdir, self.name+"-K-*-rep-*_f") repfiles = glob.glob(reps) return repfiles
python
{ "resource": "" }