_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q272800 | NextflowGenerator.export_params | test | 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... | python | {
"resource": ""
} |
q272801 | NextflowGenerator.export_directives | test | 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(... | python | {
"resource": ""
} |
q272802 | NextflowGenerator.fetch_docker_tags | test | 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... | python | {
"resource": ""
} |
q272803 | NextflowGenerator.build | test | 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... | python | {
"resource": ""
} |
q272804 | set_kmers | test | 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 ... | python | {
"resource": ""
} |
q272805 | main | test | 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... | python | {
"resource": ""
} |
q272806 | FlowcraftReport._get_report_id | test | 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 ... | python | {
"resource": ""
} |
q272807 | FlowcraftReport.update_trace_watch | test | 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... | python | {
"resource": ""
} |
q272808 | FlowcraftReport.update_log_watch | test | 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
... | python | {
"resource": ""
} |
q272809 | FlowcraftReport._send_live_report | test | 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... | python | {
"resource": ""
} |
q272810 | FlowcraftReport._init_live_reports | test | 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 ... | python | {
"resource": ""
} |
q272811 | FlowcraftReport._close_connection | test | 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... | python | {
"resource": ""
} |
q272812 | convert_adatpers | test | 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... | python | {
"resource": ""
} |
q272813 | main | test | 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... | python | {
"resource": ""
} |
q272814 | send_to_output | test | 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... | python | {
"resource": ""
} |
q272815 | main | test | 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... | python | {
"resource": ""
} |
q272816 | MainWrapper.build_versions | test | 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... | python | {
"resource": ""
} |
q272817 | main | test | 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(... | python | {
"resource": ""
} |
q272818 | colored_print | test | 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 ... | python | {
"resource": ""
} |
q272819 | procs_dict_parser | test | 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... | python | {
"resource": ""
} |
q272820 | proc_collector | test | 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... | python | {
"resource": ""
} |
q272821 | guess_file_compression | test | 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 ... | python | {
"resource": ""
} |
q272822 | get_qual_range | test | 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... | python | {
"resource": ""
} |
q272823 | get_encodings_in_range | test | 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... | python | {
"resource": ""
} |
q272824 | parse_coverage_table | test | 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... | python | {
"resource": ""
} |
q272825 | filter_assembly | test | 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... | python | {
"resource": ""
} |
q272826 | filter_bam | test | 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... | python | {
"resource": ""
} |
q272827 | evaluate_min_coverage | test | 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
... | python | {
"resource": ""
} |
q272828 | get_assembly_size | test | 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... | python | {
"resource": ""
} |
q272829 | main | test | 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... | python | {
"resource": ""
} |
q272830 | convert_camel_case | test | 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',... | python | {
"resource": ""
} |
q272831 | collect_process_map | test | 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... | python | {
"resource": ""
} |
q272832 | main | test | 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_... | python | {
"resource": ""
} |
q272833 | quickhull | test | 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... | python | {
"resource": ""
} |
q272834 | CHNMF._map_w_to_data | test | 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... | python | {
"resource": ""
} |
q272835 | median_filter | test | 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 | python | {
"resource": ""
} |
q272836 | compute_gaussian_krnl | test | 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 | python | {
"resource": ""
} |
q272837 | compute_ssm | test | 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 | python | {
"resource": ""
} |
q272838 | compute_nc | test | 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... | python | {
"resource": ""
} |
q272839 | gaussian_filter | test | 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=... | python | {
"resource": ""
} |
q272840 | compute_nc | test | 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.... | python | {
"resource": ""
} |
q272841 | circular_shift | test | 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 | python | {
"resource": ""
} |
q272842 | embedded_space | test | 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) ... | python | {
"resource": ""
} |
q272843 | _plot_formatting | test | 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... | python | {
"resource": ""
} |
q272844 | plot_boundaries | test | 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:... | python | {
"resource": ""
} |
q272845 | plot_labels | test | 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... | python | {
"resource": ""
} |
q272846 | plot_one_track | test | 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:
... | python | {
"resource": ""
} |
q272847 | plot_tree | test | 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... | python | {
"resource": ""
} |
q272848 | get_feat_segments | test | 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... | python | {
"resource": ""
} |
q272849 | feat_segments_to_2dfmc_max | test | 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... | python | {
"resource": ""
} |
q272850 | compute_similarity | test | 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
... | python | {
"resource": ""
} |
q272851 | OLDA.fit | test | 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
... | python | {
"resource": ""
} |
q272852 | OLDA.partial_fit | test | 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... | python | {
"resource": ""
} |
q272853 | read_references | test | 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
--... | python | {
"resource": ""
} |
q272854 | find_estimation | test | def find_estimation(jam, boundaries_id, labels_id, params):
"""Finds the correct estimation from all the estimations contained in a
JAMS file given the specified arguments.
Parameters
----------
jam : jams.JAMS
JAMS object.
boundaries_id : str
Identifier of the algorithm used to... | python | {
"resource": ""
} |
q272855 | save_estimations | test | def save_estimations(file_struct, times, labels, boundaries_id, labels_id,
**params):
"""Saves the segment estimations in a JAMS file.
Parameters
----------
file_struct : FileStruct
Object with the different file paths of the current file.
times : np.array or list
... | python | {
"resource": ""
} |
q272856 | get_all_boundary_algorithms | test | def get_all_boundary_algorithms():
"""Gets all the possible boundary algorithms in MSAF.
Returns
-------
algo_ids : list
List of all the IDs of boundary algorithms (strings).
"""
algo_ids = []
for name in msaf.algorithms.__all__:
module = eval(msaf.algorithms.__name__ + "." ... | python | {
"resource": ""
} |
q272857 | get_configuration | test | def get_configuration(feature, annot_beats, framesync, boundaries_id,
labels_id):
"""Gets the configuration dictionary from the current parameters of the
algorithms to be evaluated."""
config = {}
config["annot_beats"] = annot_beats
config["feature"] = feature
config["frame... | python | {
"resource": ""
} |
q272858 | get_dataset_files | test | def get_dataset_files(in_path):
"""Gets the files of the given dataset."""
# Get audio files
audio_files = []
for ext in ds_config.audio_exts:
audio_files += glob.glob(
os.path.join(in_path, ds_config.audio_dir, "*" + ext))
# Make sure directories exist
utils.ensure_dir(os.p... | python | {
"resource": ""
} |
q272859 | read_hier_references | test | def read_hier_references(jams_file, annotation_id=0, exclude_levels=[]):
"""Reads hierarchical references from a jams file.
Parameters
----------
jams_file : str
Path to the jams file.
annotation_id : int > 0
Identifier of the annotator to read from.
exclude_levels: list
... | python | {
"resource": ""
} |
q272860 | get_duration | test | def get_duration(features_file):
"""Reads the duration of a given features file.
Parameters
----------
features_file: str
Path to the JSON file containing the features.
Returns
-------
dur: float
Duration of the analyzed file.
"""
with open(features_file) as f:
... | python | {
"resource": ""
} |
q272861 | write_mirex | test | def write_mirex(times, labels, out_file):
"""Writes results to file using the standard MIREX format.
Parameters
----------
times: np.array
Times in seconds of the boundaries.
labels: np.array
Labels associated to the segments defined by the boundaries.
out_file: str
Outp... | python | {
"resource": ""
} |
q272862 | FileStruct._get_dataset_file | test | def _get_dataset_file(self, dir, ext):
"""Gets the desired dataset file."""
audio_file_ext = "." + self.audio_file.split(".")[-1]
base_file = os.path.basename(self.audio_file).replace(
audio_file_ext, ext)
return os.path.join(self.ds_path, dir, base_file) | python | {
"resource": ""
} |
q272863 | align_segmentation | test | def align_segmentation(beat_times, song):
'''Load a ground-truth segmentation, and align times to the nearest
detected beats.
Arguments:
beat_times -- array
song -- path to the audio file
Returns:
segment_beats -- array
beat-aligned segment boundaries
segme... | python | {
"resource": ""
} |
q272864 | Features.estimate_beats | test | def estimate_beats(self):
"""Estimates the beats using librosa.
Returns
-------
times: np.array
Times of estimated beats in seconds.
frames: np.array
Frame indeces of estimated beats.
"""
# Compute harmonic-percussive source separation if ... | python | {
"resource": ""
} |
q272865 | Features.read_ann_beats | test | def read_ann_beats(self):
"""Reads the annotated beats if available.
Returns
-------
times: np.array
Times of annotated beats in seconds.
frames: np.array
Frame indeces of annotated beats.
"""
times, frames = (None, None)
# Read a... | python | {
"resource": ""
} |
q272866 | Features.compute_beat_sync_features | test | def compute_beat_sync_features(self, beat_frames, beat_times, pad):
"""Make the features beat-synchronous.
Parameters
----------
beat_frames: np.array
The frame indeces of the beat positions.
beat_times: np.array
The time points of the beat positions (in ... | python | {
"resource": ""
} |
q272867 | Features.read_features | test | def read_features(self, tol=1e-3):
"""Reads the features from a file and stores them in the current
object.
Parameters
----------
tol: float
Tolerance level to detect duration of audio.
"""
try:
# Read JSON file
with open(self.... | python | {
"resource": ""
} |
q272868 | Features.write_features | test | def write_features(self):
"""Saves features to file."""
out_json = collections.OrderedDict()
try:
# Only save the necessary information
self.read_features()
except (WrongFeaturesFormatError, FeaturesNotFound,
NoFeaturesFileError):
# We ... | python | {
"resource": ""
} |
q272869 | Features.get_param_names | test | def get_param_names(self):
"""Returns the parameter names for these features, avoiding
the global parameters."""
return [name for name in vars(self) if not name.startswith('_') and
name not in self._global_param_names] | python | {
"resource": ""
} |
q272870 | Features._compute_framesync_times | test | def _compute_framesync_times(self):
"""Computes the framesync times based on the framesync features."""
self._framesync_times = librosa.core.frames_to_time(
np.arange(self._framesync_features.shape[0]), self.sr,
self.hop_length) | python | {
"resource": ""
} |
q272871 | Features.frame_times | test | def frame_times(self):
"""This getter returns the frame times, for the corresponding type of
features."""
frame_times = None
# Make sure we have already computed the features
self.features
if self.feat_type is FeatureTypes.framesync:
self._compute_framesync_ti... | python | {
"resource": ""
} |
q272872 | Features.features | test | def features(self):
"""This getter will compute the actual features if they haven't
been computed yet.
Returns
-------
features: np.array
The actual features. Each row corresponds to a feature vector.
"""
# Compute features if needed
if self._... | python | {
"resource": ""
} |
q272873 | Features.select_features | test | def select_features(cls, features_id, file_struct, annot_beats, framesync):
"""Selects the features from the given parameters.
Parameters
----------
features_id: str
The identifier of the features (it must be a key inside the
`features_registry`)
file_str... | python | {
"resource": ""
} |
q272874 | SegmenterInterface._preprocess | test | def _preprocess(self, valid_features=["pcp", "tonnetz", "mfcc",
"cqt", "tempogram"]):
"""This method obtains the actual features."""
# Use specific feature
if self.feature_str not in valid_features:
raise RuntimeError("Feature %s in not valid... | python | {
"resource": ""
} |
q272875 | SegmenterInterface._postprocess | test | def _postprocess(self, est_idxs, est_labels):
"""Post processes the estimations from the algorithm, removing empty
segments and making sure the lenghts of the boundaries and labels
match."""
# Make sure we are using the previously input bounds, if any
if self.in_bound_idxs is not... | python | {
"resource": ""
} |
q272876 | main | test | def main():
"""Main function to sweep parameters of a certain algorithm."""
parser = argparse.ArgumentParser(
description="Runs the speficied algorithm(s) on the MSAF "
"formatted dataset.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("in_path",
... | python | {
"resource": ""
} |
q272877 | print_results | test | def print_results(results):
"""Print all the results.
Parameters
----------
results: pd.DataFrame
Dataframe with all the results
"""
if len(results) == 0:
logging.warning("No results to print!")
return
res = results.mean()
logging.info("Results:\n%s" % res) | python | {
"resource": ""
} |
q272878 | compute_gt_results | test | def compute_gt_results(est_file, ref_file, boundaries_id, labels_id, config,
bins=251, annotator_id=0):
"""Computes the results by using the ground truth dataset identified by
the annotator parameter.
Return
------
results : dict
Dictionary of the results (see functio... | python | {
"resource": ""
} |
q272879 | compute_information_gain | test | def compute_information_gain(ann_inter, est_inter, est_file, bins):
"""Computes the information gain of the est_file from the annotated
intervals and the estimated intervals."""
ann_times = utils.intervals_to_times(ann_inter)
est_times = utils.intervals_to_times(est_inter)
return mir_eval.beat.infor... | python | {
"resource": ""
} |
q272880 | process_track | test | def process_track(file_struct, boundaries_id, labels_id, config,
annotator_id=0):
"""Processes a single track.
Parameters
----------
file_struct : object (FileStruct) or str
File struct or full path of the audio file to be evaluated.
boundaries_id : str
Identifier ... | python | {
"resource": ""
} |
q272881 | get_results_file_name | test | def get_results_file_name(boundaries_id, labels_id, config,
annotator_id):
"""Based on the config and the dataset, get the file name to store the
results."""
utils.ensure_dir(msaf.config.results_dir)
file_name = os.path.join(msaf.config.results_dir, "results")
file_name += ... | python | {
"resource": ""
} |
q272882 | process | test | def process(in_path, boundaries_id=msaf.config.default_bound_id,
labels_id=msaf.config.default_label_id, annot_beats=False,
framesync=False, feature="pcp", hier=False, save=False,
out_file=None, n_jobs=4, annotator_id=0, config=None):
"""Main process to evaluate algorithms' resul... | python | {
"resource": ""
} |
q272883 | AddConfigVar | test | def AddConfigVar(name, doc, configparam, root=config):
"""Add a new variable to msaf.config
Parameters
----------
name: str
String of the form "[section0.[section1.[etc]]]option", containing the
full name for this configuration variable.
string: str
What does this variable s... | python | {
"resource": ""
} |
q272884 | compute_all_features | test | def compute_all_features(file_struct, framesync):
"""Computes all features for the given file."""
for feature_id in msaf.features_registry:
logging.info("Computing %s for file %s" % (feature_id,
file_struct.audio_file))
feats = Features.select_f... | python | {
"resource": ""
} |
q272885 | process | test | def process(in_path, out_file, n_jobs, framesync):
"""Computes the features for the selected dataset or file."""
if os.path.isfile(in_path):
# Single file mode
# Get (if they exitst) or compute features
file_struct = msaf.io.FileStruct(in_path)
file_struct.features_file = out_fil... | python | {
"resource": ""
} |
q272886 | gaussian_cost | test | def gaussian_cost(X):
'''Return the average log-likelihood of data under a standard normal
'''
d, n = X.shape
if n < 2:
return 0
sigma = np.var(X, axis=1, ddof=1)
cost = -0.5 * d * n * np.log(2. * np.pi) - 0.5 * (n - 1.) * np.sum(sigma)
return cost | python | {
"resource": ""
} |
q272887 | lognormalize | test | def lognormalize(F, floor=0.1, min_db=-80):
"""Log-normalizes features such that each vector is between min_db to 0."""
assert min_db < 0
F = min_max_normalize(F, floor=floor)
F = np.abs(min_db) * np.log10(F) # Normalize from min_db to 0
return F | python | {
"resource": ""
} |
q272888 | min_max_normalize | test | def min_max_normalize(F, floor=0.001):
"""Normalizes features such that each vector is between floor to 1."""
F += -F.min() + floor
F = F / F.max(axis=0)
return F | python | {
"resource": ""
} |
q272889 | normalize | test | def normalize(X, norm_type, floor=0.0, min_db=-80):
"""Normalizes the given matrix of features.
Parameters
----------
X: np.array
Each row represents a feature vector.
norm_type: {"min_max", "log", np.inf, -np.inf, 0, float > 0, None}
- `"min_max"`: Min/max scaling is performed
... | python | {
"resource": ""
} |
q272890 | get_time_frames | test | def get_time_frames(dur, anal):
"""Gets the time frames and puts them in a numpy array."""
n_frames = get_num_frames(dur, anal)
return np.linspace(0, dur, num=n_frames) | python | {
"resource": ""
} |
q272891 | remove_empty_segments | test | def remove_empty_segments(times, labels):
"""Removes empty segments if needed."""
assert len(times) - 1 == len(labels)
inters = times_to_intervals(times)
new_inters = []
new_labels = []
for inter, label in zip(inters, labels):
if inter[0] < inter[1]:
new_inters.append(inter)
... | python | {
"resource": ""
} |
q272892 | sonify_clicks | test | def sonify_clicks(audio, clicks, out_file, fs, offset=0):
"""Sonifies the estimated times into the output file.
Parameters
----------
audio: np.array
Audio samples of the input track.
clicks: np.array
Click positions in seconds.
out_file: str
Path to the output file.
... | python | {
"resource": ""
} |
q272893 | synchronize_labels | test | def synchronize_labels(new_bound_idxs, old_bound_idxs, old_labels, N):
"""Synchronizes the labels from the old_bound_idxs to the new_bound_idxs.
Parameters
----------
new_bound_idxs: np.array
New indeces to synchronize with.
old_bound_idxs: np.array
Old indeces, same shape as labels... | python | {
"resource": ""
} |
q272894 | process_segmentation_level | test | def process_segmentation_level(est_idxs, est_labels, N, frame_times, dur):
"""Processes a level of segmentation, and converts it into times.
Parameters
----------
est_idxs: np.array
Estimated boundaries in frame indeces.
est_labels: np.array
Estimated labels.
N: int
Numb... | python | {
"resource": ""
} |
q272895 | align_end_hierarchies | test | def align_end_hierarchies(hier1, hier2, thres=0.5):
"""Align the end of the hierarchies such that they end at the same exact
second as long they have the same duration within a certain threshold.
Parameters
----------
hier1: list
List containing hierarchical segment boundaries.
hier2: l... | python | {
"resource": ""
} |
q272896 | SIVM._distance | test | def _distance(self, idx):
""" compute distances of a specific data point to all other samples"""
if scipy.sparse.issparse(self.data):
step = self.data.shape[1]
else:
step = 50000
d = np.zeros((self.data.shape[1]))
if idx == -1:
# set vec to o... | python | {
"resource": ""
} |
q272897 | XMeans.estimate_K_knee | test | def estimate_K_knee(self, th=.015, maxK=12):
"""Estimates the K using K-means and BIC, by sweeping various K and
choosing the optimal BIC."""
# Sweep K-means
if self.X.shape[0] < maxK:
maxK = self.X.shape[0]
if maxK < 2:
maxK = 2
K = np.arange(... | python | {
"resource": ""
} |
q272898 | XMeans.get_clustered_data | test | def get_clustered_data(self, X, labels, label_index):
"""Returns the data with a specific label_index, using the previously
learned labels."""
D = X[np.argwhere(labels == label_index)]
return D.reshape((D.shape[0], D.shape[-1])) | python | {
"resource": ""
} |
q272899 | XMeans.run_kmeans | test | def run_kmeans(self, X, K):
"""Runs k-means and returns the labels assigned to the data."""
wX = vq.whiten(X)
means, dist = vq.kmeans(wX, K, iter=100)
labels, dist = vq.vq(wX, means)
return means, labels | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.