code
stringlengths
1
18.2k
= flat_trace.reshape((-1, k)) if weights is not None: weights = weights[burn:] weights = weights.ravel() if cutoff_weight is not None and weights is not None: mask = weights >= cutoff_weight * weights.max() flat_trace = flat_trace[mask, :] weights = weights[mask] else: raise ValueError("Unknown sampler class: %s" % (ty...
nbins is None: lq, uq = scipy.stats.scoreatpercentile(u, [25, 75], axis=1) h = 2.0 * (uq - lq) / u.shape[0]**(1.0 / 3.0) n = scipy.asarray(scipy.ceil(1.0 / h), dtype=int) else: try: iter(nbins) n = nbins except TypeError: n = nbins * scipy.ones(u.shape[0]) hist = [scipy.stats.histogram(uv, numbins=nv, defaultlimits=[0,...
h in hist]) f = plt.figure(figsize=figsize) a = f.add_subplot(1, 1, 1) for i, (h, pn) in enumerate(zip(hist, labels)): a.imshow( scipy.atleast_2d(scipy.asarray(h.count[::-1], dtype=float)).T, cmap='gray_r', interpolation='nearest', vmin=min_ct, vmax=max_ct, extent=(i, i + 1, 0, 1), aspect='auto' ) if plot_samples: for ...
for p in points] if point_color is None: c_cycle = itertools.cycle(['b', 'g', 'r', 'c', 'm', 'y', 'k']) else: c_cycle = itertools.cycle(scipy.atleast_1d(point_color)) for p in u_points: c = c_cycle.next() for i, uv in enumerate(p): a.plot([i, i + 1], [uv, uv], color=c, lw=point_lw) a.set_xlim(0, len(hist)) a.set_ylim(0...
def plot_sampler_cov( sampler, method='corr', weights=None, cutoff_weight=None, labels=None, burn=0, chain_mask=None, temp_idx=0, cbar_label=None, title='', rot_x_labels=False, figsize=None, xlabel_on_top=True ): """Make a plot of the sampler's correlation or covariance matrix. Returns the figure and axis created. Para...
which matches the shape of the `chain` attribute that would be present in a :py:class:`emcee.Sampler` instance. method : {'corr', 'cov'} Whether to plot the correlation matrix ('corr') or the covariance matrix ('cov'). The covariance matrix is often not useful because different parameters have wildly different scales. ...
hyperparameter. Default is to use empty strings. burn : int, optional The number of samples to burn before making the marginal histograms. Default is zero (use all samples). chain_mask : (index) array, optional Mask identifying the chains to keep before plotting, in case there are bad chains. Default is to use all chai...
plotting a :py:class:`emcee.PTSampler`. Default is 0 (samples from the posterior). cbar_label : str, optional The label to use for the colorbar. The default is chosen based on the value of the `method` keyword. title : str, optional Title to use for the plot. rot_x_labels : bool, optional If True, the labels for the x-...
labels). figsize : 2-tuple, optional The figure size to use. Default is to use the matplotlib default. xlabel_on_top : bool, optional If True, the x-axis labels are put on top (the way mathematicians present matrices). Default is True. """ try: k = sampler.flatchain.shape[-1] except AttributeError: # Assumes array inpu...
samples: if isinstance(sampler, emcee.EnsembleSampler): if chain_mask is None: chain_mask = scipy.ones(sampler.chain.shape[0], dtype=bool) flat_trace = sampler.chain[chain_mask, burn:, :] flat_trace = flat_trace.reshape((-1, k)) elif isinstance(sampler, emcee.PTSampler): if chain_mask is None: chain_mask = scipy.ones(s...
= flat_trace.reshape((-1, k)) if weights is not None: weights = weights[temp_idx, chain_mask, burn:] weights = weights.ravel() elif sampler.ndim == 3: if chain_mask is None: chain_mask = scipy.ones(sampler.shape[0], dtype=bool) flat_trace = sampler[chain_mask, burn:, :] flat_trace = flat_trace.reshape((-1, k)) if weigh...
not None: weights = weights[burn:] weights = weights.ravel() if cutoff_weight is not None and weights is not None: mask = weights >= cutoff_weight * weights.max() flat_trace = flat_trace[mask, :] weights = weights[mask] else: raise ValueError("Unknown sampler class: %s" % (type(sampler),)) if labels is None: labels = [...
if weights is None: if method == 'corr': cov = scipy.corrcoef(flat_trace, rowvar=0, ddof=1) else: cov = scipy.cov(flat_trace, rowvar=0, ddof=1) else: cov = scipy.cov(flat_trace, rowvar=0, aweights=weights) if method == 'corr': stds = scipy.sqrt(scipy.diag(cov)) STD_1, STD_2 = scipy.meshgrid(stds, stds) cov = cov / (STD...
cax = a_cov.pcolor(cov, cmap='seismic', vmin=-1 * vmax, vmax=vmax) divider = make_axes_locatable(a_cov) a_cb = divider.append_axes("right", size="10%", pad=0.05) cbar = f_cov.colorbar(cax, cax=a_cb, label=cbar_label) a_cov.set_xlabel('parameter') a_cov.set_ylabel('parameter') a_cov.axis('square') a_cov.invert_yaxis() i...
def sample_u(self, q): r"""Extract a sample from random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the inverse CDF. To facilitate efficient sampling, this function returns a *vector* of PPF values, one value for each variable. Basically, the idea is that, given a vector...
will return corresponding samples for each variable. Parameters ---------- q : array-like, (`num_params`,) Values between 0 and 1 to evaluate inverse CDF at. """ p1_num_params = len(self.p1.bounds) return scipy.concatenate( ( self.p1.sample_u(q[:p1_num_params]), self.p2.sample_u(q[p1_num_params:]) ) )
def elementwise_cdf(self, p): r"""Convert a sample to random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the CDF. To facilitate efficient sampling, this function returns a *vector* of CDF values, one value for each variable. Basically, the idea is that, given a vector :m...
return variables uniform on :math:`[0, 1]` corresponding to each variable. This is the inverse operation to :py:meth:`sample_u`. Parameters ---------- p : array-like, (`num_params`,) Values to evaluate CDF at. """ p1_num_params = len(self.p1.bounds) return scipy.concatenate( ( self.p1.elementwise_cdf(p[:p1_num_params])...
def random_draw(self, size=None): """Draw random samples of the hyperparameters. The outputs of the two priors are stacked vertically. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is None. """ draw_1 = self.p1.random_dr...
def sample_u(self, q): r"""Extract a sample from random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the inverse CDF. To facilitate efficient sampling, this function returns a *vector* of PPF values, one value for each variable. Basically, the idea is that, given a vector...
will return corresponding samples for each variable. Parameters ---------- q : array of float Values between 0 and 1 to evaluate inverse CDF at. """ q = scipy.atleast_1d(q) if len(q) != len(self.bounds): raise ValueError("length of q must equal the number of parameters!") if q.ndim != 1: raise ValueError("q must be one...
[0, 1]!") return scipy.asarray([(b[1] - b[0]) * v + b[0] for v, b in zip(q, self.bounds)])
def elementwise_cdf(self, p): r"""Convert a sample to random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the CDF. To facilitate efficient sampling, this function returns a *vector* of CDF values, one value for each variable. Basically, the idea is that, given a vector :m...
return variables uniform on :math:`[0, 1]` corresponding to each variable. This is the inverse operation to :py:meth:`sample_u`. Parameters ---------- p : array-like, (`num_params`,) Values to evaluate CDF at. """ p = scipy.atleast_1d(p) if len(p) != len(self.bounds): raise ValueError("length of p must equal the number...
p[k] <= self.bounds[k][0]: c[k] = 0.0 elif p[k] >= self.bounds[k][1]: c[k] = 1.0 else: c[k] = (p[k] - self.bounds[k][0]) / (self.bounds[k][1] - self.bounds[k][0]) return c
def random_draw(self, size=None): """Draw random samples of the hyperparameters. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is None. """ return scipy.asarray([numpy.random.uniform(low=b[0], high=b[1], size=size) for b...
def random_draw(self, size=None): """Draw random samples of the hyperparameters. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is None. """ if size is None: size = 1 single_val = True else: single_val = False out_shape =...
len(self.bounds)): if j != 2: out[j, :] = numpy.random.uniform(low=self.bounds[j][0], high=self.bounds[j][1], size=size) else: out[j, :] = numpy.random.uniform(low=self.bounds[j][0], high=out[j - 1, :], size=size) if not single_val: return out else: return out.ravel()
def sample_u(self, q): r"""Extract a sample from random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the inverse CDF. To facilitate efficient sampling, this function returns a *vector* of PPF values, one value for each variable. Basically, the idea is that, given a vector...
will return corresponding samples for each variable. Parameters ---------- q : array of float Values between 0 and 1 to evaluate inverse CDF at. """ q = scipy.atleast_1d(q) if len(q) != len(self.univariate_priors): raise ValueError("length of q must equal the number of parameters!") if q.ndim != 1: raise ValueError("q ...
[0, 1]!") return scipy.asarray([p.ppf(v) for v, p in zip(q, self.univariate_priors)])
def elementwise_cdf(self, p): r"""Convert a sample to random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the CDF. To facilitate efficient sampling, this function returns a *vector* of CDF values, one value for each variable. Basically, the idea is that, given a vector :m...
return variables uniform on :math:`[0, 1]` corresponding to each variable. This is the inverse operation to :py:meth:`sample_u`. Parameters ---------- p : array-like, (`num_params`,) Values to evaluate CDF at. """ p = scipy.atleast_1d(p) if len(p) != len(self.univariate_priors): raise ValueError("length of p must equal...
def random_draw(self, size=None): """Draw random samples of the hyperparameters. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is None. """ return scipy.asarray([p.rvs(size=size) for p in self.univariate_priors])
def bounds(self): """The bounds of the random variable. Set `self.i=0.95` to return the 95% interval if this is used for setting bounds on optimizers/etc. where infinite bounds may not be useful. """ return [scipy.stats.norm.interval(self.i, loc=m, scale=s) for s, m in zip(self.sigma, self.mu)]
def sample_u(self, q): r"""Extract a sample from random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the inverse CDF. To facilitate efficient sampling, this function returns a *vector* of PPF values, one value for each variable. Basically, the idea is that, given a vector...
will return corresponding samples for each variable. Parameters ---------- q : array of float Values between 0 and 1 to evaluate inverse CDF at. """ q = scipy.atleast_1d(q) if len(q) != len(self.sigma): raise ValueError("length of q must equal the number of parameters!") if q.ndim != 1: raise ValueError("q must be one-...
[0, 1]!") return scipy.asarray([scipy.stats.norm.ppf(v, loc=m, scale=s) for v, s, m in zip(q, self.sigma, self.mu)])
def elementwise_cdf(self, p): r"""Convert a sample to random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the CDF. To facilitate efficient sampling, this function returns a *vector* of CDF values, one value for each variable. Basically, the idea is that, given a vector :m...
return variables uniform on :math:`[0, 1]` corresponding to each variable. This is the inverse operation to :py:meth:`sample_u`. Parameters ---------- p : array-like, (`num_params`,) Values to evaluate CDF at. """ p = scipy.atleast_1d(p) if len(p) != len(self.sigma): raise ValueError("length of p must equal the number ...
zip(p, self.sigma, self.mu)])
def random_draw(self, size=None): """Draw random samples of the hyperparameters. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is None. """ return scipy.asarray([scipy.stats.norm.rvs(loc=m, scale=s, size=size) for s, m i...
def bounds(self): """The bounds of the random variable. Set `self.i=0.95` to return the 95% interval if this is used for setting bounds on optimizers/etc. where infinite bounds may not be useful. """ return [scipy.stats.lognorm.interval(self.i, s, loc=0, scale=em) for s, em in zip(self.sigma, self.emu)]
def sample_u(self, q): r"""Extract a sample from random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the inverse CDF. To facilitate efficient sampling, this function returns a *vector* of PPF values, one value for each variable. Basically, the idea is that, given a vector...
will return corresponding samples for each variable. Parameters ---------- q : array of float Values between 0 and 1 to evaluate inverse CDF at. """ q = scipy.atleast_1d(q) if len(q) != len(self.sigma): raise ValueError("length of q must equal the number of parameters!") if q.ndim != 1: raise ValueError("q must be one-...
[0, 1]!") return scipy.asarray([scipy.stats.lognorm.ppf(v, s, loc=0, scale=em) for v, s, em in zip(q, self.sigma, self.emu)])
def elementwise_cdf(self, p): r"""Convert a sample to random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the CDF. To facilitate efficient sampling, this function returns a *vector* of CDF values, one value for each variable. Basically, the idea is that, given a vector :m...
return variables uniform on :math:`[0, 1]` corresponding to each variable. This is the inverse operation to :py:meth:`sample_u`. Parameters ---------- p : array-like, (`num_params`,) Values to evaluate CDF at. """ p = scipy.atleast_1d(p) if len(p) != len(self.sigma): raise ValueError("length of p must equal the number ...
in zip(p, self.sigma, self.emu)])
def random_draw(self, size=None): """Draw random samples of the hyperparameters. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is None. """ return scipy.asarray([scipy.stats.lognorm.rvs(s, loc=0, scale=em, size=size) for...
def bounds(self): """The bounds of the random variable. Set `self.i=0.95` to return the 95% interval if this is used for setting bounds on optimizers/etc. where infinite bounds may not be useful. """ return [scipy.stats.gamma.interval(self.i, a, loc=0, scale=1.0 / b) for a, b in zip(self.a, self.b)]
def sample_u(self, q): r"""Extract a sample from random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the inverse CDF. To facilitate efficient sampling, this function returns a *vector* of PPF values, one value for each variable. Basically, the idea is that, given a vector...
will return corresponding samples for each variable. Parameters ---------- q : array of float Values between 0 and 1 to evaluate inverse CDF at. """ q = scipy.atleast_1d(q) if len(q) != len(self.a): raise ValueError("length of q must equal the number of parameters!") if q.ndim != 1: raise ValueError("q must be one-dime...
[0, 1]!") return scipy.asarray([scipy.stats.gamma.ppf(v, a, loc=0, scale=1.0 / b) for v, a, b in zip(q, self.a, self.b)])
def elementwise_cdf(self, p): r"""Convert a sample to random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the CDF. To facilitate efficient sampling, this function returns a *vector* of CDF values, one value for each variable. Basically, the idea is that, given a vector :m...
return variables uniform on :math:`[0, 1]` corresponding to each variable. This is the inverse operation to :py:meth:`sample_u`. Parameters ---------- p : array-like, (`num_params`,) Values to evaluate CDF at. """ p = scipy.atleast_1d(p) if len(p) != len(self.a): raise ValueError("length of p must equal the number of p...
a, b in zip(p, self.a, self.b)])
def random_draw(self, size=None): """Draw random samples of the hyperparameters. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is None. """ return scipy.asarray([scipy.stats.gamma.rvs(a, loc=0, scale=1.0 / b, size=size) ...
def sample_u(self, q): r"""Extract a sample from random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the inverse CDF. To facilitate efficient sampling, this function returns a *vector* of PPF values, one value for each variable. Basically, the idea is that, given a vector...
will return corresponding samples for each variable. Parameters ---------- q : array of float Values between 0 and 1 to evaluate inverse CDF at. """ q = scipy.atleast_1d(q) if len(q) != self.num_var: raise ValueError("length of q must equal the number of parameters!") if q.ndim != 1: raise ValueError("q must be one-dim...
[0, 1]!") # Old way, not quite correct: # q = scipy.sort(q) # return scipy.asarray([(self.ub - self.lb) * v + self.lb for v in q]) # New way, based on conditional marginals: out = scipy.zeros_like(q, dtype=float) out[0] = self.lb for d in xrange(0, len(out)): out[d] = ( (1.0 - (1.0 - q[d])**(1.0 / (self.num_var - d))) ...
out[max(d - 1, 0)] ) return out
def elementwise_cdf(self, p): r"""Convert a sample to random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the CDF. To facilitate efficient sampling, this function returns a *vector* of CDF values, one value for each variable. Basically, the idea is that, given a vector :m...
return variables uniform on :math:`[0, 1]` corresponding to each variable. This is the inverse operation to :py:meth:`sample_u`. Parameters ---------- p : array-like, (`num_params`,) Values to evaluate CDF at. """ p = scipy.atleast_1d(p) if len(p) != len(self.bounds): raise ValueError("length of p must equal the number...
uniform variables: # for k in xrange(0, len(self.bounds)): # if p[k] <= self.bounds[k][0]: # c[k] = 0.0 # elif p[k] >= self.bounds[k][1]: # c[k] = 1.0 # else: # c[k] = (p[k] - self.bounds[k][0]) / (self.bounds[k][1] - self.bounds[k][0]) # New way, based on conditional marginals: for d in xrange(0, len(c)): pdm1 = p[d -...
pdm1: c[d] = 0.0 elif p[d] >= self.ub: c[d] = 1.0 else: c[d] = 1.0 - (1.0 - (p[d] - pdm1) / (self.ub - pdm1))**(self.num_var - d) return c
def random_draw(self, size=None): """Draw random samples of the hyperparameters. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is None. """ if size is None: size = 1 single_val = True else: single_val = False out_shape =...
), axis=0 ) if not single_val: return out else: return out.ravel()
def zapier_cancel_hook(request): ''' Zapier can post something like this when tickets are cancelled { "ticket_type": "Individual (Regular)", "barcode": "12345678", "email": "demo@example.com" } ''' if request.META.get('HTTP_X_ZAPIER_SECRET', None) != settings.WAFER_TICKETS_SECRET: raise PermissionDenied('Incorrect secr...
def zapier_guest_hook(request): ''' Zapier can POST something like this when tickets are bought: { "ticket_type": "Individual (Regular)", "barcode": "12345678", "email": "demo@example.com" } ''' if request.META.get('HTTP_X_ZAPIER_SECRET', None) != settings.WAFER_TICKETS_SECRET: raise PermissionDenied('Incorrect secret'...
def fetch_token(self): """Gains token from secure backend service. :return: Token formatted for Cocaine protocol header. """ grant_type = 'client_credentials' channel = yield self._tvm.ticket_full( self._client_id, self._client_secret, grant_type, {}) ticket = yield channel.rx.get() raise gen.Return(self._make_token(ti...
def make_secure_adaptor(service, mod, client_id, client_secret, tok_update_sec=None): """ :param service: Service to wrap in. :param mod: Name (type) of token refresh backend. :param client_id: Client identifier. :param client_secret: Client secret. :param tok_update_sec: Token update interval in seconds. """ if mod ==...
def process_summary(summaryfile, **kwargs): """Extracting information from an albacore summary file. Only reads which have a >0 length are returned. The fields below may or may not exist, depending on the type of sequencing performed. Fields 1-14 are for 1D sequencing. Fields 1-23 for 2D sequencing. Fields 24-27, 2-5, ...
4 channel 5 start_time 6 duration 7 num_events 8 template_start 9 num_events_template 10 template_duration 11 num_called_template 12 sequence_length_template 13 mean_qscore_template 14 strand_score_template 15 complement_start 16 num_events_complement 17 complement_duration 18 num_called_complement 19 sequence_length_c...
36 rear_foundseq_length 37 kit 38 variant """ logging.info("Nanoget: Collecting metrics from summary file {} for {} sequencing".format( summaryfile, kwargs["readtype"])) ut.check_existance(summaryfile) if kwargs["readtype"] == "1D": cols = ["read_id", "run_id", "channel", "start_time", "duration", "sequence_length_temp...
ValueError: logging.error("Nanoget: did not find expected columns in summary file {}:\n {}".format( summaryfile, ', '.join(cols))) sys.exit("ERROR: expected columns in summary file {} not found:\n {}".format( summaryfile, ', '.join(cols))) if kwargs["barcoded"]: datadf.columns = ["readIDs", "runIDs", "channelIDs", "tim...
def check_bam(bam, samtype="bam"): """Check if bam file is valid. Bam file should: - exists - has an index (create if necessary) - is sorted by coordinate - has at least one mapped read """ ut.check_existance(bam) samfile = pysam.AlignmentFile(bam, "rb") if not samfile.has_index(): pysam.index(bam) samfile = pysam.Alig...
found, created index.") if not samfile.header['HD']['SO'] == 'coordinate': logging.error("Nanoget: Bam file {} not sorted by coordinate!.".format(bam)) sys.exit("Please use a bam file sorted by coordinate.") if samtype == "bam": logging.info("Nanoget: Bam file {} contains {} mapped and {} unmapped reads.".format( bam, ...
file {}".format(bam)) return samfile
def process_ubam(bam, **kwargs): """Extracting metrics from unaligned bam format Extracting lengths """ logging.info("Nanoget: Starting to collect statistics from ubam file {}.".format(bam)) samfile = pysam.AlignmentFile(bam, "rb", check_sq=False) if not samfile.has_index(): pysam.index(bam) # Need to reload the samfil...
columns=["readIDs", "quals", "lengths"]) \ .dropna(axis='columns', how='all') \ .dropna(axis='index', how='any') logging.info("Nanoget: ubam {} contains {} reads.".format( bam, datadf["lengths"].size)) return ut.reduce_memory_usage(datadf)
def process_bam(bam, **kwargs): """Combines metrics from bam after extraction. Processing function: calls pool of worker functions to extract from a bam file the following metrics: -lengths -aligned lengths -qualities -aligned qualities -mapping qualities -edit distances to the reference genome scaled by read length Re...
params = zip([bam] * len(chromosomes), chromosomes) with cfutures.ProcessPoolExecutor() as executor: datadf = pd.DataFrame( data=[res for sublist in executor.map(extract_from_bam, params) for res in sublist], columns=["readIDs", "quals", "aligned_quals", "lengths", "aligned_lengths", "mapQ", "percentIdentity"]) \ .drop...
def extract_from_bam(params): """Extracts metrics from bam. Worker function per chromosome loop over a bam file and create list with tuples containing metrics: -qualities -aligned qualities -lengths -aligned lengths -mapping qualities -edit distances to the reference genome scaled by read length """ bam, chromosome = p...
not read.is_secondary]
def get_pID(read): """Return the percent identity of a read. based on the NM tag if present, if not calculate from MD tag and CIGAR string read.query_alignment_length can be zero in the case of ultra long reads aligned with minimap2 -L """ try: return 100 * (1 - read.get_tag("NM") / read.query_alignment_length) except ...
KeyError: return None except ZeroDivisionError: return None
def handle_compressed_input(inputfq, file_type="fastq"): """Return handles from compressed files according to extension. Check for which fastq input is presented and open a handle accordingly Can read from compressed files (gz, bz2, bgz) or uncompressed Relies on file extensions to recognize compression """ ut.check_ex...
{} {}".format(file_type, inputfq)) return bz2.open(inputfq, 'rt') elif inputfq.endswith(('.fastq', '.fq', 'fasta', '.fa', '.fas')): return open(inputfq, 'r') else: logging.error("INPUT ERROR: Unrecognized file extension {}".format(inputfq)) sys.exit('INPUT ERROR:\nUnrecognized file extension in {}\n' 'Supported are gz,...
def process_fasta(fasta, **kwargs): """Combine metrics extracted from a fasta file.""" logging.info("Nanoget: Starting to collect statistics from a fasta file.") inputfasta = handle_compressed_input(fasta, file_type="fasta") return ut.reduce_memory_usage(pd.DataFrame( data=[len(rec) for rec in SeqIO.parse(inputfasta, "...
def process_fastq_plain(fastq, **kwargs): """Combine metrics extracted from a fastq file.""" logging.info("Nanoget: Starting to collect statistics from plain fastq file.") inputfastq = handle_compressed_input(fastq) return ut.reduce_memory_usage(pd.DataFrame( data=[res for res in extract_from_fastq(inputfastq) if res],...
def extract_from_fastq(fq): """Extract metrics from a fastq file. Return average quality and read length """ for rec in SeqIO.parse(fq, "fastq"): yield nanomath.ave_qual(rec.letter_annotations["phred_quality"]), len(rec)
def stream_fastq_full(fastq, threads): """Generator for returning metrics extracted from fastq. Extract from a fastq file: -readname -average and median quality -read_lenght """ logging.info("Nanoget: Starting to collect full metrics from plain fastq file.") inputfastq = handle_compressed_input(fastq) with cfutures.Pro...
def extract_all_from_fastq(rec): """Extract metrics from a fastq file. Return identifier, read length, average quality and median quality """ return (rec.id, len(rec), nanomath.ave_qual(rec.letter_annotations["phred_quality"]), nanomath.median_qual(rec.letter_annotations["phred_quality"]))
def process_fastq_rich(fastq, **kwargs): """Extract metrics from a richer fastq file. Extract information from fastq files generated by albacore or MinKNOW, containing richer information in the header (key-value pairs) read=<int> [72] ch=<int> [159] start_time=<timestamp> [2016-07-15T14:23:22Z] # UTC ISO 8601 ISO 3339 ...
23, 22, tzinfo=tzutc()) """ logging.info("Nanoget: Starting to collect statistics from rich fastq file.") inputfastq = handle_compressed_input(fastq) res = [] for record in SeqIO.parse(inputfastq, "fastq"): try: read_info = info_to_dict(record.description) res.append( (nanomath.ave_qual(record.letter_annotations["phred...
"channelIDs", "timestamp", "runIDs"]).dropna() df["channelIDs"] = df["channelIDs"].astype("int64") return ut.reduce_memory_usage(df)
def readfq(fp): """Generator function adapted from https://github.com/lh3/readfq.""" last = None # this is a buffer keeping the last unprocessed line while True: # mimic closure; is it a bad idea? if not last: # the first record or a record following a fastq for l in fp: # search for the start of the next record if l[0...
last = l[:-1] # save this line break if not last: break name, seqs, last = last[1:].partition(" ")[0], [], None for l in fp: # read the sequence if l[0] in '@+>': last = l[:-1] break seqs.append(l[:-1]) if not last or last[0] != '+': # this is a fasta record yield name, ''.join(seqs), None # yield a fasta record if not...
# this is a fastq record seq, leng, seqs = ''.join(seqs), 0, [] for l in fp: # read the quality seqs.append(l[:-1]) leng += len(l) - 1 if leng >= len(seq): # have read enough quality last = None yield name, seq, ''.join(seqs) # yield a fastq record break if last: # reach EOF before reading enough quality yield name, se...