Search is not available for this dataset
text
stringlengths
75
104k
def _store_N_samples(self, start, ipyclient, quiet=False): """ Find all quartets of samples and store in a large array A chunk size is assigned for sampling from the array of quartets based on the number of cpus available. This should be relatively large so that we don't spend ...
def _dump_qmc(self): """ Writes the inferred quartet sets from the database to a text file to be used as input for QMC. Quartets that had no information available (i.e., no SNPs) were written to the database as 0,0,0,0 and are excluded here from the output. """ ...
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,...
def _compute_stats(self, start, ipyclient, quiet=False): """ Compute sampling stats and consens trees. """ ## get name indices names = self.samples ## make a consensus from bootstrap reps. if self.checkpoint.boots: tre = ete3.Tree(self.trees...
def _load(self, name, workdir, quiet=False): """ Load a JSON serialized tetrad instance to continue from a checkpoint. """ ## load the JSON string and try with name+.json path = os.path.join(workdir, name) if not path.endswith(".tet.json"): path += ".tet.json...
def _inference(self, start, ipyclient, quiet): """ Sends slices of quartet sets to parallel engines for computing, enters results into output database, sends finished quartet sets to QMC for tree inference, and prints progress bars. """ ## load-balancer for single-threa...
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...
def run(self, force=False, quiet=False, ipyclient=None): """ Parameters ---------- force (bool): Overwrite existing results for object with the same name and workdir as this one. verbose (int): 0=primt nothing; 1=print progress bars; 2=print pr...
def start_ipcluster(data): """ Start ipcluster """ ## if MPI argument then use --ip arg to view all sockets iparg = "" if "MPI" in data._ipcluster["engines"]: iparg = "--ip=*" ## make ipcluster arg call standard = """ ipcluster start --daemonize ...
def register_ipcluster(data): """ The name is a unique id that keeps this __init__ of ipyrad distinct from interfering with other ipcontrollers. Run statements are wrapped so that ipcluster will be killed on exit. """ ## check if this pid already has a running cluster data._ipcluster["cluste...
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...
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 """ ...
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...
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)...
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')...
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...
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, ...
def merge_pairs_after_refmapping(data, two_files, merged_out): """ A function to merge fastq files produced by bam2fq. """ ## create temp files nonmerged1 = tempfile.NamedTemporaryFile( mode='wb', dir=data.dirs.edits, suffix="_nonmerged_R1_.fastq").name nonmerged2 = te...
def merge_after_pysam(data, clust): """ This is for pysam post-flight merging. The input is a cluster for an individual locus. We have to split the clusters, write R1 and R2 to files then call merge_pairs(). This is not ideal, it's slow, but it works. This is the absolute worst way to do this, i...
def merge_pairs(data, two_files, merged_out, revcomp, merge): """ Merge PE reads. Takes in a list of unmerged files [r1, r2] and the filehandle to write merged data to, and it returns the number of reads that were merged (overlapping). If merge==0 then only concat pairs (nnnn), no merging in vsearch...
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...
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...
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...
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...
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: ...
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, ...
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...
def _concat_reps(self, kpop, max_var_multiple, quiet, **kwargs): """ Combine structure replicates into a single indfile, returns nreps, ninds. Excludes reps with too high of variance (set with max_variance_multiplier) to exclude runs that did not converge. """ ## make an output handle...
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...
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
def run(self, kpop, nreps, ipyclient=None, seed=12345, force=False, quiet=False, ): """ submits a job to run on the cluster and returns an asynchronous result object. K is the number of populations, randomseed if not set will be ...
def write_structure_files(self, kpop, rep=1): """ Prepares input files for running structure. Users typically do not need to call this function since it is called internally by .run(). But it is optionally available here in case users wish to generate files and run structure se...
def get_clumpp_table(self, kvalues, max_var_multiple=0, quiet=False): """ Returns a dictionary of results tables for making structure barplots. This calls the same functions used in get_evanno_table() to call CLUMPP to permute replicates. Parameters: ----------- ...
def get_evanno_table(self, kvalues, max_var_multiple=0, quiet=False): """ Calculates the Evanno table from results files for tests with K-values in the input list kvalues. The values lnPK, lnPPK, and deltaK are calculated. The max_var_multiplier arg can be used to exclude result...
def parse(self, psearch, dsearch): """ parse an _f structure output file """ stable = "" with open(self.repfile) as orep: dat = orep.readlines() for line in dat: ## stat lines if "Estimated Ln Prob of Data" in line: self...
def _call_raxml(command_list): """ call the command as sps """ proc = subprocess.Popen( command_list, stderr=subprocess.STDOUT, stdout=subprocess.PIPE ) comm = proc.communicate() return comm
def _command_list(self): """ build the command list """ cmd = [self.params.binary, "-f", str(self.params.f), "-T", str(self.params.T), "-m", str(self.params.m), "-N", str(self.params.N), "-x", str(self.params.x), ...
def run(self, ipyclient=None, quiet=False, force=False, block=False, ): """ Submits raxml job to run. If no ipyclient object is provided then the function will block until the raxml run is finished. If an ipyclient is provided then the job is se...
def _get_binary(self): """ find binaries available""" ## check for binary backup_binaries = ["raxmlHPC-PTHREADS", "raxmlHPC-PTHREADS-SSE3"] ## check user binary first, then backups for binary in [self.params.binary] + backup_binaries: proc = subprocess.Popen(["which...
def share_matrix(locifile, tree=None, nameorder=None): """ returns a matrix of shared RAD-seq data Parameters: ----------- locifile (str): Path to a ipyrad .loci file. tree (str): Path to Newick file or a Newick string representation of a tree. If used, names will...
def _getarray(loci, snames): """ parse loci list and return presence/absence matrix ordered by the tips on the tree or list of names. """ ## make an empty matrix lxs = np.zeros((len(snames), len(loci)), dtype=np.uint64) ## fill the matrix for loc in xrange(len(loci)): for seq i...
def batch( baba, ipyclient=None, ): """ distributes jobs to the parallel client """ ## parse args handle = baba.data taxdicts = baba.tests mindicts = baba.params.mincov nboots = baba.params.nboots ## if ms generator make into reusable list sims = 0 if isinstance...
def dstat(inarr, taxdict, mindict=1, nboots=1000, name=0): """ private function to perform a single D-stat test""" #if isinstance(inarr, str): # with open(inarr, 'r') as infile: # inarr = infile.read().strip().split("|\n") # ## get data as an array from loci file # ## if loci-list th...
def _loci_to_arr(loci, taxdict, mindict): """ return a frequency array from a loci file for all loci with taxa from taxdict and min coverage from mindict. """ ## make the array (4 or 5) and a mask array to remove loci without cov nloci = len(loci) maxlen = np.max(np.array([len(locus.split...
def _get_boots(arr, nboots): """ return array of bootstrap D-stats """ ## hold results (nboots, [dstat, ]) boots = np.zeros((nboots,)) ## iterate to fill boots for bidx in xrange(nboots): ## sample with replacement lidx = np.random.randint(0, arr.shape[0], arr.shape[0]) ...
def _get_signif_4(arr, nboots): """ returns a list of stats and an array of dstat boots. Stats includes z-score and two-sided P-value. """ abba, baba, dst = _prop_dstat(arr) boots = _get_boots(arr, nboots) estimate, stddev = (boots.mean(), boots.std()) zscore = 0. if stddev: ...
def _get_signif_5(arr, nboots): """ returns a list of stats and an array of dstat boots. Stats includes z-score and two-sided P-value. """ statsarr = np.zeros((3, 7), dtype=np.float64) bootsarr = np.zeros((3, nboots)) idx = 0 for acol in [2, 3, 4]: rows = np.array([0, 1, acol,...
def _simulate(self, nreps, admix=None, Ns=500000, gen=20): """ Enter a baba.Tree object in which the 'tree' attribute (newick derived tree) has edge lengths in units of generations. You can use the 'gen' parameter to multiply branch lengths by a constant. Parameters: ----------- nreps: ...
def taxon_table(self): """ Returns the .tests list of taxa as a pandas dataframe. By auto-generating this table from tests it means that the table itself cannot be modified unless it is returned and saved. """ if self.tests: keys = sorted(self.test...
def run(self, ipyclient=None, ): """ Run a batch of dstat tests on a list of tests, where each test is a dictionary mapping sample names to {p1 - p4} (and sometimes p5). Parameters modifying the behavior of the run, such as the number of bootstrap replicates (n...
def plot(self, show_test_labels=True, use_edge_lengths=True, collapse_outgroup=False, pct_tree_x=0.5, pct_tree_y=0.2, subset_tests=None, #toytree_kwargs=None, *args, **kwargs): """ Draw a multi-panel figure with tree...
def loci2multinex(name, locifile, subsamples=None, outdir=None, maxloci=None, minSNPs=1, seed=12345, mcmc_burnin=int(1e6), mcmc_ngen=int(2e6), mcmc_sample_f...
def nexmake(mdict, nlocus, dirs, mcmc_burnin, mcmc_ngen, mcmc_sample_freq): """ 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. """ ## create matrix as a string max_name_len = max([len(i) for i in...
def call_fastq_dump_on_SRRs(self, srr, outname, paired): """ calls fastq-dump on SRRs, relabels fastqs by their accession names, and writes them to the workdir. Saves temp sra files in the designated tmp folder and immediately removes them. """ ## build command for fastq-dumping fd_cmd = [ ...
def fields_checker(fields): """ returns a fields argument formatted as a list of strings. and doesn't allow zero. """ ## make sure fields will work if isinstance(fields, int): fields = str(fields) if isinstance(fields, str): if "," in fields: fields = [str(i) for ...
def run(self, force=False, ipyclient=None, name_fields=30, name_separator="_", dry_run=False): """ Download the accessions into a the designated workdir. Parameters ---------- force: (bool) If force=True then existing fil...
def _submit_jobs(self, force, ipyclient, name_fields, name_separator, dry_run): """ Download the accessions into a the designated workdir. If file already exists it will only be overwritten if force=True. Temporary files are removed. ...
def fetch_runinfo(self, fields=None, quiet=False): """ Call esearch to grep SRR info for a project (SRP). Use the command sra.fetch_fields to see available fields to be fetched. This function returns a DataFrame with runinfo for the selected fields. Parameters: ---------...
def Async(cls, token, session=None, **options): """Returns the client in async mode.""" return cls(token, session=session, is_async=True, **options)
def get_constants(self, **params: keys): """Get the CR Constants Parameters ---------- \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional[list] = None Filter which keys should be excluded...
def get_player(self, *tags: crtag, **params: keys): """Get a player information Parameters ---------- \*tags: str Valid player tags. Minimum length: 3 Valid characters: 0289PYLQGRJCUV \*\*keys: Optional[list] = None Filter which keys should be...
def get_player_verify(self, tag: crtag, apikey: str, **params: keys): """Check the API Key of a player. This endpoint has been **restricted** to certain members of the community Parameters ---------- tag: str A valid tournament tag. Minimum length: 3 ...
def get_player_battles(self, *tags: crtag, **params: keys): """Get a player's battle log Parameters ---------- \*tags: str Valid player tags. Minimum length: 3 Valid characters: 0289PYLQGRJCUV \*\*keys: Optional[list] = None Filter which keys ...
def get_clan(self, *tags: crtag, **params: keys): """Get a clan information Parameters ---------- \*tags: str Valid clan tags. Minimum length: 3 Valid characters: 0289PYLQGRJCUV \*\*keys: Optional[list] = None Filter which keys should be inclu...
def get_tracking_clans(self, **params: keys): """Get a list of clans that are being tracked by having either cr-api.com or royaleapi.com in the description Parameters ---------- \*\*keys: Optional[list] = None Filter which keys should be included in the ...
def get_clan_tracking(self, *tags: crtag, **params: keys): """Returns if the clan is currently being tracked by the API by having either cr-api.com or royaleapi.com in the clan description Parameters ---------- \*tags: str Valid clan tags. Minimum length: 3 ...
def get_clan_war(self, tag: crtag, **params: keys): """Get inforamtion about a clan's current clan war Parameters ---------- *tag: str A valid clan tag. Minimum length: 3 Valid characters: 0289PYLQGRJCUV \*\*keys: Optional[list] = None Filter ...
def get_tournament(self, tag: crtag, **params: keys): """Get a tournament information Parameters ---------- tag: str A valid tournament tag. Minimum length: 3 Valid characters: 0289PYLQGRJCUV \*\*keys: Optional[list] = None Filter which keys s...
def search_tournaments(self, **params: keys): """Search for a tournament Parameters ---------- name: str The name of the tournament \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optio...
def get_top_war_clans(self, country_key='', **params: keys): """Get a list of top clans by war location_id: Optional[str] = '' A location ID or '' (global) See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json for a list of acceptable location ID...
def get_top_players(self, country_key='', **params: keys): """Get a list of top players location_id: Optional[str] = '' A location ID or '' (global) See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json for a list of acceptable location IDs ...
def get_popular_clans(self, **params: keys): """Get a list of most queried clans \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional[list] = None Filter which keys should be excluded from the ...
def get_popular_players(self, **params: keys): """Get a list of most queried players \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional[list] = None Filter which keys should be excluded from the ...
def get_popular_tournaments(self, **params: keys): """Get a list of most queried tournaments \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional[list] = None Filter which keys should be excluded from the ...
def get_popular_decks(self, **params: keys): """Get a list of most queried decks \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional[list] = None Filter which keys should be excluded from the ...
def get_known_tournaments(self, **params: tournamentfilter): """Get a list of queried tournaments \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional[list] = None Filter which keys should be excluded from...
def get_player(self, tag: crtag, timeout=None): """Get information about a player Parameters ---------- tag: str A valid tournament tag. Minimum length: 3 Valid characters: 0289PYLQGRJCUV timeout: Optional[int] = None Custom timeout that overw...
def get_player_verify(self, tag: crtag, apikey: str, timeout=None): """Check the API Key of a player. This endpoint has been **restricted** to certain members of the community Raises BadRequest if the apikey is invalid Parameters ---------- tag: str ...
def get_player_battles(self, tag: crtag, **params: keys): """Get a player's battle log Parameters ---------- tag: str A valid tournament tag. Minimum length: 3 Valid characters: 0289PYLQGRJCUV \*\*limit: Optional[int] = None Limit the number o...
def get_player_chests(self, tag: crtag, timeout: int=None): """Get information about a player's chest cycle Parameters ---------- tag: str A valid tournament tag. Minimum length: 3 Valid characters: 0289PYLQGRJCUV timeout: Optional[int] = None ...
def get_clan(self, tag: crtag, timeout: int=None): """Get inforamtion about a clan Parameters ---------- tag: str A valid tournament tag. Minimum length: 3 Valid characters: 0289PYLQGRJCUV timeout: Optional[int] = None Custom timeout that over...
def search_clans(self, **params: clansearch): """Search for a clan. At least one of the filters must be present Parameters ---------- name: Optional[str] The name of a clan (has to be at least 3 characters long) locationId: Optional[int] ...
def get_clan_war(self, tag: crtag, timeout: int=None): """Get inforamtion about a clan's current clan war Parameters ---------- tag: str A valid tournament tag. Minimum length: 3 Valid characters: 0289PYLQGRJCUV timeout: Optional[int] = None C...
def get_tournament(self, tag: crtag, timeout=0): """Get a tournament information Parameters ---------- tag: str A valid tournament tag. Minimum length: 3 Valid characters: 0289PYLQGRJCUV \*\*timeout: Optional[int] = None Custom timeout that ov...
def search_tournaments(self, name: str, **params: keys): """Search for a tournament by its name Parameters ---------- name: str The name of a tournament \*\*limit: Optional[int] = None Limit the number of items returned in the response \*\*timeout...
def get_all_cards(self, timeout: int=None): """Get a list of all the cards in the game Parameters ---------- timeout: Optional[int] = None Custom timeout that overwrites Client.timeout """ url = self.api.CARDS return self._get_model(url, timeout=timeo...
def get_all_locations(self, timeout: int=None): """Get a list of all locations Parameters ---------- timeout: Optional[int] = None Custom timeout that overwrites Client.timeout """ url = self.api.LOCATIONS return self._get_model(url, timeout=timeout)
def get_location(self, location_id: int, timeout: int=None): """Get a location information Parameters ---------- location_id: int A location ID See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json for a list of acceptable locatio...
def get_top_clans(self, location_id='global', **params: keys): """Get a list of top clans by trophy Parameters ---------- location_id: Optional[str] = 'global' A location ID or global See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json ...
def get_top_players(self, location_id='global', **params: keys): """Get a list of top players Parameters ---------- location_id: Optional[str] = 'global' A location ID or global See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json ...
def get_clan_image(self, obj: BaseAttrDict): """Get the clan badge image URL Parameters --------- obj: official_api.models.BaseAttrDict An object that has the clan badge ID either in ``.clan.badge_id`` or ``.badge_id`` Can be a clan or a profile for example. ...
def get_arena_image(self, obj: BaseAttrDict): """Get the arena image URL Parameters --------- obj: official_api.models.BaseAttrDict An object that has the arena ID in ``.arena.id`` Can be ``Profile`` for example. Returns None or str """ b...
def get_card_info(self, card_name: str): """Returns card info from constants Parameters --------- card_name: str A card name Returns None or Constants """ for c in self.constants.cards: if c.name == card_name: return c
def get_rarity_info(self, rarity: str): """Returns card info from constants Parameters --------- rarity: str A rarity name Returns None or Constants """ for c in self.constants.rarities: if c.name == rarity: return c
def get_deck_link(self, deck: BaseAttrDict): """Form a deck link Parameters --------- deck: official_api.models.BaseAttrDict An object is a deck. Can be retrieved from ``Player.current_deck`` Returns str """ deck_link = 'https://link.clashroyale.com/...
def get_datetime(self, timestamp: str, unix=True): """Converts a %Y%m%dT%H%M%S.%fZ to a UNIX timestamp or a datetime.datetime object Parameters --------- timestamp: str A timstamp in the %Y%m%dT%H%M%S.%fZ format, usually returned by the API in the ``creat...
def get_clan(self): """(a)sync function to return clan.""" try: return self.client.get_clan(self.clan.tag) except AttributeError: try: return self.client.get_clan(self.tag) except AttributeError: raise ValueError('This player do...
def refresh(self): """(a)sync refresh the data.""" if self.client.is_async: return self._arefresh() data, cached, ts, response = self.client._request(self.response.url, timeout=None, refresh=True) return self.from_data(data, cached, ts, response)
def typecasted(func): """Decorator that converts arguments via annotations.""" signature = inspect.signature(func).parameters.items() @wraps(func) def wrapper(*args, **kwargs): args = list(args) new_args = [] new_kwargs = {} for _, param in signature: convert...
def coerce_annotation(ann, namespace): '''Validate that the annotation has the correct namespace, and is well-formed. If the annotation is not of the correct namespace, automatic conversion is attempted. Parameters ---------- ann : jams.Annotation The annotation object in question ...