Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def adapt(self, d, x): y = np.dot(self.w, x) e = d - y R1 = np.dot(np.dot(np.dot(self.R,x),x.T),self.R) R2 = self.mu + np.dot(np.dot(x,self.R),x.T) self.R = 1/self.mu * (self.R - R1/R2) dw = np.dot(self.R, x.T) * e ...
[ "\n Adapt weights according one desired value and its input.\n\n **Args:**\n\n * `d` : desired value (float)\n\n * `x` : input array (1-dimensional array)\n " ]
Please provide a description of the function:def run(self, d, x): # measure the data and check if the dimmension agree N = len(x) if not len(d) == N: raise ValueError('The length of vector d and matrix x must agree.') self.n = len(x[0]) # prepare data ...
[ "\n This function filters multiple samples in a row.\n\n **Args:**\n\n * `d` : desired value (1 dimensional array)\n\n * `x` : input matrix (2-dimensional array). Rows are samples,\n columns are input arrays.\n\n **Returns:**\n\n * `y` : output value (1 dimension...
Please provide a description of the function:def adapt(self, d, x): # create input matrix and target vector self.x_mem[:,1:] = self.x_mem[:,:-1] self.x_mem[:,0] = x self.d_mem[1:] = self.d_mem[:-1] self.d_mem[0] = d # estimate output and error self.y_mem ...
[ "\n Adapt weights according one desired value and its input.\n\n **Args:**\n\n * `d` : desired value (float)\n\n * `x` : input array (1-dimensional array)\n " ]
Please provide a description of the function:def run(self, d, x): # measure the data and check if the dimmension agree N = len(x) if not len(d) == N: raise ValueError('The length of vector d and matrix x must agree.') self.n = len(x[0]) # prepare data ...
[ "\n This function filters multiple samples in a row.\n\n **Args:**\n\n * `d` : desired value (1 dimensional array)\n\n * `x` : input matrix (2-dimensional array). Rows are samples,\n columns are input arrays.\n\n **Returns:**\n\n * `y` : output value (1 dimensional...
Please provide a description of the function:def LDA_base(x, labels): classes = np.array(tuple(set(labels))) cols = x.shape[1] # mean values for every class means = np.zeros((len(classes), cols)) for i, cl in enumerate(classes): means[i] = np.mean(x[labels==cl], axis=0) # scatter ma...
[ "\n Base function used for Linear Discriminant Analysis.\n\n **Args:**\n\n * `x` : input matrix (2d array), every row represents new sample\n\n * `labels` : list of labels (iterable), every item should be label for \\\n sample with corresponding index\n\n **Returns:**\n \n * `eigenvalues`,...
Please provide a description of the function:def LDA(x, labels, n=False): # select n if not provided if not n: n = x.shape[1] - 1 # validate inputs try: x = np.array(x) except: raise ValueError('Impossible to convert x to a numpy array.') assert type(n) == int, ...
[ "\n Linear Discriminant Analysis function.\n\n **Args:**\n\n * `x` : input matrix (2d array), every row represents new sample\n\n * `labels` : list of labels (iterable), every item should be label for \\\n sample with corresponding index\n\n **Kwargs:**\n\n * `n` : number of features returned...
Please provide a description of the function:def LDA_discriminants(x, labels): # validate inputs try: x = np.array(x) except: raise ValueError('Impossible to convert x to a numpy array.') # make the LDA eigen_values, eigen_vectors = LDA_base(x, labels) return eigen_value...
[ "\n Linear Discriminant Analysis helper for determination how many columns of\n data should be reduced.\n\n **Args:**\n\n * `x` : input matrix (2d array), every row represents new sample\n\n * `labels` : list of labels (iterable), every item should be label for \\\n sample with corresponding i...
Please provide a description of the function:def adapt(self, d, x): y = np.dot(self.w, x) e = d - y self.eps = self.eps - self.ro * self.mu * e * self.last_e * \ np.dot(x, self.last_x) / \ (np.dot(self.last_x, self.last_x) + self.eps)**2 nu = self.mu / (s...
[ "\n Adapt weights according one desired value and its input.\n\n **Args:**\n\n * `d` : desired value (float)\n\n * `x` : input array (1-dimensional array)\n " ]
Please provide a description of the function:def adapt(self, d, x): self.update_memory_x(x) m_d, m_x = self.read_memory() # estimate y = np.dot(self.w, x-m_x) + m_d e = d - y nu = self.mu / (self.eps + np.dot(x-m_x, x-m_x)) dw = nu * e * (x-m_x) s...
[ "\n Adapt weights according one desired value and its input.\n\n Args:\n\n * `d` : desired value (float)\n\n * `x` : input array (1-dimensional array)\n " ]
Please provide a description of the function:def read_memory(self): if self.mem_empty == True: if self.mem_idx == 0: m_x = np.zeros(self.n) m_d = 0 else: m_x = np.mean(self.mem_x[:self.mem_idx+1], axis=0) m_d = np.m...
[ "\n This function read mean value of target`d`\n and input vector `x` from history\n " ]
Please provide a description of the function:def filter_data(d, x, model="lms", **kwargs): # overwrite n with correct size kwargs["n"] = x.shape[1] # create filter according model if model in ["LMS", "lms"]: f = FilterLMS(**kwargs) elif model in ["NLMS", "nlms"]: f = FilterNLMS(...
[ "\n Function that filter data with selected adaptive filter.\n \n **Args:**\n\n * `d` : desired value (1 dimensional array)\n\n * `x` : input matrix (2-dimensional array). Rows are samples, columns are\n input arrays.\n \n **Kwargs:**\n \n * Any key argument that can be accepted ...
Please provide a description of the function:def AdaptiveFilter(model="lms", **kwargs): # check if the filter size was specified if not "n" in kwargs: raise ValueError('Filter size is not defined (n=?).') # create filter according model if model in ["LMS", "lms"]: f = FilterLMS(...
[ "\n Function that filter data with selected adaptive filter.\n \n **Args:**\n\n * `d` : desired value (1 dimensional array)\n\n * `x` : input matrix (2-dimensional array). Rows are samples, columns are \n input arrays.\n \n **Kwargs:**\n \n * Any key argument that can be accepted...
Please provide a description of the function:def learning_entropy(w, m=10, order=1, alpha=False): w = np.array(w) # get length of data and number of parameters N = w.shape[0] n = w.shape[1] # get abs dw from w dw = np.copy(w) dw[order:] = np.abs(np.diff(dw, n=order, axis=0)) # avera...
[ "\n This function estimates Learning Entropy.\n\n **Args:**\n\n * `w` : history of adaptive parameters of an adaptive model (2d array),\n every row represents parameters in given time index.\n\n **Kwargs:**\n\n * `m` : window size (1d array) - how many last samples are used for\n evaluation...
Please provide a description of the function:def activation(self, x, f="sigmoid", der=False): if f == "sigmoid": if der: return x * (1 - x) return 1. / (1 + np.exp(-x)) elif f == "tanh": if der: return 1 - x**2 ret...
[ "\n This function process values of layer outputs with activation function.\n\n **Args:**\n\n * `x` : array to process (1-dimensional array) \n\n **Kwargs:**\n\n * `f` : activation function\n\n * `der` : normal output, or its derivation (bool)\n\n **Returns:**\n\n ...
Please provide a description of the function:def predict(self, x): self.x[1:] = x self.y = self.activation(np.sum(self.w*self.x, axis=1), f=self.f) return self.y
[ "\n This function make forward pass through this layer (no update).\n\n **Args:**\n\n * `x` : input vector (1-dimensional array)\n\n **Returns:**\n \n * `y` : output of MLP (float or 1-diemnsional array).\n Size depends on number of nodes in this layer.\n ...
Please provide a description of the function:def update(self, w, e): if len(w.shape) == 1: e = self.activation(self.y, f=self.f, der=True) * e * w dw = self.mu * np.outer(e, self.x) else: e = self.activation(self.y, f=self.f, der=True) * (1 - self.y) * np.dot...
[ "\n This function make update according provided target\n and the last used input vector.\n\n **Args:**\n\n * `d` : target (float or 1-dimensional array).\n Size depends on number of MLP outputs.\n\n **Returns:**\n\n * `w` : weights of the layers (2-dimensional l...
Please provide a description of the function:def train(self, x, d, epochs=10, shuffle=False): # measure the data and check if the dimmension agree N = len(x) if not len(d) == N: raise ValueError('The length of vector d and matrix x must agree.') if not len(x[0]) ==...
[ "\n Function for batch training of MLP.\n\n **Args:**\n\n * `x` : input array (2-dimensional array).\n Every row represents one input vector (features).\n\n * `d` : input array (n-dimensional array).\n Every row represents target for one input vector.\n T...
Please provide a description of the function:def run(self, x): # measure the data and check if the dimmension agree try: x = np.array(x) except: raise ValueError('Impossible to convert x to a numpy array') N = len(x) # create empty arrays ...
[ "\n Function for batch usage of already trained and tested MLP.\n\n **Args:**\n\n * `x` : input array (2-dimensional array).\n Every row represents one input vector (features).\n\n **Returns:**\n \n * `y`: output vector (n-dimensional array). Every row represents...
Please provide a description of the function:def predict(self, x): # forward pass to hidden layers for l in self.layers: x = l.predict(x) self.x[1:] = x # forward pass to output layer if self.outputs == 1: self.y = np.dot(self.w, self.x) e...
[ "\n This function make forward pass through MLP (no update).\n\n **Args:**\n\n * `x` : input vector (1-dimensional array)\n\n **Returns:**\n \n * `y` : output of MLP (float or 1-diemnsional array).\n Size depends on number of MLP outputs.\n \n "...
Please provide a description of the function:def update(self, d): # update output layer e = d - self.y error = np.copy(e) if self.outputs == 1: dw = self.mu * e * self.x w = np.copy(self.w)[1:] else: dw = self.mu * np.outer(e, self....
[ "\n This function make update according provided target\n and the last used input vector.\n\n **Args:**\n\n * `d` : target (float or 1-dimensional array).\n Size depends on number of MLP outputs.\n\n **Returns:**\n \n * `e` : error used for update (float o...
Please provide a description of the function:def PCA_components(x): # validate inputs try: x = np.array(x) except: raise ValueError('Impossible to convert x to a numpy array.') # eigen values and eigen vectors of data covariance matrix eigen_values, eigen_vectors = np.linal...
[ "\n Principal Component Analysis helper to check out eigenvalues of components.\n\n **Args:**\n\n * `x` : input matrix (2d array), every row represents new sample\n\n **Returns:**\n \n * `components`: sorted array of principal components eigenvalues \n \n " ]
Please provide a description of the function:def PCA(x, n=False): # select n if not provided if not n: n = x.shape[1] - 1 # validate inputs try: x = np.array(x) except: raise ValueError('Impossible to convert x to a numpy array.') assert type(n) == int, "Provi...
[ "\n Principal component analysis function.\n\n **Args:**\n\n * `x` : input matrix (2d array), every row represents new sample\n\n **Kwargs:**\n\n * `n` : number of features returned (integer) - how many columns \n should the output keep\n\n **Returns:**\n \n * `new_x` : matrix with redu...
Please provide a description of the function:def clean_axis(axis): axis.get_xaxis().set_ticks([]) axis.get_yaxis().set_ticks([]) for spine in list(axis.spines.values()): spine.set_visible(False)
[ "Remove ticks, tick labels, and frame from axis" ]
Please provide a description of the function:def get_seaborn_colorbar(dfr, classes): levels = sorted(list(set(classes.values()))) paldict = { lvl: pal for (lvl, pal) in zip( levels, sns.cubehelix_palette( len(levels), light=0.9, dark=0.1, reverse=True...
[ "Return a colorbar representing classes, for a Seaborn plot.\n\n The aim is to get a pd.Series for the passed dataframe columns,\n in the form:\n 0 colour for class in col 0\n 1 colour for class in col 1\n ... colour for class in col ...\n n colour for class in col n\n " ]
Please provide a description of the function:def get_safe_seaborn_labels(dfr, labels): if labels is not None: return [labels.get(i, i) for i in dfr.index] return [i for i in dfr.index]
[ "Returns labels guaranteed to correspond to the dataframe." ]
Please provide a description of the function:def get_seaborn_clustermap(dfr, params, title=None, annot=True): fig = sns.clustermap( dfr, cmap=params.cmap, vmin=params.vmin, vmax=params.vmax, col_colors=params.colorbar, row_colors=params.colorbar, figsize=...
[ "Returns a Seaborn clustermap." ]
Please provide a description of the function:def heatmap_seaborn(dfr, outfilename=None, title=None, params=None): # Decide on figure layout size: a minimum size is required for # aesthetics, and a maximum to avoid core dumps on rendering. # If we hit the maximum size, we should modify font size. ma...
[ "Returns seaborn heatmap with cluster dendrograms.\n\n - dfr - pandas DataFrame with relevant data\n - outfilename - path to output file (indicates output format)\n " ]
Please provide a description of the function:def add_mpl_dendrogram(dfr, fig, heatmap_gs, orientation="col"): # Row or column axes? if orientation == "row": dists = distance.squareform(distance.pdist(dfr)) spec = heatmap_gs[1, 0] orient = "left" nrows, ncols = 1, 2 h...
[ "Return a dendrogram and corresponding gridspec, attached to the fig\n\n Modifies the fig in-place. Orientation is either 'row' or 'col' and\n determines location and orientation of the rendered dendrogram.\n " ]
Please provide a description of the function:def get_mpl_heatmap_axes(dfr, fig, heatmap_gs): # Create heatmap axis heatmap_axes = fig.add_subplot(heatmap_gs[1, 1]) heatmap_axes.set_xticks(np.linspace(0, dfr.shape[0] - 1, dfr.shape[0])) heatmap_axes.set_yticks(np.linspace(0, dfr.shape[0] - 1, dfr.sh...
[ "Return axis for Matplotlib heatmap." ]
Please provide a description of the function:def add_mpl_colorbar(dfr, fig, dend, params, orientation="row"): for name in dfr.index[dend["dendrogram"]["leaves"]]: if name not in params.classes: params.classes[name] = name # Assign a numerical value to each class, for mpl classdict ...
[ "Add class colorbars to Matplotlib heatmap." ]
Please provide a description of the function:def add_mpl_labels(heatmap_axes, rowlabels, collabels, params): if params.labels: # If a label mapping is missing, use the key text as fall back rowlabels = [params.labels.get(lab, lab) for lab in rowlabels] collabels = [params.labels.get(lab...
[ "Add labels to Matplotlib heatmap axes, in-place." ]
Please provide a description of the function:def add_mpl_colorscale(fig, heatmap_gs, ax_map, params, title=None): # Set tick intervals cbticks = [params.vmin + e * params.vdiff for e in (0, 0.25, 0.5, 0.75, 1)] if params.vmax > 10: exponent = int(floor(log10(params.vmax))) - 1 cbticks =...
[ "Add colour scale to heatmap." ]
Please provide a description of the function:def heatmap_mpl(dfr, outfilename=None, title=None, params=None): # Layout figure grid and add title # Set figure size by the number of rows in the dataframe figsize = max(8, dfr.shape[0] * 0.175) fig = plt.figure(figsize=(figsize, figsize)) # if titl...
[ "Returns matplotlib heatmap with cluster dendrograms.\n\n - dfr - pandas DataFrame with relevant data\n - outfilename - path to output file (indicates output format)\n - params - a list of parameters for plotting: [colormap, vmin, vmax]\n - labels - dictionary of alternative labels, keyed by default seq...
Please provide a description of the function:def run_dependency_graph(jobgraph, workers=None, logger=None): cmdsets = [] for job in jobgraph: cmdsets = populate_cmdsets(job, cmdsets, depth=1) # Put command sets in reverse order, and submit to multiprocessing_run cmdsets.reverse() cumre...
[ "Creates and runs pools of jobs based on the passed jobgraph.\n\n - jobgraph - list of jobs, which may have dependencies.\n - verbose - flag for multiprocessing verbosity\n - logger - a logger module logger (optional)\n\n The strategy here is to loop over each job in the list of jobs (jobgraph),\n an...
Please provide a description of the function:def populate_cmdsets(job, cmdsets, depth): if len(cmdsets) < depth: cmdsets.append(set()) cmdsets[depth-1].add(job.command) if len(job.dependencies) == 0: return cmdsets for j in job.dependencies: cmdsets = populate_cmdsets(j, cmd...
[ "Creates a list of sets containing jobs at different depths of the\n dependency tree.\n\n This is a recursive function (is there something quicker in the itertools\n module?) that descends each 'root' job in turn, populating each\n " ]
Please provide a description of the function:def multiprocessing_run(cmdlines, workers=None): # Run jobs # If workers is None or greater than the number of cores available, # it will be set to the maximum number of cores pool = multiprocessing.Pool(processes=workers) results = [pool.apply_async...
[ "Distributes passed command-line jobs using multiprocessing.\n\n - cmdlines - an iterable of command line strings\n\n Returns the sum of exit codes from each job that was run. If\n all goes well, this should be 0. Anything else and the calling\n function should act accordingly.\n " ]
Please provide a description of the function:def get_input_files(dirname, *ext): filelist = [f for f in os.listdir(dirname) if os.path.splitext(f)[-1] in ext] return [os.path.join(dirname, f) for f in filelist]
[ "Returns files in passed directory, filtered by extension.\n\n - dirname - path to input directory\n - *ext - list of arguments describing permitted file extensions\n " ]
Please provide a description of the function:def get_sequence_lengths(fastafilenames): tot_lengths = {} for fn in fastafilenames: tot_lengths[os.path.splitext(os.path.split(fn)[-1])[0]] = \ sum([len(s) for s in SeqIO.parse(fn, 'fasta')]) return tot_lengths
[ "Returns dictionary of sequence lengths, keyed by organism.\n\n Biopython's SeqIO module is used to parse all sequences in the FASTA\n file corresponding to each organism, and the total base count in each\n is obtained.\n\n NOTE: ambiguity symbols are not discounted.\n " ]
Please provide a description of the function:def parse_cmdline(): parser = ArgumentParser(prog="average_nucleotide_identity.py") parser.add_argument( "--version", action="version", version="%(prog)s: pyani " + VERSION ) parser.add_argument( "-o", "--outdir", dest="ou...
[ "Parse command-line arguments for script." ]
Please provide a description of the function:def last_exception(): exc_type, exc_value, exc_traceback = sys.exc_info() return "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
[ " Returns last exception as a string, or use in logging.\n " ]
Please provide a description of the function:def make_outdir(): if os.path.exists(args.outdirname): if not args.force: logger.error( "Output directory %s would overwrite existing " + "files (exiting)", args.outdirname, ) sys.exit(1) ...
[ "Make the output directory, if required.\n\n This is a little involved. If the output directory already exists,\n we take the safe option by default, and stop with an error. We can,\n however, choose to force the program to go on, in which case we can\n either clobber the existing directory, or not. ...
Please provide a description of the function:def compress_delete_outdir(outdir): # Compress output in .tar.gz file and remove raw output tarfn = outdir + ".tar.gz" logger.info("\tCompressing output from %s to %s", outdir, tarfn) with tarfile.open(tarfn, "w:gz") as fh: fh.add(outdir) log...
[ "Compress the contents of the passed directory to .tar.gz and delete." ]
Please provide a description of the function:def calculate_anim(infiles, org_lengths): logger.info("Running ANIm") logger.info("Generating NUCmer command-lines") deltadir = os.path.join(args.outdirname, ALIGNDIR["ANIm"]) logger.info("Writing nucmer output to %s", deltadir) # Schedule NUCmer run...
[ "Returns ANIm result dataframes for files in input directory.\n\n - infiles - paths to each input file\n - org_lengths - dictionary of input sequence lengths, keyed by sequence\n\n Finds ANI by the ANIm method, as described in Richter et al (2009)\n Proc Natl Acad Sci USA 106: 19126-19131 doi:10.1073/pn...
Please provide a description of the function:def calculate_tetra(infiles): logger.info("Running TETRA.") # First, find Z-scores logger.info("Calculating TETRA Z-scores for each sequence.") tetra_zscores = {} for filename in infiles: logger.info("Calculating TETRA Z-scores for %s", filen...
[ "Calculate TETRA for files in input directory.\n\n - infiles - paths to each input file\n - org_lengths - dictionary of input sequence lengths, keyed by sequence\n\n Calculates TETRA correlation scores, as described in:\n\n Richter M, Rossello-Mora R (2009) Shifting the genomic gold standard for\n th...
Please provide a description of the function:def unified_anib(infiles, org_lengths): logger.info("Running %s", args.method) blastdir = os.path.join(args.outdirname, ALIGNDIR[args.method]) logger.info("Writing BLAST output to %s", blastdir) # Build BLAST databases and run pairwise BLASTN if not ...
[ "Calculate ANIb for files in input directory.\n\n - infiles - paths to each input file\n - org_lengths - dictionary of input sequence lengths, keyed by sequence\n\n Calculates ANI by the ANIb method, as described in Goris et al. (2007)\n Int J Syst Evol Micr 57: 81-91. doi:10.1099/ijs.0.64483-0. There a...
Please provide a description of the function:def write(results): logger.info("Writing %s results to %s", args.method, args.outdirname) if args.method == "TETRA": out_excel = os.path.join(args.outdirname, TETRA_FILESTEMS[0]) + ".xlsx" out_csv = os.path.join(args.outdirname, TETRA_FILESTEMS[0...
[ "Write ANIb/ANIm/TETRA results to output directory.\n\n - results - results object from analysis\n\n Each dataframe is written to an Excel-format file (if args.write_excel is\n True), and plain text tab-separated file in the output directory. The\n order of result output must be reflected in the order o...
Please provide a description of the function:def draw(filestems, gformat): # Draw heatmaps for filestem in filestems: fullstem = os.path.join(args.outdirname, filestem) outfilename = fullstem + ".%s" % gformat infilename = fullstem + ".tab" df = pd.read_csv(infilename, index...
[ "Draw ANIb/ANIm/TETRA results\n\n - filestems - filestems for output files\n - gformat - the format for output graphics\n " ]
Please provide a description of the function:def subsample_input(infiles): logger.info("--subsample: %s", args.subsample) try: samplesize = float(args.subsample) except TypeError: # Not a number logger.error( "--subsample must be int or float, got %s (exiting)", type(args.s...
[ "Returns a random subsample of the input files.\n\n - infiles: a list of input files for analysis\n " ]
Please provide a description of the function:def wait(self, interval=SGE_WAIT): finished = False while not finished: time.sleep(interval) interval = min(2 * interval, 60) finished = os.system("qstat -j %s > /dev/null" % (self.name))
[ "Wait until the job finishes, and poll SGE on its status." ]
Please provide a description of the function:def generate_script(self): self.script = "" # Holds the script string total = 1 # total number of jobs in this group # for now, SGE_TASK_ID becomes TASK_ID, but we base it at zero self.script += # build...
[ "Create the SGE script that will run the jobs in the JobGroup, with\n the passed arguments.\n ", "let \"TASK_ID=$SGE_TASK_ID - 1\"\\n", "let \"%s_INDEX=$TASK_ID %% %d\"\\n", "%s=${%s_ARRAY[$%s_INDEX]}\\n", "let \"TASK_ID=$TASK_ID / %d\"\\n" ]
Please provide a description of the function:def generate_nucmer_jobs( filenames, outdir=".", nucmer_exe=pyani_config.NUCMER_DEFAULT, filter_exe=pyani_config.FILTER_DEFAULT, maxmatch=False, jobprefix="ANINUCmer", ): ncmds, fcmds = generate_nucmer_commands( filenames, outdir, nuc...
[ "Return a list of Jobs describing NUCmer command-lines for ANIm\n\n - filenames - a list of paths to input FASTA files\n - outdir - path to output directory\n - nucmer_exe - location of the nucmer binary\n - maxmatch - Boolean flag indicating to use NUCmer's -maxmatch option\n\n Loop over all FASTA f...
Please provide a description of the function:def generate_nucmer_commands( filenames, outdir=".", nucmer_exe=pyani_config.NUCMER_DEFAULT, filter_exe=pyani_config.FILTER_DEFAULT, maxmatch=False, ): nucmer_cmdlines, delta_filter_cmdlines = [], [] for idx, fname1 in enumerate(filenames[:-1...
[ "Return a tuple of lists of NUCmer command-lines for ANIm\n\n The first element is a list of NUCmer commands, the second a list\n of delta_filter_wrapper.py commands. These are ordered such that\n commands are paired. The NUCmer commands should be run before\n the delta-filter commands.\n\n - filenam...
Please provide a description of the function:def construct_nucmer_cmdline( fname1, fname2, outdir=".", nucmer_exe=pyani_config.NUCMER_DEFAULT, filter_exe=pyani_config.FILTER_DEFAULT, maxmatch=False, ): outsubdir = os.path.join(outdir, pyani_config.ALIGNDIR["ANIm"]) outprefix = os.pa...
[ "Returns a tuple of NUCmer and delta-filter commands\n\n The split into a tuple was made necessary by changes to SGE/OGE. The\n delta-filter command must now be run as a dependency of the NUCmer\n command, and be wrapped in a Python script to capture STDOUT.\n\n NOTE: This command-line writes output dat...
Please provide a description of the function:def parse_delta(filename): aln_length, sim_errors = 0, 0 for line in [l.strip().split() for l in open(filename, "r").readlines()]: if line[0] == "NUCMER" or line[0].startswith(">"): # Skip headers continue # We only process lines wit...
[ "Returns (alignment length, similarity errors) tuple from passed .delta.\n\n - filename - path to the input .delta file\n\n Extracts the aligned length and number of similarity errors for each\n aligned uniquely-matched region, and returns the cumulative total for\n each as a tuple.\n " ]
Please provide a description of the function:def process_deltadir(delta_dir, org_lengths, logger=None): # Process directory to identify input files - as of v0.2.4 we use the # .filter files that result from delta-filter (1:1 alignments) deltafiles = pyani_files.get_input_files(delta_dir, ".filter") ...
[ "Returns a tuple of ANIm results for .deltas in passed directory.\n\n - delta_dir - path to the directory containing .delta files\n - org_lengths - dictionary of total sequence lengths, keyed by sequence\n\n Returns the following pandas dataframes in an ANIResults object;\n query sequences are rows, sub...
Please provide a description of the function:def parse_cmdline(): parser = ArgumentParser(prog="genbank_get_genomes_by_taxon.py") parser.add_argument( "-o", "--outdir", dest="outdirname", required=True, action="store", default=None, help="Output direc...
[ "Parse command-line arguments" ]
Please provide a description of the function:def set_ncbi_email(): Entrez.email = args.email logger.info("Set NCBI contact email to %s", args.email) Entrez.tool = "genbank_get_genomes_by_taxon.py"
[ "Set contact email for NCBI." ]
Please provide a description of the function:def entrez_retry(func, *fnargs, **fnkwargs): tries, success = 0, False while not success and tries < args.retries: try: output = func(*fnargs, **fnkwargs) success = True except (HTTPError, URLError): tries += 1...
[ "Retries the passed function up to the number of times specified\n by args.retries\n " ]
Please provide a description of the function:def entrez_batch_webhistory(record, expected, batchsize, *fnargs, **fnkwargs): results = [] for start in range(0, expected, batchsize): batch_handle = entrez_retry( Entrez.efetch, retstart=start, retmax=batchsize, ...
[ "Recovers the Entrez data from a prior NCBI webhistory search, in\n batches of defined size, using Efetch. Returns all results as a list.\n\n - record: Entrez webhistory record\n - expected: number of expected search returns\n - batchsize: how many search returns to retrieve in a batch\n - *fnargs: a...
Please provide a description of the function:def get_asm_uids(taxon_uid): query = "txid%s[Organism:exp]" % taxon_uid logger.info("Entrez ESearch with query: %s", query) # Perform initial search for assembly UIDs with taxon ID as query. # Use NCBI history for the search. handle = entrez_retry( ...
[ "Returns a set of NCBI UIDs associated with the passed taxon.\n\n This query at NCBI returns all assemblies for the taxon subtree\n rooted at the passed taxon_uid.\n " ]
Please provide a description of the function:def extract_filestem(data): escapes = re.compile(r"[\s/,#\(\)]") escname = re.sub(escapes, '_', data['AssemblyName']) return '_'.join([data['AssemblyAccession'], escname])
[ "Extract filestem from Entrez eSummary data.\n\n Function expects esummary['DocumentSummarySet']['DocumentSummary'][0]\n\n Some illegal characters may occur in AssemblyName - for these, a more\n robust regex replace/escape may be required. Sadly, NCBI don't just\n use standard percent escapes, but inste...
Please provide a description of the function:def get_ncbi_asm(asm_uid, fmt='fasta'): logger.info("Identifying assembly information from NCBI for %s", asm_uid) # Obtain full eSummary data for the assembly summary = Entrez.read( entrez_retry( Entrez.esummary, db="assembly", id=asm_ui...
[ "Returns the NCBI AssemblyAccession and AssemblyName for the assembly\n with passed UID, and organism data for class/label files also, as well\n as accession, so we can track whether downloads fail because only the\n most recent version is available..\n\n AssemblyAccession and AssemblyName are data fiel...
Please provide a description of the function:def retrieve_asm_contigs(filestem, ftpstem="ftp://ftp.ncbi.nlm.nih.gov/genomes/all", fmt='fasta'): logger.info("Retrieving assembly sequence for %s", filestem) # Define format suffix logger.info("%s format r...
[ "Downloads an assembly sequence to a local directory.\n\n The filestem corresponds to <AA>_<AN>, where <AA> and <AN> are\n AssemblyAccession and AssemblyName: data fields in the eSummary record.\n These correspond to downloadable files for each assembly at\n ftp://ftp.ncbi.nlm.nih.gov/genomes/all/GC[AF]...
Please provide a description of the function:def write_contigs(asm_uid, contig_uids, batchsize=10000): # Has duplicate code with get_class_label_info() - needs refactoring logger.info("Collecting contig data for %s", asm_uid) # Assembly record - get binomial and strain names asm_record = Entrez.rea...
[ "Writes assembly contigs out to a single FASTA file in the script's\n designated output directory.\n\n FASTA records are returned, as GenBank and even GenBankWithParts format\n records don't reliably give correct sequence in all cases.\n\n The script returns two strings for each assembly, a 'class' and ...
Please provide a description of the function:def logreport_downloaded(accession, skippedlist, accessiondict, uidaccdict): for vid in accessiondict[accession.split('.')[0]]: if vid in skippedlist: status = "NOT DOWNLOADED" else: status = "DOWNLOADED" logger.warnin...
[ "Reports to logger whether alternative assemblies for an accession that\n was missing have been downloaded\n " ]
Please provide a description of the function:def calculate_tetra_zscores(infilenames): org_tetraz = {} for filename in infilenames: org = os.path.splitext(os.path.split(filename)[-1])[0] org_tetraz[org] = calculate_tetra_zscore(filename) return org_tetraz
[ "Returns dictionary of TETRA Z-scores for each input file.\n\n - infilenames - collection of paths to sequence files\n " ]
Please provide a description of the function:def calculate_tetra_zscore(filename): # For the Teeling et al. method, the Z-scores require us to count # mono, di, tri and tetranucleotide sequences - these are stored # (in order) in the counts tuple counts = (collections.defaultdict(int), collections....
[ "Returns TETRA Z-score for the sequence in the passed file.\n\n - filename - path to sequence file\n\n Calculates mono-, di-, tri- and tetranucleotide frequencies\n for each sequence, on each strand, and follows Teeling et al. (2004)\n in calculating a corresponding Z-score for each observed\n tetran...
Please provide a description of the function:def calculate_correlations(tetra_z): orgs = sorted(tetra_z.keys()) correlations = pd.DataFrame(index=orgs, columns=orgs, dtype=float).fillna(1.0) for idx, org1 in enumerate(orgs[:-1]): for org2 in orgs[idx+1:]: ...
[ "Returns dataframe of Pearson correlation coefficients.\n\n - tetra_z - dictionary of Z-scores, keyed by sequence ID\n\n Calculates Pearson correlation coefficient from Z scores for each\n tetranucleotide. This is done longhand here, which is fast enough,\n but for robustness we might want to do somethi...
Please provide a description of the function:def get_labels(filename, logger=None): labeldict = {} if filename is not None: if logger: logger.info("Reading labels from %s", filename) with open(filename, "r") as ifh: count = 0 for line in ifh.readlines(): ...
[ "Returns a dictionary of alternative sequence labels, or None\n\n - filename - path to file containing tab-separated table of labels\n\n Input files should be formatted as <key>\\t<label>, one pair per line.\n " ]
Please provide a description of the function:def add_tot_length(self, qname, sname, value, sym=True): self.alignment_lengths.loc[qname, sname] = value if sym: self.alignment_lengths.loc[sname, qname] = value
[ "Add a total length value to self.alignment_lengths." ]
Please provide a description of the function:def add_sim_errors(self, qname, sname, value, sym=True): self.similarity_errors.loc[qname, sname] = value if sym: self.similarity_errors.loc[sname, qname] = value
[ "Add a similarity error value to self.similarity_errors." ]
Please provide a description of the function:def add_pid(self, qname, sname, value, sym=True): self.percentage_identity.loc[qname, sname] = value if sym: self.percentage_identity.loc[sname, qname] = value
[ "Add a percentage identity value to self.percentage_identity." ]
Please provide a description of the function:def add_coverage(self, qname, sname, qcover, scover=None): self.alignment_coverage.loc[qname, sname] = qcover if scover: self.alignment_coverage.loc[sname, qname] = scover
[ "Add percentage coverage values to self.alignment_coverage." ]
Please provide a description of the function:def data(self): stemdict = { "ANIm": pyani_config.ANIM_FILESTEMS, "ANIb": pyani_config.ANIB_FILESTEMS, "ANIblastall": pyani_config.ANIBLASTALL_FILESTEMS, } return zip( ( self.ali...
[ "Return list of (dataframe, filestem) tuples." ]
Please provide a description of the function:def build_db_cmd(self, fname): return self.funcs.db_func(fname, self.outdir, self.exes.format_exe)[0]
[ "Return database format/build command" ]
Please provide a description of the function:def get_db_name(self, fname): return self.funcs.db_func(fname, self.outdir, self.exes.format_exe)[1]
[ "Return database filename" ]
Please provide a description of the function:def build_blast_cmd(self, fname, dbname): return self.funcs.blastn_func(fname, dbname, self.outdir, self.exes.blast_exe)
[ "Return BLASTN command" ]
Please provide a description of the function:def fragment_fasta_files(infiles, outdirname, fragsize): outfnames = [] for fname in infiles: outstem, outext = os.path.splitext(os.path.split(fname)[-1]) outfname = os.path.join(outdirname, outstem) + "-fragments" + outext outseqs = [] ...
[ "Chops sequences of the passed files into fragments, returns filenames.\n\n - infiles - paths to each input sequence file\n - outdirname - path to output directory\n - fragsize - the size of sequence fragments\n\n Takes every sequence from every file in infiles, and splits them into\n consecutive fra...
Please provide a description of the function:def get_fraglength_dict(fastafiles): fraglength_dict = {} for filename in fastafiles: qname = os.path.split(filename)[-1].split("-fragments")[0] fraglength_dict[qname] = get_fragment_lengths(filename) return fraglength_dict
[ "Returns dictionary of sequence fragment lengths, keyed by query name.\n\n - fastafiles - list of FASTA input whole sequence files\n\n Loops over input files and, for each, produces a dictionary with fragment\n lengths, keyed by sequence ID. These are returned as a dictionary with\n the keys being query...
Please provide a description of the function:def get_fragment_lengths(fastafile): fraglengths = {} for seq in SeqIO.parse(fastafile, "fasta"): fraglengths[seq.id] = len(seq) return fraglengths
[ "Returns dictionary of sequence fragment lengths, keyed by fragment ID.\n\n Biopython's SeqIO module is used to parse all sequences in the FASTA\n file.\n\n NOTE: ambiguity symbols are not discounted.\n " ]
Please provide a description of the function:def build_db_jobs(infiles, blastcmds): dbjobdict = {} # Dict of database construction jobs, keyed by filename # Create dictionary of database building jobs, keyed by db name # defining jobnum for later use as last job index used for idx, fname in enumer...
[ "Returns dictionary of db-building commands, keyed by dbname." ]
Please provide a description of the function:def make_blastcmd_builder( mode, outdir, format_exe=None, blast_exe=None, prefix="ANIBLAST" ): if mode == "ANIb": # BLAST/formatting executable depends on mode blastcmds = BLASTcmds( BLASTfunctions(construct_makeblastdb_cmd, construct_blastn...
[ "Returns BLASTcmds object for construction of BLAST commands." ]
Please provide a description of the function:def make_job_graph(infiles, fragfiles, blastcmds): joblist = [] # Holds list of job dependency graphs # Get dictionary of database-building jobs dbjobdict = build_db_jobs(infiles, blastcmds) # Create list of BLAST executable jobs, with dependencies ...
[ "Return a job dependency graph, based on the passed input sequence files.\n\n - infiles - a list of paths to input FASTA files\n - fragfiles - a list of paths to fragmented input FASTA files\n\n By default, will run ANIb - it *is* possible to make a mess of passing the\n wrong executable for the mode yo...
Please provide a description of the function:def generate_blastdb_commands(filenames, outdir, blastdb_exe=None, mode="ANIb"): if mode == "ANIb": construct_db_cmdline = construct_makeblastdb_cmd else: construct_db_cmdline = construct_formatdb_cmd if blastdb_exe is None: cmdlines ...
[ "Return a list of makeblastdb command-lines for ANIb/ANIblastall\n\n - filenames - a list of paths to input FASTA files\n - outdir - path to output directory\n - blastdb_exe - path to the makeblastdb executable\n " ]
Please provide a description of the function:def construct_makeblastdb_cmd( filename, outdir, blastdb_exe=pyani_config.MAKEBLASTDB_DEFAULT ): title = os.path.splitext(os.path.split(filename)[-1])[0] outfilename = os.path.join(outdir, os.path.split(filename)[-1]) return ( "{0} -dbtype nucl -...
[ "Returns a single makeblastdb command.\n\n - filename - input filename\n - blastdb_exe - path to the makeblastdb executable\n " ]
Please provide a description of the function:def construct_formatdb_cmd(filename, outdir, blastdb_exe=pyani_config.FORMATDB_DEFAULT): title = os.path.splitext(os.path.split(filename)[-1])[0] newfilename = os.path.join(outdir, os.path.split(filename)[-1]) shutil.copy(filename, newfilename) return ( ...
[ "Returns a single formatdb command.\n\n - filename - input filename\n - blastdb_exe - path to the formatdb executable\n " ]
Please provide a description of the function:def generate_blastn_commands(filenames, outdir, blast_exe=None, mode="ANIb"): if mode == "ANIb": construct_blast_cmdline = construct_blastn_cmdline else: construct_blast_cmdline = construct_blastall_cmdline cmdlines = [] for idx, fname1 i...
[ "Return a list of blastn command-lines for ANIm\n\n - filenames - a list of paths to fragmented input FASTA files\n - outdir - path to output directory\n - blastn_exe - path to BLASTN executable\n\n Assumes that the fragment sequence input filenames have the form\n ACCESSION-fragments.ext, where the ...
Please provide a description of the function:def construct_blastn_cmdline( fname1, fname2, outdir, blastn_exe=pyani_config.BLASTN_DEFAULT ): fstem1 = os.path.splitext(os.path.split(fname1)[-1])[0] fstem2 = os.path.splitext(os.path.split(fname2)[-1])[0] fstem1 = fstem1.replace("-fragments", "") ...
[ "Returns a single blastn command.\n\n - filename - input filename\n - blastn_exe - path to BLASTN executable\n " ]
Please provide a description of the function:def construct_blastall_cmdline( fname1, fname2, outdir, blastall_exe=pyani_config.BLASTALL_DEFAULT ): fstem1 = os.path.splitext(os.path.split(fname1)[-1])[0] fstem2 = os.path.splitext(os.path.split(fname2)[-1])[0] fstem1 = fstem1.replace("-fragments", ""...
[ "Returns a single blastall command.\n\n - blastall_exe - path to BLASTALL executable\n " ]
Please provide a description of the function:def process_blast( blast_dir, org_lengths, fraglengths=None, mode="ANIb", identity=0.3, coverage=0.7, logger=None, ): # Process directory to identify input files blastfiles = pyani_files.get_input_files(blast_dir, ".blast_tab") # ...
[ "Returns a tuple of ANIb results for .blast_tab files in the output dir.\n\n - blast_dir - path to the directory containing .blast_tab files\n - org_lengths - the base count for each input sequence\n - fraglengths - dictionary of query sequence fragment lengths, only\n needed for BLASTALL output\n - ...
Please provide a description of the function:def parse_blast_tab(filename, fraglengths, identity, coverage, mode="ANIb"): # Assuming that the filename format holds org1_vs_org2.blast_tab: qname = os.path.splitext(os.path.split(filename)[-1])[0].split("_vs_")[0] # Load output as dataframe if mode ==...
[ "Returns (alignment length, similarity errors, mean_pid) tuple\n from .blast_tab\n\n - filename - path to .blast_tab file\n\n Calculate the alignment length and total number of similarity errors (as\n we would with ANIm), as well as the Goris et al.-defined mean identity\n of all valid BLAST matches ...
Please provide a description of the function:def split_seq(iterable, size): elm = iter(iterable) item = list(itertools.islice(elm, size)) while item: yield item item = list(itertools.islice(elm, size))
[ "Splits a passed iterable into chunks of a given size." ]
Please provide a description of the function:def build_joblist(jobgraph): jobset = set() for job in jobgraph: jobset = populate_jobset(job, jobset, depth=1) return list(jobset)
[ "Returns a list of jobs, from a passed jobgraph." ]
Please provide a description of the function:def compile_jobgroups_from_joblist(joblist, jgprefix, sgegroupsize): jobcmds = defaultdict(list) for job in joblist: jobcmds[job.command.split(' ', 1)[0]].append(job.command) jobgroups = [] for cmds in list(jobcmds.items()): # Break argli...
[ "Return list of jobgroups, rather than list of jobs." ]
Please provide a description of the function:def run_dependency_graph(jobgraph, logger=None, jgprefix="ANIm_SGE_JG", sgegroupsize=10000, sgeargs=None): joblist = build_joblist(jobgraph) # Try to be informative by telling the user what jobs will run dep_count = 0 # how many de...
[ "Creates and runs GridEngine scripts for jobs based on the passed\n jobgraph.\n\n - jobgraph - list of jobs, which may have dependencies.\n - verbose - flag for multiprocessing verbosity\n - logger - a logger module logger (optional)\n - jgprefix - a prefix for the submitted jobs, in the scheduler\n ...
Please provide a description of the function:def populate_jobset(job, jobset, depth): jobset.add(job) if len(job.dependencies) == 0: return jobset for j in job.dependencies: jobset = populate_jobset(j, jobset, depth+1) return jobset
[ " Creates a set of jobs, containing jobs at difference depths of the\n dependency tree, retaining dependencies as strings, not Jobs.\n " ]
Please provide a description of the function:def build_directories(root_dir): # If the root directory doesn't exist, create it if not os.path.exists(root_dir): os.mkdir(root_dir) # Create subdirectories directories = [os.path.join(root_dir, subdir) for subdir in ("output...
[ "Constructs the subdirectories output, stderr, stdout, and jobs in the\n passed root directory. These subdirectories have the following roles:\n\n jobs Stores the scripts for each job\n stderr Stores the stderr output from SGE\n stdout Stores the stdout output...
Please provide a description of the function:def build_job_scripts(root_dir, jobs): # Loop over the job list, creating each job script in turn, and then adding # scriptPath to the Job object for job in jobs: scriptpath = os.path.join(root_dir, "jobs", job.name) with open(scriptpath, "w"...
[ "Constructs the script for each passed Job in the jobs iterable\n\n - root_dir Path to output directory\n " ]
Please provide a description of the function:def submit_safe_jobs(root_dir, jobs, sgeargs=None): # Loop over each job, constructing SGE command-line based on job settings for job in jobs: job.out = os.path.join(root_dir, "stdout") job.err = os.path.join(root_dir, "stderr") # Add th...
[ "Submit the passed list of jobs to the Grid Engine server, using the\n passed directory as the root for scheduler output.\n\n - root_dir Path to output directory\n - jobs Iterable of Job objects\n " ]
Please provide a description of the function:def submit_jobs(root_dir, jobs, sgeargs=None): waiting = list(jobs) # List of jobs still to be done # Loop over the list of pending jobs, while there still are any while len(waiting) > 0: # extract submittable jobs submittable...
[ " Submit each of the passed jobs to the SGE server, using the passed\n directory as root for SGE output.\n\n - root_dir Path to output directory\n - jobs List of Job objects\n " ]