INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Automatically Adds a dependency of a process. | def _add_dependency(self, p, template, inlane, outlane, pid):
"""Automatically Adds a dependency of a process.
This method adds a template to the process list attribute as a
dependency. It will adapt the input lane, output lane and process
id of the process that depends on it.
... |
Searches the process tree backwards in search of a provided process | def _search_tree_backwards(self, template, parent_lanes):
"""Searches the process tree backwards in search of a provided process
The search takes into consideration the provided parent lanes and
searches only those
Parameters
----------
template : str
Name o... |
Adds the header template to the master template string | def _build_header(self):
"""Adds the header template to the master template string
"""
logger.debug("===============")
logger.debug("Building header")
logger.debug("===============")
self.template += hs.header |
Adds the footer template to the master template string | def _build_footer(self):
"""Adds the footer template to the master template string"""
logger.debug("===============")
logger.debug("Building header")
logger.debug("===============")
self.template += fs.footer |
Given a process this method updates the: attr: ~Process. main_raw_inputs attribute with the corresponding raw input channel of that process. The input channel and input type can be overridden if the input_channel and input_type arguments are provided. | def _update_raw_input(self, p, sink_channel=None, input_type=None):
"""Given a process, this method updates the
:attr:`~Process.main_raw_inputs` attribute with the corresponding
raw input channel of that process. The input channel and input type
can be overridden if the `input_channel` a... |
Given a process this method updates the: attr: ~Process. extra_inputs attribute with the corresponding extra inputs of that process | def _update_extra_inputs(self, p):
"""Given a process, this method updates the
:attr:`~Process.extra_inputs` attribute with the corresponding extra
inputs of that process
Parameters
----------
p : flowcraft.Process.Process
"""
if p.extra_input:
... |
Given a process this method updates the: attr: ~Process. secondary_channels attribute with the corresponding secondary inputs of that channel. | def _update_secondary_channels(self, p):
"""Given a process, this method updates the
:attr:`~Process.secondary_channels` attribute with the corresponding
secondary inputs of that channel.
The rationale of the secondary channels is the following:
- Start storing any secondar... |
Sets the main channels for the pipeline | def _set_channels(self):
"""Sets the main channels for the pipeline
This method will parse de the :attr:`~Process.processes` attribute
and perform the following tasks for each process:
- Sets the input/output channels and main input forks and adds
them to the process'... |
Sets the main raw inputs and secondary inputs on the init process | def _set_init_process(self):
"""Sets the main raw inputs and secondary inputs on the init process
This method will fetch the :class:`flowcraft.process.Init` process
instance and sets the raw input (
:func:`flowcraft.process.Init.set_raw_inputs`) for
that process. This will handl... |
Sets the secondary channels for the pipeline | def _set_secondary_channels(self):
"""Sets the secondary channels for the pipeline
This will iterate over the
:py:attr:`NextflowGenerator.secondary_channels` dictionary that is
populated when executing
:func:`~NextflowGenerator._update_secondary_channels` method.
"""
... |
Adds compiler channels to the: attr: processes attribute. | def _set_general_compilers(self):
"""Adds compiler channels to the :attr:`processes` attribute.
This method will iterate over the pipeline's processes and check
if any process is feeding channels to a compiler process. If so, that
compiler process is added to the pipeline and those chan... |
Compiles all status channels for the status compiler process | def _set_status_channels(self):
"""Compiles all status channels for the status compiler process
"""
status_inst = pc.StatusCompiler(template="status_compiler")
report_inst = pc.ReportCompiler(template="report_compiler")
# Compile status channels from pipeline process
st... |
Returns the nextflow resources string from a dictionary object | def _get_resources_string(res_dict, pid):
""" Returns the nextflow resources string from a dictionary object
If the dictionary has at least on of the resource directives, these
will be compiled for each process in the dictionary and returned
as a string read for injection in the nextflo... |
Returns the nextflow containers string from a dictionary object | def _get_container_string(cont_dict, pid):
""" Returns the nextflow containers string from a dictionary object
If the dictionary has at least on of the container directives, these
will be compiled for each process in the dictionary and returned
as a string read for injection in the next... |
Returns the nextflow params string from a dictionary object. | def _get_params_string(self):
"""Returns the nextflow params string from a dictionary object.
The params dict should be a set of key:value pairs with the
parameter name, and the default parameter value::
self.params = {
"genomeSize": 2.1,
"minCoverag... |
Returns the merged nextflow params string from a dictionary object. | def _get_merged_params_string(self):
"""Returns the merged nextflow params string from a dictionary object.
The params dict should be a set of key:value pairs with the
parameter name, and the default parameter value::
self.params = {
"genomeSize": 2.1,
... |
Returns the nextflow manifest config string to include in the config file from the information on the pipeline. | def _get_manifest_string(self):
"""Returns the nextflow manifest config string to include in the
config file from the information on the pipeline.
Returns
-------
str
Nextflow manifest configuration string
"""
config_str = ""
config_str += '... |
This method will iterate over all process in the pipeline and populate the nextflow configuration files with the directives of each process in the pipeline. | def _set_configurations(self):
"""This method will iterate over all process in the pipeline and
populate the nextflow configuration files with the directives
of each process in the pipeline.
"""
logger.debug("======================")
logger.debug("Setting configurations"... |
Writes dag to output file | def dag_to_file(self, dict_viz, output_file=".treeDag.json"):
"""Writes dag to output file
Parameters
----------
dict_viz: dict
Tree like dictionary that is used to export tree data of processes
to html file and here for the dotfile .treeDag.json
"""
... |
Write pipeline attributes to json | def render_pipeline(self):
"""Write pipeline attributes to json
This function writes the pipeline and their attributes to a json file,
that is intended to be read by resources/pipeline_graph.html to render
a graphical output showing the DAG.
"""
dict_viz = {
... |
Wrapper method that writes all configuration files to the pipeline directory | def write_configs(self, project_root):
"""Wrapper method that writes all configuration files to the pipeline
directory
"""
# Write resources config
with open(join(project_root, "resources.config"), "w") as fh:
fh.write(self.resources)
# Write containers conf... |
Export pipeline params as a JSON to stdout | def export_params(self):
"""Export pipeline params as a JSON to stdout
This run mode iterates over the pipeline processes and exports the
params dictionary of each component as a JSON to stdout.
"""
params_json = {}
# Skip first init process
for p in self.proce... |
Export pipeline directives as a JSON to stdout | def export_directives(self):
"""Export pipeline directives as a JSON to stdout
"""
directives_json = {}
# Skip first init process
for p in self.processes[1:]:
directives_json[p.template] = p.directives
# Flush params json to stdout
sys.stdout.write(... |
Export all dockerhub tags associated with each component given by the - t flag. | def fetch_docker_tags(self):
"""
Export all dockerhub tags associated with each component given by
the -t flag.
"""
# dict to store the already parsed components (useful when forks are
# given to the pipeline string via -t flag
dict_of_parsed = {}
# fetc... |
Main pipeline builder | def build(self):
"""Main pipeline builder
This method is responsible for building the
:py:attr:`NextflowGenerator.template` attribute that will contain
the nextflow code of the pipeline.
First it builds the header, then sets the main channels, the
secondary inputs, seco... |
Returns a kmer list based on the provided kmer option and max read len. | def set_kmers(kmer_opt, max_read_len):
"""Returns a kmer list based on the provided kmer option and max read len.
Parameters
----------
kmer_opt : str
The k-mer option. Can be either ``'auto'``, ``'default'`` or a
sequence of space separated integers, ``'23, 45, 67'``.
max_read_len ... |
Main executor of the spades template. | def main(sample_id, fastq_pair, max_len, kmer, clear):
"""Main executor of the spades template.
Parameters
----------
sample_id : str
Sample Identification string.
fastq_pair : list
Two element list containing the paired FastQ files.
max_len : int
Maximum read length. Th... |
Returns a hash of the reports JSON file | def _get_report_id(self):
"""Returns a hash of the reports JSON file
"""
if self.watch:
# Searches for the first occurence of the nextflow pipeline
# file name in the .nextflow.log file
pipeline_path = get_nextflow_filepath(self.log_file)
# Get ... |
Parses the. nextflow. log file for signatures of pipeline status and sets the: attr: status_info attribute. | def _update_pipeline_status(self):
"""
Parses the .nextflow.log file for signatures of pipeline status and sets
the :attr:`status_info` attribute.
"""
prev_status = self.status_info
with open(self.log_file) as fh:
for line in fh:
if "Sessio... |
Parses the nextflow trace file and retrieves the path of report JSON files that have not been sent to the service yet. | def update_trace_watch(self):
"""Parses the nextflow trace file and retrieves the path of report JSON
files that have not been sent to the service yet.
"""
# Check the size stamp of the tracefile. Only proceed with the parsing
# if it changed from the previous size.
size... |
Parses nextflow log file and updates the run status | def update_log_watch(self):
"""Parses nextflow log file and updates the run status
"""
# Check the size stamp of the tracefile. Only proceed with the parsing
# if it changed from the previous size.
size_stamp = os.path.getsize(self.log_file)
self.trace_retry = 0
... |
Sends a PUT request with the report JSON files currently in the report_queue attribute. | def _send_live_report(self, report_id):
"""Sends a PUT request with the report JSON files currently in the
report_queue attribute.
Parameters
----------
report_id : str
Hash of the report JSON as retrieved from :func:`~_get_report_hash`
"""
# Determi... |
Sends a POST request to initialize the live reports | def _init_live_reports(self, report_id):
"""Sends a POST request to initialize the live reports
Parameters
----------
report_id : str
Hash of the report JSON as retrieved from :func:`~_get_report_hash`
"""
logger.debug("Sending initial POST request to {} to ... |
Sends a delete request for the report JSON hash | def _close_connection(self, report_id):
"""Sends a delete request for the report JSON hash
Parameters
----------
report_id : str
Hash of the report JSON as retrieved from :func:`~_get_report_hash`
"""
logger.debug(
"Closing connection and sending... |
Generates an adapter file for FastQC from a fasta file. | def convert_adatpers(adapter_fasta):
"""Generates an adapter file for FastQC from a fasta file.
The provided adapters file is assumed to be a simple fasta file with the
adapter's name as header and the corresponding sequence::
>TruSeq_Universal_Adapter
AATGATACGGCGACCACCGAGATCTACACTCTTTCCC... |
Main executor of the fastq template. | def main(fastq_pair, adapter_file, cpus):
""" Main executor of the fastq template.
Parameters
----------
fastq_pair : list
Two element list containing the paired FastQ files.
adapter_file : str
Path to adapters file.
cpus : int or str
Number of cpu's that will be by Fast... |
Send dictionary to output json file This function sends master_dict dictionary to a json file if master_dict is populated with entries otherwise it won t create the file | def send_to_output(master_dict, mash_output, sample_id, assembly_file):
"""Send dictionary to output json file
This function sends master_dict dictionary to a json file if master_dict is
populated with entries, otherwise it won't create the file
Parameters
----------
master_dict: dict
d... |
Main function that allows to dump a mash dist txt file to a json file | def main(mash_output, hash_cutoff, sample_id, assembly_file):
"""
Main function that allows to dump a mash dist txt file to a json file
Parameters
----------
mash_output: str
A string with the input file.
hash_cutoff: str
the percentage cutoff for the percentage of shared hashes... |
Writes versions JSON for a template file | def build_versions(self):
"""Writes versions JSON for a template file
This method creates the JSON file ``.versions`` based on the metadata
and specific functions that are present in a given template script.
It starts by fetching the template metadata, which can be specified
vi... |
converts top results from mash screen txt output to json format | def main(mash_output, sample_id):
'''
converts top results from mash screen txt output to json format
Parameters
----------
mash_output: str
this is a string that stores the path to this file, i.e, the name of
the file
sample_id: str
sample name
'''
logger.info(... |
This function enables users to add a color to the print. It also enables to pass end_char to print allowing to print several strings in the same line in different prints. | def colored_print(msg, color_label="white_bold"):
"""
This function enables users to add a color to the print. It also enables
to pass end_char to print allowing to print several strings in the same line
in different prints.
Parameters
----------
color_string: str
The color code to ... |
This function handles the dictionary of attributes of each Process class to print to stdout lists of all the components or the components which the user specifies in the - t flag. | def procs_dict_parser(procs_dict):
"""
This function handles the dictionary of attributes of each Process class
to print to stdout lists of all the components or the components which the
user specifies in the -t flag.
Parameters
----------
procs_dict: dict
A dictionary with the clas... |
Function that collects all processes available and stores a dictionary of the required arguments of each process class to be passed to procs_dict_parser | def proc_collector(process_map, args, pipeline_string):
"""
Function that collects all processes available and stores a dictionary of
the required arguments of each process class to be passed to
procs_dict_parser
Parameters
----------
process_map: dict
The dictionary with the Proces... |
Guesses the compression of an input file. | def guess_file_compression(file_path, magic_dict=None):
"""Guesses the compression of an input file.
This function guesses the compression of a given file by checking for
a binary signature at the beginning of the file. These signatures are
stored in the :py:data:`MAGIC_DICT` dictionary. The supported ... |
Get range of the Unicode encode range for a given string of characters. | def get_qual_range(qual_str):
""" Get range of the Unicode encode range for a given string of characters.
The encoding is determined from the result of the :py:func:`ord` built-in.
Parameters
----------
qual_str : str
Arbitrary string.
Returns
-------
x : tuple
(Minimu... |
Returns the valid encodings for a given encoding range. | def get_encodings_in_range(rmin, rmax):
""" Returns the valid encodings for a given encoding range.
The encoding ranges are stored in the :py:data:`RANGES` dictionary, with
the encoding name as a string and a list as a value containing the
phred score and a tuple with the encoding range. For a given en... |
Main executor of the integrity_coverage template. | def main(sample_id, fastq_pair, gsize, minimum_coverage, opts):
""" Main executor of the integrity_coverage template.
Parameters
----------
sample_id : str
Sample Identification string.
fastq_pair : list
Two element list containing the paired FastQ files.
gsize : float or int
... |
Parses a file with coverage information into objects. | def parse_coverage_table(coverage_file):
"""Parses a file with coverage information into objects.
This function parses a TSV file containing coverage results for
all contigs in a given assembly and will build an ``OrderedDict``
with the information about their coverage and length. The length
infor... |
Generates a filtered assembly file. | def filter_assembly(assembly_file, minimum_coverage, coverage_info,
output_file):
"""Generates a filtered assembly file.
This function generates a filtered assembly file based on an original
assembly and a minimum coverage threshold.
Parameters
----------
assembly_file : st... |
Uses Samtools to filter a BAM file according to minimum coverage | def filter_bam(coverage_info, bam_file, min_coverage, output_bam):
"""Uses Samtools to filter a BAM file according to minimum coverage
Provided with a minimum coverage value, this function will use Samtools
to filter a BAM file. This is performed to apply the same filter to
the BAM file as the one appl... |
Checks whether a filtered assembly passes a size threshold | def check_filtered_assembly(coverage_info, coverage_bp, minimum_coverage,
genome_size, contig_size, max_contigs,
sample_id):
"""Checks whether a filtered assembly passes a size threshold
Given a minimum coverage threshold, this function evaluates whether ... |
Evaluates the minimum coverage threshold from the value provided in the coverage_opt. | def evaluate_min_coverage(coverage_opt, assembly_coverage, assembly_size):
""" Evaluates the minimum coverage threshold from the value provided in
the coverage_opt.
Parameters
----------
coverage_opt : str or int or float
If set to "auto" it will try to automatically determine the coverage
... |
Returns the number of nucleotides and the size per contig for the provided assembly file path | def get_assembly_size(assembly_file):
"""Returns the number of nucleotides and the size per contig for the
provided assembly file path
Parameters
----------
assembly_file : str
Path to assembly file.
Returns
-------
assembly_size : int
Size of the assembly in nucleotide... |
Main executor of the process_assembly_mapping template. | def main(sample_id, assembly_file, coverage_file, coverage_bp_file, bam_file,
opts, gsize):
"""Main executor of the process_assembly_mapping template.
Parameters
----------
sample_id : str
Sample Identification string.
assembly_file : str
Path to assembly file in Fasta form... |
Main executor of the process_spades template. | def main(sample_id, assembly_file, gsize, opts, assembler):
"""Main executor of the process_spades template.
Parameters
----------
sample_id : str
Sample Identification string.
assembly_file : str
Path to the assembly file generated by Spades.
gsize : int
Estimate of gen... |
Convers a CamelCase string into a snake_case one | def convert_camel_case(name):
"""Convers a CamelCase string into a snake_case one
Parameters
----------
name : str
An arbitrary string that may be CamelCase
Returns
-------
str
The input string converted into snake_case
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2',... |
Collects Process classes and return dict mapping templates to classes | def collect_process_map():
"""Collects Process classes and return dict mapping templates to classes
This function crawls through the components module and retrieves all
classes that inherit from the Process class. Then, it converts the name
of the classes (which should be CamelCase) to snake_case, whic... |
Main executor of the process_newick template. | def main(newick):
"""Main executor of the process_newick template.
Parameters
----------
newick : str
path to the newick file.
"""
logger.info("Starting newick file processing")
print(newick)
tree = dendropy.Tree.get(file=open(newick, 'r'), schema="newick")
tree.reroot_... |
Factorize s. t. CUR = data | def factorize(self):
""" Factorize s.t. CUR = data
Updated Values
--------------
.C : updated values for C.
.U : updated values for U.
.R : updated values for R.
"""
[prow, pcol] = self.sample_probability()
self._rid = self.s... |
Factorize s. t. CUR = data | def factorize(self):
""" Factorize s.t. CUR = data
Updated Values
--------------
.C : updated values for C.
.U : updated values for U.
.R : updated values for R.
"""
[prow, pcol] = self.sample_probability()
self._rid = self.sam... |
Find data points on the convex hull of a supplied data set | def quickhull(sample):
""" Find data points on the convex hull of a supplied data set
Args:
sample: data points as column vectors n x d
n - number samples
d - data dimension (should be two)
Returns:
a k x d matrix containint the convex hull data poin... |
Return data points that are most similar to basis vectors W | def _map_w_to_data(self):
""" Return data points that are most similar to basis vectors W
"""
# assign W to the next best data sample
self._Wmapped_index = vq(self.data, self.W)
self.Wmapped = np.zeros(self.W.shape)
# do not directly assign, i.e. Wdist = self.data[:,sel... |
compute new W | def update_w(self):
""" compute new W """
def select_hull_points(data, n=3):
""" select data points for pairwise projections of the first n
dimensions """
# iterate over all projections and select data points
idx = np.array([])
# iterate over... |
Factorize s. t. WH = data | def factorize(self, show_progress=False, compute_w=True, compute_h=True,
compute_err=True, niter=1):
""" Factorize s.t. WH = data
Parameters
----------
show_progress : bool
print some extra information to stdout.
compute_h : ... |
compute new W | def update_w(self):
""" compute new W """
def select_next(iterval):
""" select the next best data sample using robust map
or simply the max iterval ... """
if self._robust_map:
k = np.argsort(iterval)[::-1]
d_sub = self.data[:,k[:self... |
Factorize s. t. WH = data | def factorize(self, show_progress=False, compute_w=True, compute_h=True,
compute_err=True, robust_cluster=3, niter=1, robust_nselect=-1):
""" Factorize s.t. WH = data
Parameters
----------
show_progress : bool
print some extra informatio... |
Main process. Returns ------- est_idxs: np. array ( N ) or list Estimated times for the segment boundaries in frame indeces. List if hierarchical segmentation. est_labels: np. array ( N - 1 ) or list Estimated labels for the segments. List if hierarchical segmentation. | def process(self):
"""Main process.
Returns
-------
est_idxs : np.array(N) or list
Estimated times for the segment boundaries in frame indeces.
List if hierarchical segmentation.
est_labels : np.array(N-1) or list
Estimated labels for the segme... |
Main process. for flat segmentation. Returns ------- est_idxs: np. array ( N ) Estimated times for the segment boundaries in frame indeces. est_labels: np. array ( N - 1 ) Estimated labels for the segments. | def processFlat(self):
"""Main process.for flat segmentation.
Returns
-------
est_idxs : np.array(N)
Estimated times for the segment boundaries in frame indeces.
est_labels : np.array(N-1)
Estimated labels for the segments.
"""
self.config[... |
Main process. for hierarchial segmentation. Returns ------- est_idxs: list List with np. arrays for each layer of segmentation containing the estimated indeces for the segment boundaries. est_labels: list List with np. arrays containing the labels for each layer of the hierarchical segmentation. | def processHierarchical(self):
"""Main process.for hierarchial segmentation.
Returns
-------
est_idxs : list
List with np.arrays for each layer of segmentation containing
the estimated indeces for the segment boundaries.
est_labels : list
List ... |
Median filter along the first axis of the feature matrix X. | def median_filter(X, M=8):
"""Median filter along the first axis of the feature matrix X."""
for i in range(X.shape[1]):
X[:, i] = filters.median_filter(X[:, i], size=M)
return X |
Creates a gaussian kernel following Foote s paper. | def compute_gaussian_krnl(M):
"""Creates a gaussian kernel following Foote's paper."""
g = signal.gaussian(M, M // 3., sym=True)
G = np.dot(g.reshape(-1, 1), g.reshape(1, -1))
G[M // 2:, :M // 2] = -G[M // 2:, :M // 2]
G[:M // 2, M // 2:] = -G[:M // 2, M // 2:]
return G |
Computes the self - similarity matrix of X. | def compute_ssm(X, metric="seuclidean"):
"""Computes the self-similarity matrix of X."""
D = distance.pdist(X, metric=metric)
D = distance.squareform(D)
D /= D.max()
return 1 - D |
Computes the novelty curve from the self - similarity matrix X and the gaussian kernel G. | def compute_nc(X, G):
"""Computes the novelty curve from the self-similarity matrix X and
the gaussian kernel G."""
N = X.shape[0]
M = G.shape[0]
nc = np.zeros(N)
for i in range(M // 2, N - M // 2 + 1):
nc[i] = np.sum(X[i - M // 2:i + M // 2, i - M // 2:i + M // 2] * G)
# Norma... |
Obtain peaks from a novelty curve using an adaptive threshold. | def pick_peaks(nc, L=16):
"""Obtain peaks from a novelty curve using an adaptive threshold."""
offset = nc.mean() / 20.
nc = filters.gaussian_filter1d(nc, sigma=4) # Smooth out nc
th = filters.median_filter(nc, size=L) + offset
#th = filters.gaussian_filter(nc, sigma=L/2., mode="nearest") + offse... |
Main process. Returns ------- est_idxs: np. array ( N ) Estimated indeces the segment boundaries in frames. est_labels: np. array ( N - 1 ) Estimated labels for the segments. | def processFlat(self):
"""Main process.
Returns
-------
est_idxs : np.array(N)
Estimated indeces the segment boundaries in frames.
est_labels : np.array(N-1)
Estimated labels for the segments.
"""
# Preprocess to obtain features
F =... |
Factorize s. t. WH = data | def factorize(self, show_progress=False, compute_w=True, compute_h=True,
compute_err=True, niter=1):
""" Factorize s.t. WH = data
Parameters
----------
show_progress : bool
print some extra information to stdout.
niter : int
... |
Gaussian filter along the first axis of the feature matrix X. | def gaussian_filter(X, M=8, axis=0):
"""Gaussian filter along the first axis of the feature matrix X."""
for i in range(X.shape[axis]):
if axis == 1:
X[:, i] = filters.gaussian_filter(X[:, i], sigma=M / 2.)
elif axis == 0:
X[i, :] = filters.gaussian_filter(X[i, :], sigma=... |
Computes the novelty curve from the structural features. | def compute_nc(X):
"""Computes the novelty curve from the structural features."""
N = X.shape[0]
# nc = np.sum(np.diff(X, axis=0), axis=1) # Difference between SF's
nc = np.zeros(N)
for i in range(N - 1):
nc[i] = distance.euclidean(X[i, :], X[i + 1, :])
# Normalize
nc += np.abs(nc.... |
Obtain peaks from a novelty curve using an adaptive threshold. | def pick_peaks(nc, L=16, offset_denom=0.1):
"""Obtain peaks from a novelty curve using an adaptive threshold."""
offset = nc.mean() * float(offset_denom)
th = filters.median_filter(nc, size=L) + offset
#th = filters.gaussian_filter(nc, sigma=L/2., mode="nearest") + offset
#import pylab as plt
#p... |
Shifts circularly the X squre matrix in order to get a time - lag matrix. | def circular_shift(X):
"""Shifts circularly the X squre matrix in order to get a
time-lag matrix."""
N = X.shape[0]
L = np.zeros(X.shape)
for i in range(N):
L[i, :] = np.asarray([X[(i + j) % N, j] for j in range(N)])
return L |
Time - delay embedding with m dimensions and tau delays. | def embedded_space(X, m, tau=1):
"""Time-delay embedding with m dimensions and tau delays."""
N = X.shape[0] - int(np.ceil(m))
Y = np.zeros((N, int(np.ceil(X.shape[1] * m))))
for i in range(N):
# print X[i:i+m,:].flatten().shape, w, X.shape
# print Y[i,:].shape
rem = int((m % 1) ... |
Main process. Returns ------- est_idxs: np. array ( N ) Estimated times for the segment boundaries in frame indeces. est_labels: np. array ( N - 1 ) Estimated labels for the segments. | def processFlat(self):
"""Main process.
Returns
-------
est_idxs : np.array(N)
Estimated times for the segment boundaries in frame indeces.
est_labels : np.array(N-1)
Estimated labels for the segments.
"""
# Structural Features params
... |
Formats the plot with the correct axis labels title ticks and so on. | def _plot_formatting(title, est_file, algo_ids, last_bound, N, output_file):
"""Formats the plot with the correct axis labels, title, ticks, and
so on."""
import matplotlib.pyplot as plt
if title is None:
title = os.path.basename(est_file).split(".")[0]
plt.title(title)
plt.yticks(np.ara... |
Plots all the boundaries. | def plot_boundaries(all_boundaries, est_file, algo_ids=None, title=None,
output_file=None):
"""Plots all the boundaries.
Parameters
----------
all_boundaries: list
A list of np.arrays containing the times of the boundaries, one array
for each algorithm.
est_file:... |
Plots all the labels. | def plot_labels(all_labels, gt_times, est_file, algo_ids=None, title=None,
output_file=None):
"""Plots all the labels.
Parameters
----------
all_labels: list
A list of np.arrays containing the labels of the boundaries, one array
for each algorithm.
gt_times: np.array... |
Plots the results of one track with ground truth if it exists. | def plot_one_track(file_struct, est_times, est_labels, boundaries_id, labels_id,
title=None):
"""Plots the results of one track, with ground truth if it exists."""
import matplotlib.pyplot as plt
# Set up the boundaries id
bid_lid = boundaries_id
if labels_id is not None:
... |
Plots a given tree containing hierarchical segmentation. | def plot_tree(T, res=None, title=None, cmap_id="Pastel2"):
"""Plots a given tree, containing hierarchical segmentation.
Parameters
----------
T: mir_eval.segment.tree
A tree object containing the hierarchical segmentation.
res: float
Frame-rate resolution of the tree (None to use se... |
Returns a set of segments defined by the bound_idxs. | def get_feat_segments(F, bound_idxs):
"""Returns a set of segments defined by the bound_idxs.
Parameters
----------
F: np.ndarray
Matrix containing the features, one feature vector per row.
bound_idxs: np.ndarray
Array with boundary indeces.
Returns
-------
feat_segment... |
From a list of feature segments return a list of 2D - Fourier Magnitude Coefs using the maximum segment size as main size and zero pad the rest. | def feat_segments_to_2dfmc_max(feat_segments, offset=4):
"""From a list of feature segments, return a list of 2D-Fourier Magnitude
Coefs using the maximum segment size as main size and zero pad the rest.
Parameters
----------
feat_segments: list
List of segments, one for each boundary inter... |
Main function to compute the segment similarity of file file_struct. | def compute_similarity(F, bound_idxs, dirichlet=False, xmeans=False, k=5,
offset=4):
"""Main function to compute the segment similarity of file file_struct.
Parameters
----------
F: np.ndarray
Matrix containing one feature vector per row.
bound_idxs: np.ndarray
... |
Main process. Returns ------- est_idx: np. array ( N ) Estimated indeces for the segment boundaries in frames. est_labels: np. array ( N - 1 ) Estimated labels for the segments. | def processFlat(self):
"""Main process.
Returns
-------
est_idx : np.array(N)
Estimated indeces for the segment boundaries in frames.
est_labels : np.array(N-1)
Estimated labels for the segments.
"""
# Preprocess to obtain features, times, ... |
Fit the OLDA model | def fit(self, X, Y):
'''Fit the OLDA model
Parameters
----------
X : array-like, shape [n_samples]
Training data: each example is an n_features-by-* data array
Y : array-like, shape [n_samples]
Training labels: each label is an array of change-points
... |
Partial - fit the OLDA model | def partial_fit(self, X, Y):
'''Partial-fit the OLDA model
Parameters
----------
X : array-like, shape [n_samples]
Training data: each example is an n_features-by-* data array
Y : array-like, shape [n_samples]
Training labels: each label is an array of c... |
Actual implementation of the features. | def compute_features(self):
"""Actual implementation of the features.
Returns
-------
cqt: np.array(N, F)
The features, each row representing a feature vector for a give
time frame/beat.
"""
linear_cqt = np.abs(librosa.cqt(
self._audio... |
Actual implementation of the features. | def compute_features(self):
"""Actual implementation of the features.
Returns
-------
mfcc: np.array(N, F)
The features, each row representing a feature vector for a give
time frame/beat.
"""
S = librosa.feature.melspectrogram(self._audio,
... |
Actual implementation of the features. | def compute_features(self):
"""Actual implementation of the features.
Returns
-------
pcp: np.array(N, F)
The features, each row representing a feature vector for a give
time frame/beat.
"""
audio_harmonic, _ = self.compute_HPSS()
pcp_cqt ... |
Actual implementation of the features. | def compute_features(self):
"""Actual implementation of the features.
Returns
-------
tonnetz: np.array(N, F)
The features, each row representing a feature vector for a give
time frame/beat.
"""
pcp = PCP(self.file_struct, self.feat_type, self.sr,... |
Actual implementation of the features. | def compute_features(self):
"""Actual implementation of the features.
Returns
-------
tempogram: np.array(N, F)
The features, each row representing a feature vector for a give
time frame/beat.
"""
return librosa.feature.tempogram(self._audio, sr=s... |
Reads the estimations ( boundaries and/ or labels ) from a jams file containing the estimations of an algorithm. | def read_estimations(est_file, boundaries_id, labels_id=None, **params):
"""Reads the estimations (boundaries and/or labels) from a jams file
containing the estimations of an algorithm.
Parameters
----------
est_file : str
Path to the estimated file (JAMS file).
boundaries_id : str
... |
Reads the boundary times and the labels. | def read_references(audio_path, annotator_id=0):
"""Reads the boundary times and the labels.
Parameters
----------
audio_path : str
Path to the audio file
Returns
-------
ref_times : list
List of boundary times
ref_labels : list
List of labels
Raises
--... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.