_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q259200
Functions.run
validation
async def run(self, *args, data): """ run the function you want """ cmd = self._get(data.text) try: if cmd is not None: command = self[cmd](*args, data=data) return await peony.utils.execute(command) except: fmt = "Error occurred ...
python
{ "resource": "" }
q259201
HivePlot.simplified_edges
validation
def simplified_edges(self): """ A generator for getting all of the edges without consuming extra memory. """ for group, edgelist in self.edges.items(): for u, v, d in edgelist: yield (u, v)
python
{ "resource": "" }
q259202
HivePlot.has_edge_within_group
validation
def has_edge_within_group(self, group): """ Checks whether there are within-group edges or not. """ assert group in self.nodes.keys(),\ "{0} not one of the group of nodes".format(group) nodelist = self.nodes[group] for n1, n2 in self.simplified_edges(): ...
python
{ "resource": "" }
q259203
HivePlot.plot_axis
validation
def plot_axis(self, rs, theta): """ Renders the axis. """ xs, ys = get_cartesian(rs, theta) self.ax.plot(xs, ys, 'black', alpha=0.3)
python
{ "resource": "" }
q259204
HivePlot.plot_nodes
validation
def plot_nodes(self, nodelist, theta, group): """ Plots nodes to screen. """ for i, node in enumerate(nodelist): r = self.internal_radius + i * self.scale x, y = get_cartesian(r, theta) circle = plt.Circle(xy=(x, y), radius=self.dot_radius, ...
python
{ "resource": "" }
q259205
HivePlot.group_theta
validation
def group_theta(self, group): """ Computes the theta along which a group's nodes are aligned. """ for i, g in enumerate(self.nodes.keys()): if g == group: break return i * self.major_angle
python
{ "resource": "" }
q259206
HivePlot.find_node_group_membership
validation
def find_node_group_membership(self, node): """ Identifies the group for which a node belongs to. """ for group, nodelist in self.nodes.items(): if node in nodelist: return group
python
{ "resource": "" }
q259207
HivePlot.get_idx
validation
def get_idx(self, node): """ Finds the index of the node in the sorted list. """ group = self.find_node_group_membership(node) return self.nodes[group].index(node)
python
{ "resource": "" }
q259208
HivePlot.node_radius
validation
def node_radius(self, node): """ Computes the radial position of the node. """ return self.get_idx(node) * self.scale + self.internal_radius
python
{ "resource": "" }
q259209
HivePlot.node_theta
validation
def node_theta(self, node): """ Convenience function to find the node's theta angle. """ group = self.find_node_group_membership(node) return self.group_theta(group)
python
{ "resource": "" }
q259210
HivePlot.add_edges
validation
def add_edges(self): """ Draws all of the edges in the graph. """ for group, edgelist in self.edges.items(): for (u, v, d) in edgelist: self.draw_edge(u, v, d, group)
python
{ "resource": "" }
q259211
HivePlot.draw
validation
def draw(self): """ The master function that is called that draws everything. """ self.ax.set_xlim(-self.plot_radius(), self.plot_radius()) self.ax.set_ylim(-self.plot_radius(), self.plot_radius()) self.add_axes_and_nodes() self.add_edges() self.ax.axis(...
python
{ "resource": "" }
q259212
HivePlot.adjust_angles
validation
def adjust_angles(self, start_node, start_angle, end_node, end_angle): """ This function adjusts the start and end angles to correct for duplicated axes. """ start_group = self.find_node_group_membership(start_node) end_group = self.find_node_group_membership(end_node) ...
python
{ "resource": "" }
q259213
Type.mods_genre
validation
def mods_genre(self): """ Guesses an appropriate MODS XML genre type. """ type2genre = { 'conference': 'conference publication', 'book chapter': 'bibliography', 'unpublished': 'article' } tp = str(self.type).lower() return type2genre.get(tp, tp)
python
{ "resource": "" }
q259214
get_publications
validation
def get_publications(context, template='publications/publications.html'): """ Get all publications. """ types = Type.objects.filter(hidden=False) publications = Publication.objects.select_related() publications = publications.filter(external=False, type__in=types) publications = publications.order_by('-year', '...
python
{ "resource": "" }
q259215
get_publication
validation
def get_publication(context, id): """ Get a single publication. """ pbl = Publication.objects.filter(pk=int(id)) if len(pbl) < 1: return '' pbl[0].links = pbl[0].customlink_set.all() pbl[0].files = pbl[0].customfile_set.all() return render_template( 'publications/publication.html', context['request'], {...
python
{ "resource": "" }
q259216
get_publication_list
validation
def get_publication_list(context, list, template='publications/publications.html'): """ Get a publication list. """ list = List.objects.filter(list__iexact=list) if not list: return '' list = list[0] publications = list.publication_set.all() publications = publications.order_by('-year', '-month', '-id') ...
python
{ "resource": "" }
q259217
tex_parse
validation
def tex_parse(string): """ Renders some basic TeX math to HTML. """ string = string.replace('{', '').replace('}', '') def tex_replace(match): return \ sub(r'\^(\w)', r'<sup>\1</sup>', sub(r'\^\{(.*?)\}', r'<sup>\1</sup>', sub(r'\_(\w)', r'<sub>\1</sub>', sub(r'\_\{(.*?)\}', r'<sub>\1</sub>', sub(...
python
{ "resource": "" }
q259218
parse
validation
def parse(string): """ Takes a string in BibTex format and returns a list of BibTex entries, where each entry is a dictionary containing the entries' key-value pairs. @type string: string @param string: bibliography in BibTex format @rtype: list @return: a list of dictionaries representing a bibliography """...
python
{ "resource": "" }
q259219
OrderedModel.swap
validation
def swap(self, qs): """ Swap the positions of this object with a reference object. """ try: replacement = qs[0] except IndexError: # already first/last return if not self._valid_ordering_reference(replacement): raise ValueEr...
python
{ "resource": "" }
q259220
OrderedModel.up
validation
def up(self): """ Move this object up one position. """ self.swap(self.get_ordering_queryset().filter(order__lt=self.order).order_by('-order'))
python
{ "resource": "" }
q259221
OrderedModel.down
validation
def down(self): """ Move this object down one position. """ self.swap(self.get_ordering_queryset().filter(order__gt=self.order))
python
{ "resource": "" }
q259222
OrderedModel.to
validation
def to(self, order): """ Move object to a certain position, updating all affected objects to move accordingly up or down. """ if order is None or self.order == order: # object is already at desired position return qs = self.get_ordering_queryset() ...
python
{ "resource": "" }
q259223
OrderedModel.above
validation
def above(self, ref): """ Move this object above the referenced object. """ if not self._valid_ordering_reference(ref): raise ValueError( "%r can only be moved above instances of %r which %s equals %r." % ( self, self.__class__, self.order_...
python
{ "resource": "" }
q259224
OrderedModel.below
validation
def below(self, ref): """ Move this object below the referenced object. """ if not self._valid_ordering_reference(ref): raise ValueError( "%r can only be moved below instances of %r which %s equals %r." % ( self, self.__class__, self.order_...
python
{ "resource": "" }
q259225
OrderedModel.top
validation
def top(self): """ Move this object to the top of the ordered stack. """ o = self.get_ordering_queryset().aggregate(Min('order')).get('order__min') self.to(o)
python
{ "resource": "" }
q259226
OrderedModel.bottom
validation
def bottom(self): """ Move this object to the bottom of the ordered stack. """ o = self.get_ordering_queryset().aggregate(Max('order')).get('order__max') self.to(o)
python
{ "resource": "" }
q259227
populate
validation
def populate(publications): """ Load custom links and files from database and attach to publications. """ customlinks = CustomLink.objects.filter(publication__in=publications) customfiles = CustomFile.objects.filter(publication__in=publications) publications_ = {} for publication in publications: publication...
python
{ "resource": "" }
q259228
worker
validation
def worker(self): """ Calculates the quartet weights for the test at a random subsampled chunk of loci. """ ## subsample loci fullseqs = self.sample_loci() ## find all iterations of samples for this quartet liters = itertools.product(*self.imap.values()) ## run tree inference fo...
python
{ "resource": "" }
q259229
get_order
validation
def get_order(tre): """ return tree order """ anode = tre.tree&">A" sister = anode.get_sisters()[0] sisters = (anode.name[1:], sister.name[1:]) others = [i for i in list("ABCD") if i not in sisters] return sorted(sisters) + sorted(others)
python
{ "resource": "" }
q259230
count_var
validation
def count_var(nex): """ count number of sites with cov=4, and number of variable sites. """ arr = np.array([list(i.split()[-1]) for i in nex]) miss = np.any(arr=="N", axis=0) nomiss = arr[:, ~miss] nsnps = np.invert(np.all(nomiss==nomiss[0, :], axis=0)).sum() return nomiss.shape[1], nsnp...
python
{ "resource": "" }
q259231
Twiist.sample_loci
validation
def sample_loci(self): """ finds loci with sufficient sampling for this test""" ## store idx of passing loci idxs = np.random.choice(self.idxs, self.ntests) ## open handle, make a proper generator to reduce mem with open(self.data) as indata: liter = (indata.read()....
python
{ "resource": "" }
q259232
Twiist.run_tree_inference
validation
def run_tree_inference(self, nexus, idx): """ Write nexus to tmpfile, runs phyml tree inference, and parses and returns the resulting tree. """ ## create a tmpdir for this test tmpdir = tempfile.tempdir tmpfile = os.path.join(tempfile.NamedTemporaryFile( ...
python
{ "resource": "" }
q259233
Twiist.plot
validation
def plot(self): """ return a toyplot barplot of the results table. """ if self.results_table == None: return "no results found" else: bb = self.results_table.sort_values( by=["ABCD", "ACBD"], ascending=[False, True], ...
python
{ "resource": "" }
q259234
PCA.plot_pairwise_dist
validation
def plot_pairwise_dist(self, labels=None, ax=None, cmap=None, cdict=None, metric="euclidean"): """ Plot pairwise distances between all samples labels: bool or list by default labels aren't included. If labels == True, then labels are read in from the vcf file. Al...
python
{ "resource": "" }
q259235
PCA.copy
validation
def copy(self): """ returns a copy of the pca analysis object """ cp = copy.deepcopy(self) cp.genotypes = allel.GenotypeArray(self.genotypes, copy=True) return cp
python
{ "resource": "" }
q259236
loci2migrate
validation
def loci2migrate(name, locifile, popdict, mindict=1): """ A function to build an input file for the program migrate from an ipyrad .loci file, and a dictionary grouping Samples into populations. Parameters: ----------- name: (str) The name prefix for the migrate formatted output file...
python
{ "resource": "" }
q259237
update
validation
def update(assembly, idict, count): """ updates dictionary with the next .5M reads from the super long string phylip file. Makes for faster reading. """ data = iter(open(os.path.join(assembly.dirs.outfiles, assembly.name+".phy"), 'r')) ntax, nchar = data.next().strip().split() ...
python
{ "resource": "" }
q259238
make
validation
def make(assembly, samples): """ Make phylip and nexus formats. This is hackish since I'm recycling the code whole-hog from pyrad V3. Probably could be good to go back through and clean up the conversion code some time. """ ## get the longest name longname = max([len(i) for i in assembly.samp...
python
{ "resource": "" }
q259239
sample_cleanup
validation
def sample_cleanup(data, sample): """ Clean up a bunch of loose files. """ umap1file = os.path.join(data.dirs.edits, sample.name+"-tmp-umap1.fastq") umap2file = os.path.join(data.dirs.edits, sample.name+"-tmp-umap2.fastq") unmapped = os.path.join(data.dirs.refmapping, sample.name+"-unmapped.bam"...
python
{ "resource": "" }
q259240
index_reference_sequence
validation
def index_reference_sequence(data, force=False): """ Index the reference sequence, unless it already exists. Also make a mapping of scaffolds to index numbers for later user in steps 5-6. """ ## get ref file from params refseq_file = data.paramsdict['reference_sequence'] index_files = [] ...
python
{ "resource": "" }
q259241
fetch_cluster_se
validation
def fetch_cluster_se(data, samfile, chrom, rstart, rend): """ Builds a single end cluster from the refmapped data. """ ## If SE then we enforce the minimum overlap distance to avoid the ## staircase syndrome of multiple reads overlapping just a little. overlap_buffer = data._hackersonly["min_SE...
python
{ "resource": "" }
q259242
ref_build_and_muscle_chunk
validation
def ref_build_and_muscle_chunk(data, sample): """ 1. Run bedtools to get all overlapping regions 2. Parse out reads from regions using pysam and dump into chunk files. We measure it out to create 10 chunk files per sample. 3. If we really wanted to speed this up, though it is pretty fast alrea...
python
{ "resource": "" }
q259243
ref_muscle_chunker
validation
def ref_muscle_chunker(data, sample): """ Run bedtools to get all overlapping regions. Pass this list into the func 'get_overlapping_reads' which will write fastq chunks to the clust.gz file. 1) Run bedtools merge to get a list of all contiguous blocks of bases in the reference seqeunce where one ...
python
{ "resource": "" }
q259244
check_insert_size
validation
def check_insert_size(data, sample): """ check mean insert size for this sample and update hackersonly.max_inner_mate_distance if need be. This value controls how far apart mate pairs can be to still be considered for bedtools merging downstream. """ ## pipe stats output to grep cmd1...
python
{ "resource": "" }
q259245
bedtools_merge
validation
def bedtools_merge(data, sample): """ Get all contiguous genomic regions with one or more overlapping reads. This is the shell command we'll eventually run bedtools bamtobed -i 1A_0.sorted.bam | bedtools merge [-d 100] -i <input_bam> : specifies the input file to bed'ize -d <int> ...
python
{ "resource": "" }
q259246
refmap_stats
validation
def refmap_stats(data, sample): """ Get the number of mapped and unmapped reads for a sample and update sample.stats """ ## shorter names mapf = os.path.join(data.dirs.refmapping, sample.name+"-mapped-sorted.bam") umapf = os.path.join(data.dirs.refmapping, sample.name+"-unmapped.bam") ...
python
{ "resource": "" }
q259247
refmap_init
validation
def refmap_init(data, sample, force): """ create some file handles for refmapping """ ## make some persistent file handles for the refmap reads files sample.files.unmapped_reads = os.path.join(data.dirs.edits, "{}-refmap_derep.fastq".format(sample.name)) sample.files.m...
python
{ "resource": "" }
q259248
Treemix._subsample
validation
def _subsample(self): """ returns a subsample of unlinked snp sites """ spans = self.maparr samp = np.zeros(spans.shape[0], dtype=np.uint64) for i in xrange(spans.shape[0]): samp[i] = np.random.randint(spans[i, 0], spans[i, 1], 1) return samp
python
{ "resource": "" }
q259249
Treemix.draw
validation
def draw(self, axes): """ Returns a treemix plot on a toyplot.axes object. """ ## create a toytree object from the treemix tree result tre = toytree.tree(newick=self.results.tree) tre.draw( axes=axes, use_edge_lengths=True, ...
python
{ "resource": "" }
q259250
_resolveambig
validation
def _resolveambig(subseq): """ Randomly resolves iupac hetero codes. This is a shortcut for now, we could instead use the phased alleles in RAD loci. """ N = [] for col in subseq: rand = np.random.binomial(1, 0.5) N.append([_AMBIGS[i][rand] for i in col]) return np.array(N)
python
{ "resource": "" }
q259251
_count_PIS
validation
def _count_PIS(seqsamp, N): """ filters for loci with >= N PIS """ counts = [Counter(col) for col in seqsamp.T if not ("-" in col or "N" in col)] pis = [i.most_common(2)[1][1] > 1 for i in counts if len(i.most_common(2))>1] if sum(pis) >= N: return sum(pis) else: return 0
python
{ "resource": "" }
q259252
Bucky._write_nex
validation
def _write_nex(self, mdict, nlocus): """ function that takes a dictionary mapping names to sequences, and a locus number, and writes it as a NEXUS file with a mrbayes analysis block given a set of mcmc arguments. """ ## create matrix as a string max_name_len =...
python
{ "resource": "" }
q259253
_read_sample_names
validation
def _read_sample_names(fname): """ Read in sample names from a plain text file. This is a convenience function for branching so if you have tons of sample names you can pass in a file rather than having to set all the names at the command line. """ try: with open(fname, 'r') as infile: ...
python
{ "resource": "" }
q259254
_bufcountlines
validation
def _bufcountlines(filename, gzipped): """ fast line counter. Used to quickly sum number of input reads when running link_fastqs to append files. """ if gzipped: fin = gzip.open(filename) else: fin = open(filename) nlines = 0 buf_size = 1024 * 1024 read_f = fin.read # loo...
python
{ "resource": "" }
q259255
_zbufcountlines
validation
def _zbufcountlines(filename, gzipped): """ faster line counter """ if gzipped: cmd1 = ["gunzip", "-c", filename] else: cmd1 = ["cat", filename] cmd2 = ["wc"] proc1 = sps.Popen(cmd1, stdout=sps.PIPE, stderr=sps.PIPE) proc2 = sps.Popen(cmd2, stdin=proc1.stdout, stdout=sps.PIPE, s...
python
{ "resource": "" }
q259256
_tuplecheck
validation
def _tuplecheck(newvalue, dtype=str): """ Takes a string argument and returns value as a tuple. Needed for paramfile conversion from CLI to set_params args """ if isinstance(newvalue, list): newvalue = tuple(newvalue) if isinstance(newvalue, str): newvalue = newvalue.rstrip(")"...
python
{ "resource": "" }
q259257
Assembly.stats
validation
def stats(self): """ Returns a data frame with Sample data and state. """ nameordered = self.samples.keys() nameordered.sort() ## Set pandas to display all samples instead of truncating pd.options.display.max_rows = len(self.samples) statdat = pd.DataFrame([self.samples[...
python
{ "resource": "" }
q259258
Assembly.files
validation
def files(self): """ Returns a data frame with Sample files. Not very readable... """ nameordered = self.samples.keys() nameordered.sort() ## replace curdir with . for shorter printing #fullcurdir = os.path.realpath(os.path.curdir) return pd.DataFrame([self.samples[i].fil...
python
{ "resource": "" }
q259259
Assembly._build_stat
validation
def _build_stat(self, idx): """ Returns a data frame with Sample stats for each step """ nameordered = self.samples.keys() nameordered.sort() newdat = pd.DataFrame([self.samples[i].stats_dfs[idx] \ for i in nameordered], index=nameordered)\ ...
python
{ "resource": "" }
q259260
Assembly.get_params
validation
def get_params(self, param=""): """ pretty prints params if called as a function """ fullcurdir = os.path.realpath(os.path.curdir) if not param: for index, (key, value) in enumerate(self.paramsdict.items()): if isinstance(value, str): value = value...
python
{ "resource": "" }
q259261
Assembly.set_params
validation
def set_params(self, param, newvalue): """ Set a parameter to a new value. Raises error if newvalue is wrong type. Note ---- Use [Assembly].get_params() to see the parameter values currently linked to the Assembly object. Parameters ---------- pa...
python
{ "resource": "" }
q259262
Assembly.branch
validation
def branch(self, newname, subsamples=None, infile=None): """ Returns a copy of the Assembly object. Does not allow Assembly object names to be replicated in namespace or path. """ ## subsample by removal or keeping. remove = 0 ## is there a better way to ask if i...
python
{ "resource": "" }
q259263
Assembly._step1func
validation
def _step1func(self, force, ipyclient): """ hidden wrapped function to start step 1 """ ## check input data files sfiles = self.paramsdict["sorted_fastq_path"] rfiles = self.paramsdict["raw_fastq_path"] ## do not allow both a sorted_fastq_path and a raw_fastq if sfiles ...
python
{ "resource": "" }
q259264
Assembly._step2func
validation
def _step2func(self, samples, force, ipyclient): """ hidden wrapped function to start step 2""" ## print header if self._headers: print("\n Step 2: Filtering reads ") ## If no samples in this assembly then it means you skipped step1, if not self.samples.keys(): ...
python
{ "resource": "" }
q259265
Assembly._step4func
validation
def _step4func(self, samples, force, ipyclient): """ hidden wrapped function to start step 4 """ if self._headers: print("\n Step 4: Joint estimation of error rate and heterozygosity") ## Get sample objects from list of strings samples = _get_samples(self, samples) ...
python
{ "resource": "" }
q259266
Assembly._step5func
validation
def _step5func(self, samples, force, ipyclient): """ hidden wrapped function to start step 5 """ ## print header if self._headers: print("\n Step 5: Consensus base calling ") ## Get sample objects from list of strings samples = _get_samples(self, samples) #...
python
{ "resource": "" }
q259267
Assembly._step6func
validation
def _step6func(self, samples, noreverse, force, randomseed, ipyclient, **kwargs): """ Hidden function to start Step 6. """ ## Get sample objects from list of strings samples = _get_samples(self, samples) ## remove ...
python
{ "resource": "" }
q259268
Assembly._samples_precheck
validation
def _samples_precheck(self, samples, mystep, force): """ Return a list of samples that are actually ready for the next step. Each step runs this prior to calling run, makes it easier to centralize and normalize how each step is checking sample states. mystep is the state prod...
python
{ "resource": "" }
q259269
combinefiles
validation
def combinefiles(filepath): """ Joins first and second read file names """ ## unpack seq files in filepath fastqs = glob.glob(filepath) firsts = [i for i in fastqs if "_R1_" in i] ## check names if not firsts: raise IPyradWarningExit("First read files names must contain '_R1_'.") #...
python
{ "resource": "" }
q259270
get_barcode_func
validation
def get_barcode_func(data, longbar): """ returns the fastest func given data & longbar""" ## build func for finding barcode if longbar[1] == 'same': if data.paramsdict["datatype"] == '2brad': def getbarcode(cutters, read1, longbar): """ find barcode for 2bRAD data """ ...
python
{ "resource": "" }
q259271
get_quart_iter
validation
def get_quart_iter(tups): """ returns an iterator to grab four lines at a time """ if tups[0].endswith(".gz"): ofunc = gzip.open else: ofunc = open ## create iterators ofile1 = ofunc(tups[0], 'r') fr1 = iter(ofile1) quart1 = itertools.izip(fr1, fr1, fr1, fr1) if tups[...
python
{ "resource": "" }
q259272
writetofastq
validation
def writetofastq(data, dsort, read): """ Writes sorted data 'dsort dict' to a tmp files """ if read == 1: rrr = "R1" else: rrr = "R2" for sname in dsort: ## skip writing if empty. Write to tmpname handle = os.path.join(data.dirs.fastqs, "{}_{}_....
python
{ "resource": "" }
q259273
collate_files
validation
def collate_files(data, sname, tmp1s, tmp2s): """ Collate temp fastq files in tmp-dir into 1 gzipped sample. """ ## out handle out1 = os.path.join(data.dirs.fastqs, "{}_R1_.fastq.gz".format(sname)) out = io.BufferedWriter(gzip.open(out1, 'w')) ## build cmd cmd1 = ['cat'] for tmpfil...
python
{ "resource": "" }
q259274
estimate_optim
validation
def estimate_optim(data, testfile, ipyclient): """ Estimate a reasonable optim value by grabbing a chunk of sequences, decompressing and counting them, to estimate the full file size. """ ## count the len of one file and assume all others are similar len insize = os.path.getsize(testfile) ...
python
{ "resource": "" }
q259275
_cleanup_and_die
validation
def _cleanup_and_die(data): """ cleanup func for step 1 """ tmpfiles = glob.glob(os.path.join(data.dirs.fastqs, "tmp_*_R*.fastq")) tmpfiles += glob.glob(os.path.join(data.dirs.fastqs, "tmp_*.p")) for tmpf in tmpfiles: os.remove(tmpf)
python
{ "resource": "" }
q259276
splitfiles
validation
def splitfiles(data, raws, ipyclient): """ sends raws to be chunked""" ## create a tmpdir for chunked_files and a chunk optimizer tmpdir = os.path.join(data.paramsdict["project_dir"], "tmp-chunks-"+data.name) if os.path.exists(tmpdir): shutil.rmtree(tmpdir) os.makedirs(tmpdir) ## chun...
python
{ "resource": "" }
q259277
putstats
validation
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...
python
{ "resource": "" }
q259278
_countmatrix
validation
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, ...
python
{ "resource": "" }
q259279
paramname
validation
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...
python
{ "resource": "" }
q259280
save_json2
validation
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"]) ...
python
{ "resource": "" }
q259281
save_json
validation
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...
python
{ "resource": "" }
q259282
Encoder.encode
validation
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 ...
python
{ "resource": "" }
q259283
depthplot
validation
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() ...
python
{ "resource": "" }
q259284
_parse_00
validation
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()) ...
python
{ "resource": "" }
q259285
_parse_01
validation
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...
python
{ "resource": "" }
q259286
Bpp._load_existing_results
validation
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)) ...
python
{ "resource": "" }
q259287
Bpp.summarize_results
validation
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 ...
python
{ "resource": "" }
q259288
multi_muscle_align
validation
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...
python
{ "resource": "" }
q259289
concatclusts
validation
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")
python
{ "resource": "" }
q259290
fill_dups_arr
validation
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 ...
python
{ "resource": "" }
q259291
build_tmp_h5
validation
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...
python
{ "resource": "" }
q259292
get_nloci
validation
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]
python
{ "resource": "" }
q259293
singlecat
validation
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. ...
python
{ "resource": "" }
q259294
write_to_fullarr
validation
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...
python
{ "resource": "" }
q259295
dask_chroms
validation
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...
python
{ "resource": "" }
q259296
inserted_indels
validation
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...
python
{ "resource": "" }
q259297
count_seeds
validation
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....
python
{ "resource": "" }
q259298
sort_seeds
validation
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()
python
{ "resource": "" }
q259299
build_clustbits
validation
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...
python
{ "resource": "" }