_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
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 = {}
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:]:
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 = {} # fetches terminal width and subtracts 3 because we always add a # new line character and we want a space at the beggining and at the end # of each line terminal_width = shutil.get_terminal_size().columns - 3 # first header center_string = " Selected container tags " # starts a list with the headers tags_list = [ [ "=" * int(terminal_width / 4), "{0}{1}{0}".format( "=" * int(((terminal_width/2 - len(center_string)) / 2)), center_string) , "{}\n".format("=" * int(terminal_width / 4)) ], ["component", "container", "tags"], [ "=" * int(terminal_width / 4), "=" * int(terminal_width / 2), "=" * int(terminal_width / 4) ] ] # Skip first init process and iterate through the others for p in self.processes[1:]: template = p.template # if component has already been printed then skip and don't print # again if template in dict_of_parsed: continue # starts a list of containers for the current process in # dict_of_parsed, in which each containers will be added to this # list once it gets parsed dict_of_parsed[template] = { "container": [] } # fetch repo name from directives of each component. for directives in p.directives.values(): try: repo = directives["container"] default_version = directives["version"] except KeyError: # adds the default container if container key isn't present # this happens for instance in integrity_coverage repo = "flowcraft/flowcraft_base" default_version = "1.0.0-1" # checks if repo_version already exists in list of the # containers for the current component being queried repo_version = repo + default_version if repo_version not in dict_of_parsed[template]["container"]: # make the request to docker hub r = requests.get( "https://hub.docker.com/v2/repositories/{}/tags/" .format(repo) ) # checks the status code of the request, if it is 200 then # parses docker hub entry, otherwise retrieve no tags but # alerts the user if r.status_code != 404: # parse response content to dict and fetch results key r_content = json.loads(r.content)["results"] for version in r_content: printed_version = (version["name"] + "*") \
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, secondary channels and finally the status channels. When the pipeline is built, is writes the code to a nextflow file. """ logger.info(colored_print( "\tSuccessfully connected {} process(es) with {} " "fork(s) across {} lane(s) \u2713".format( len(self.processes[1:]), len(self._fork_tree), self.lanes))) # Generate regular nextflow header that sets up the shebang, imports # and all possible initial channels self._build_header() self._set_channels() self._set_init_process() self._set_secondary_channels() logger.info(colored_print( "\tSuccessfully set {} secondary channel(s) \u2713".format( len(self.secondary_channels)))) self._set_compiler_channels() self._set_configurations()
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 : int The maximum read length of the current sample. Returns ------- kmers : list List of k-mer values that will be provided to Spades. """ logger.debug("Kmer option set to: {}".format(kmer_opt))
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. This value is determined in :py:class:`templates.integrity_coverage` kmer : str Can be either ``'auto'``, ``'default'`` or a sequence of space separated integers, ``'23, 45, 67'``. """ logger.info("Starting spades") logger.info("Setting SPAdes kmers") kmers = set_kmers(kmer, max_len) logger.info("SPAdes kmers set to: {}".format(kmers)) cli = [ "metaspades.py", "--only-assembler", "--threads", "$task.cpus", "-o", "." ] # Add kmers, if any were specified if kmers: cli += ["-k {}".format(",".join([str(x) for x in kmers]))] # Add FastQ files cli += [ "-1", fastq_pair[0], "-2", fastq_pair[1] ] logger.debug("Running metaSPAdes subprocess with command: {}".format(cli)) p = subprocess.Popen(cli, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate() # Attempt to decode STDERR output from bytes. If unsuccessful, coerce to # string try: stderr = stderr.decode("utf8") stdout = stdout.decode("utf8") except (UnicodeDecodeError, AttributeError): stderr = str(stderr) stdout = str(stdout) logger.info("Finished metaSPAdes subprocess with STDOUT:\\n"
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 hash from the entire pipeline file pipeline_hash = hashlib.md5() with open(pipeline_path, "rb") as fh: for chunk in iter(lambda: fh.read(4096), b""): pipeline_hash.update(chunk) # Get hash from the current working dir and hostname
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_stamp = os.path.getsize(self.trace_file) self.trace_retry = 0 if size_stamp and size_stamp == self.trace_sizestamp: return else: logger.debug("Updating trace size stamp to: {}".format(size_stamp)) self.trace_sizestamp = size_stamp with open(self.trace_file) as fh: # Skip potential empty lines at the start of file header = next(fh).strip() while not header: header = next(fh).strip() # Get header mappings before parsing the file hm = self._header_mapping(header) for line in fh: # Skip empty lines
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 if size_stamp and size_stamp == self.log_sizestamp:
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` """ # Determines the maximum number of reports sent at the same time in # the same payload buffer_size = 100 logger.debug("Report buffer size set to: {}".format(buffer_size)) for i in range(0, len(self.report_queue), buffer_size): # Reset the report compilation batch reports_compilation = [] # Iterate over report JSON batches determined by buffer_size for report in self.report_queue[i: i + buffer_size]: try: report_file = [x for x in os.listdir(report) if x.endswith(".json")][0] except IndexError: continue with open(join(report, report_file)) as fh: reports_compilation.append(json.loads(fh.read())) logger.debug("Payload sent with size: {}".format( asizeof(json.dumps(reports_compilation)) )) logger.debug("status: {}".format(self.status_info)) try: requests.put( self.broadcast_address, json={"run_id": report_id, "report_json": reports_compilation, "status": self.status_info} ) except requests.exceptions.ConnectionError: logger.error(colored_print( "ERROR: Could not establish connection with server. The server" " may be down or
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 start report live" " update".format(self.broadcast_address)) try: with open(".metadata.json") as fh: metadata = [json.load(fh)] except: metadata = [] start_json = { "data": {"results": metadata} } try: requests.post( self.broadcast_address, json={"run_id": report_id, "report_json": start_json,
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 DELETE request to {}".format( self.broadcast_address)) try: r = requests.delete(self.broadcast_address, json={"run_id": report_id}) if r.status_code != 202: logger.error(colored_print(
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 AATGATACGGCGACCACCGAGATCTACACTCTTTCCCTACACGACGCTCTTCCGATCT >TruSeq_Adapter_Index 1 GATCGGAAGAGCACACGTCTGAACTCCAGTCACATCACGATCTCGTATGCCGTCTTCTGCTTG Parameters ---------- adapter_fasta : str Path to Fasta file with adapter sequences. Returns ------- adapter_out : str or None The path to the reformatted adapter file. Returns ``None`` if the adapters file does not exist or the path is incorrect. """ adapter_out = "fastqc_adapters.tab" logger.debug("Setting output adapters file to: {}".format(adapter_out)) try: with open(adapter_fasta) as fh, \ open(adapter_out, "w") as adap_fh: for line in fh: if line.startswith(">"): head
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 FastQC. """ logger.info("Starting fastqc") # If an adapter file was provided, convert it to FastQC format if os.path.exists(adapter_file): logger.info("Adapters file provided: {}".format(adapter_file)) adapters = convert_adatpers(adapter_file) else: logger.info("Adapters file '{}' not provided or does not " "exist".format(adapter_file)) adapters = None # Setting command line for FastQC cli = [ "fastqc", "--extract", "--nogroup", "--format", "fastq", "--threads", str(cpus) ] # Add adapters file to command line, if it exists if adapters: cli += ["--adapters", "{}".format(adapters)] # Add FastQ files at the end of command line cli += fastq_pair logger.debug("Running fastqc subprocess with command: {}".format(cli)) p = subprocess.Popen(cli, stdout=PIPE, stderr=PIPE, shell=False) stdout, stderr = p.communicate() # Attempt to decode STDERR output from bytes. If unsuccessful, coerce to # string try: stderr = stderr.decode("utf8") except (UnicodeDecodeError, AttributeError):
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 dictionary that stores all entries for a specific query sequence in multi-fasta given to mash dist as input against patlas database last_seq: str string that stores the last sequence that was parsed before writing to file and therefore after the change of query sequence between different rows on the input file mash_output: str the name/path of input file to main function, i.e., the name/path of the mash dist output txt file. sample_id: str The name of the sample being parse to .report.json file Returns ------- """ plot_dict = {} # create a new file only if master_dict is populated if master_dict: out_file = open("{}.json".format( "".join(mash_output.split(".")[0])), "w") out_file.write(json.dumps(master_dict)) out_file.close() # iterate through master_dict in order to make contigs the keys for k,v in master_dict.items(): if not v[2] in plot_dict:
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 between query and plasmid in database that is allowed for the plasmid to be reported to the results outputs sample_id: str The name of the sample. """ input_f = open(mash_output, "r") master_dict = {} for line in input_f: tab_split = line.split("\t") current_seq = tab_split[1].strip() ref_accession = "_".join(tab_split[0].strip().split("_")[0:3])
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 via the ``__version__``, ``__template__`` and ``__build__`` attributes. If all of these attributes exist, it starts to populate a JSON/dict array (Note that the absence of any one of them will prevent the version from being written). Then, it will search the template scope for functions that start with the substring ``__set_version`` (For example ``def __set_version_fastqc()`). These functions should gather the version of an arbitrary program and return a JSON/dict object with the following information:: { "program": <program_name>,
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("Reading file : {}".format(mash_output)) read_mash_output = open(mash_output) dic = {} median_list = [] filtered_dic = {} logger.info("Generating dictionary and list to pre-process the final json") for line in read_mash_output: tab_split = line.split("\t") identity = tab_split[0] # shared_hashes = tab_split[1] median_multiplicity = tab_split[2] # p_value = tab_split[3] query_id = tab_split[4] # query-comment should not exist here and it is irrelevant # here identity is what in fact interests to report to json but # median_multiplicity also is important since it gives an rough # estimation of the coverage depth for each plasmid. # Plasmids should have higher coverage depth due to their increased # copy number in relation to the chromosome. dic[query_id] = [identity, median_multiplicity] median_list.append(float(median_multiplicity)) output_json = open(" ".join(mash_output.split(".")[:-1]) + ".json", "w") # median cutoff is twice the median of all median_multiplicity values # reported by mash screen. In the case of plasmids, since the database # has 9k entries and reads shouldn't have that many sequences it seems ok... if len(median_list) > 0: # this statement assures that median_list has indeed any entries median_cutoff = median(median_list) logger.info("Generating final json to dump to a file") for
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 pass to the function, which enables color change as well as background color change. msg: str The actual text to be printed end_char: str The character in which each print should finish. By default it will be "\n". """
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 class attributes for all the components (or components that are used by the -t flag), that allow to create both the short_list and detailed_list. Dictionary example: {"abyss": {'input_type': 'fastq', 'output_type': 'fasta', 'dependencies': [], 'directives': {'abyss': {'cpus': 4, 'memory': '{ 5.GB * task.attempt }', 'container': 'flowcraft/abyss', 'version': '2.1.1', 'scratch': 'true'}}} """ logger.info(colored_print( "\n===== L I S T O F P R O C E S S E S =====\n", "green_bold")) #Sort to print alphabetically ordered list of processes to ease reading procs_dict_ordered = {k: procs_dict[k] for k in sorted(procs_dict)} for template, dict_proc_info in procs_dict_ordered.items():
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 Processes currently available in flowcraft and their corresponding classes as values args: argparse.Namespace The arguments passed through argparser that will be access to check the type of list to be printed pipeline_string: str the pipeline string """ arguments_list = [] # prints a detailed list of the process class arguments if args.detailed_list: # list of attributes to be passed to proc_collector arguments_list += [ "input_type", "output_type", "description", "dependencies", "conflicts", "directives" ] # prints a short list with each process and the corresponding description if args.short_list:
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 compression formats are gzip, bzip2 and zip. If none of the signatures in this dictionary are found at the beginning of the file, it returns ``None``. Parameters ---------- file_path : str Path to input file. magic_dict : dict, optional Dictionary containing the signatures of the compression types. The key should be the binary signature and the value should be the compression format. If left ``None``, it falls back to :py:data:`MAGIC_DICT`.
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
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 encoding range provided via the two first arguments, this function will return all possible encodings and phred scores. Parameters ---------- rmin : int Minimum Unicode code in range. rmax : int Maximum Unicode code in range. Returns ------- valid_encodings : list
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 information is actually gathered from the contig header using a regular expression that assumes the usual header produced by Spades:: contig_len = int(re.search("length_(.+?)_", line).group(1)) Parameters ---------- coverage_file : str Path to TSV file containing the coverage results. Returns ------- coverage_dict : OrderedDict Contains the coverage and length information for each contig. total_size : int Total size of the assembly in base pairs. total_cov : int
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 : str Path to original assembly file. minimum_coverage : int or float Minimum coverage required for a contig to pass the filter. coverage_info : OrderedDict or dict Dictionary containing the coverage information for each contig. output_file : str Path where the filtered assembly file will be generated. """ # This flag will determine whether sequence data should be written or # ignored because the current contig did not pass the minimum # coverage threshold write_flag = False with open(assembly_file) as fh, open(output_file, "w") as out_fh: for line in fh: if line.startswith(">"): # Reset write_flag write_flag = False
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 applied to the assembly file in :py:func:`filter_assembly`. Parameters ---------- coverage_info : OrderedDict or dict Dictionary containing the coverage information for each contig. bam_file : str Path to the BAM file. min_coverage : int Minimum coverage required for a contig to pass the filter. output_bam : str Path to the generated filtered BAM file. """ # Get list of contigs that will be kept contig_list = [x for x, vals in coverage_info.items() if vals["cov"] >= min_coverage] cli = [ "samtools", "view", "-bh", "-F", "4", "-o", output_bam, "-@", "1", bam_file, ] cli += contig_list logger.debug("Runnig samtools view subprocess with command: {}".format( cli)) p = subprocess.Popen(cli, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate() # Attempt to decode STDERR output from bytes. If unsuccessful, coerce to # string try: stderr = stderr.decode("utf8") stdout = stdout.decode("utf8") except (UnicodeDecodeError, AttributeError): stderr = str(stderr) stdout = str(stdout) logger.info("Finished samtools view subprocess with STDOUT:\\n" "======================================\\n{}".format(stdout)) logger.info("Fished samtools view subprocesswith STDERR:\\n"
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 to 1/3 of the assembly size, to a minimum value of 10. If it set to a int or float, the specified value will be used. assembly_coverage : int or float The average assembly coverage for a genome assembly. This value is retrieved by the `:py:func:parse_coverage_table` function. assembly_size : int The size of the genome assembly. This value is retrieved by the `py:func:get_assembly_size` function. Returns ------- x: int Minimum coverage threshold. """ if coverage_opt == "auto": # Get the 1/3 value of the current assembly coverage min_coverage = (assembly_coverage / assembly_size) * .3 logger.info("Minimum assembly coverage automatically set to: "
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 nucleotides contig_size : dict Length of each contig (contig name as key and length as value) """ assembly_size = 0 contig_size = {} header = "" with open(assembly_file) as fh: for line in fh: # Skip empty lines
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 format. coverage_file : str Path to TSV file with coverage information for each contig. coverage_bp_file : str Path to TSV file with coverage information for each base. bam_file : str Path to BAM file. opts : list List of options for processing assembly mapping. gsize : int Expected genome size """ min_assembly_coverage, max_contigs = opts logger.info("Starting assembly mapping processing") # Get coverage info, total size and total coverage from the assembly logger.info("Parsing coverage table") coverage_info, a_cov = parse_coverage_table(coverage_file) a_size, contig_size = get_assembly_size(assembly_file) logger.info("Assembly processed with a total size of '{}' and coverage" " of '{}'".format(a_size, a_cov)) # Get number of assembled bp after filters logger.info("Parsing coverage per bp table") coverage_bp_data = get_coverage_from_file(coverage_bp_file) # Assess the minimum assembly coverage min_coverage = evaluate_min_coverage(min_assembly_coverage, a_cov, a_size) # Check if filtering the assembly using the provided min_coverage will # reduce the final bp number to less than 80% of the estimated genome # size. # If the check below passes with True, then the filtered assembly # is above the 80% genome size threshold. filtered_assembly = "{}_filt.fasta".format( os.path.splitext(assembly_file)[0]) filtered_bam = "filtered.bam" logger.info("Checking filtered assembly") if check_filtered_assembly(coverage_info, coverage_bp_data, min_coverage,
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
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, which is used as the template name. Returns ------- dict Dictionary mapping the template name (snake_case) to the corresponding process class. """ process_map = {} prefix = "{}.".format(components.__name__) for importer, modname, _ in pkgutil.iter_modules(components.__path__,
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_at_midpoint() to_write=tree.as_string("newick").strip().replace("[&R] ", '').replace(' ', '_').replace("'", "") with open(".report.json", "w") as json_report: json_dic = {
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 points """ link = lambda a, b: np.concatenate((a, b[1:])) edge = lambda a, b: np.concatenate(([a], [b])) def dome(sample, base): h, t = base dists = np.dot(sample - h, np.dot(((0, -1), (1, 0)), (t - h))) outer = np.repeat(sample, dists > 0, axis=0) if len(outer):
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] # as self might be unsorted (in non ascending order)
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]):
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))
python
{ "resource": "" }
q272837
compute_ssm
test
def compute_ssm(X, metric="seuclidean"): """Computes the self-similarity matrix of X.""" D = distance.pdist(X,
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):
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]):
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
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)
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 =
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.arange(0, 1, 1 / float(N)) + 1 / (float(N)
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: str Path to the estimated file (JSON file) algo_ids : list List of algorithm ids to to read boundaries from. If None, all algorithm ids are read. title : str Title of the plot. If None, the name of the file is printed instead. """ import matplotlib.pyplot as plt N = len(all_boundaries) # Number of lists of boundaries if algo_ids is None: algo_ids = io.get_algo_ids(est_file) # Translate ids for i, algo_id in enumerate(algo_ids):
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 Array with the ground truth boundaries. est_file: str Path to the estimated file (JSON file) algo_ids : list List of algorithm ids to to read boundaries from. If None, all algorithm ids are read. title : str Title of the plot. If None, the name of the file is printed instead. """ import matplotlib.pyplot as plt N = len(all_labels) # Number of lists of labels if algo_ids is None: algo_ids = io.get_algo_ids(est_file) #
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: bid_lid += " + " + labels_id try: # Read file jam = jams.load(file_struct.ref_file) ann = jam.search(namespace='segment_.*')[0] ref_inters, ref_labels = ann.to_interval_values() # To times ref_times = utils.intervals_to_times(ref_inters) all_boundaries = [ref_times, est_times] all_labels = [ref_labels, est_labels] algo_ids = ["GT", bid_lid] except: logging.warning("No references found in %s. Not plotting groundtruth" % file_struct.ref_file) all_boundaries = [est_times] all_labels = [est_labels] algo_ids = [bid_lid] N = len(all_boundaries) # Index the labels to normalize them for i, labels in enumerate(all_labels): all_labels[i] = mir_eval.util.index_labels(labels)[0] # Get color map cm = plt.get_cmap('gist_rainbow') max_label = max(max(labels) for labels in all_labels) figsize = (8, 4) plt.figure(1, figsize=figsize, dpi=120, facecolor='w', edgecolor='k') for i, boundaries in enumerate(all_boundaries): color = "b"
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 seconds). title: str Title for the plot. `None` for no title. cmap_id: str Color Map ID """ import matplotlib.pyplot as plt def round_time(t, res=0.1): v = int(t / float(res)) * res return v # Get color map cmap = plt.get_cmap(cmap_id) # Get segments by level level_bounds = [] for level in T.levels: if level == "root": continue segments = T.get_segments_in_level(level) level_bounds.append(segments) # Plot axvspans for each segment B = float(len(level_bounds)) #plt.figure(figsize=figsize) for i, segments in enumerate(level_bounds): labels = utils.segment_labels_to_floats(segments) for segment, label in zip(segments, labels): #print i, label, cmap(label) if res is None: start = segment.start end = segment.end
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_segments: list List of segments, one for each boundary interval.
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 interval. offset: int >= 0 Number of frames to ignore from beginning and end of each segment. Returns ------- fmcs: np.ndarray Tensor containing the 2D-FMC matrices, one matrix per segment. """ if len(feat_segments) == 0: return [] # Get maximum segment size max_len
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 Array with the indeces of the segment boundaries. dirichlet: boolean Whether to use the dirichlet estimator of the number of unique labels. xmeans: boolean Whether to use the xmeans estimator of the number of unique labels. k: int > 0 If the other two predictors are `False`, use fixed number of labels. offset: int >= 0 Number of frames to ignore from beginning and end of each segment. Returns ------- labels_est: np.ndarray Estimated labels, containing integer identifiers. """ # Get the feature segments feat_segments = get_feat_segments(F, bound_idxs) # Get the 2D-FMCs segments fmcs = feat_segments_to_2dfmc_max(feat_segments, offset) if len(fmcs) == 0: return np.arange(len(bound_idxs) - 1) # Compute the labels using kmeans if dirichlet: k_init = np.min([fmcs.shape[0], k]) # Only compute the dirichlet method if the fmc shape is small enough if fmcs.shape[1] > 500:
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 (eg, a list of segment boundaries) Returns ------- self : object
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 change-points (eg, a list of segment boundaries) Returns ------- self : object ''' for (xi, yi) in itertools.izip(X, Y): prev_mean = None prev_length = None if self.scatter_within_ is None: # First round: initialize d, n = xi.shape if yi[0] > 0: yi = np.concatenate([np.array([0]), yi]) if yi[-1] < n: yi = np.concatenate([yi, np.array([n])]) self.scatter_within_ = self.sigma * np.eye(d) self.scatter_ordinal_ = np.zeros(d) # iterate over segments for (seg_start, seg_end) in zip(yi[:-1], yi[1:]): seg_length = seg_end - seg_start if seg_length < 2: continue seg_mean = np.mean(xi[:, seg_start:seg_end], axis=1, keepdims=True) seg_cov = np.cov(xi[:, seg_start:seg_end]) self.scatter_within_ = self.scatter_within_ + seg_length * seg_cov
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 ------ IOError: if `audio_path` doesn't exist. """ # Dataset path ds_path = os.path.dirname(os.path.dirname(audio_path)) # Read references jam_path = os.path.join(ds_path, ds_config.references_dir, os.path.basename(audio_path)[:-4] +
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 compute the boundaries. labels_id : str Identifier of the algorithm used to compute the labels. params : dict Additional search parameters. E.g. {"feature" : "pcp"}. Returns ------- ann : jams.Annotation Found estimation. `None` if it couldn't be found. """ # Use handy JAMS search interface namespace = "multi_segment" if
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 Estimated boundary times. If `list`, estimated hierarchical boundaries. labels : np.array(N, 2) Estimated labels (None in case we are only storing boundary evaluations). boundaries_id : str Boundary algorithm identifier. labels_id : str Labels algorithm identifier. params : dict Dictionary with additional parameters for both algorithms. """ # Remove features if they exist params.pop("features", None) # Get duration dur = get_duration(file_struct.features_file) # Convert to intervals and sanity check if 'numpy' in str(type(times)): # Flat check inters = utils.times_to_intervals(times) assert len(inters) == len(labels), "Number of boundary intervals " \ "(%d) and labels (%d) do not match" % (len(inters), len(labels)) # Put into lists to simplify the writing process later inters = [inters] labels = [labels] else: # Hierarchical check inters = [] for level in range(len(times)): est_inters = utils.times_to_intervals(times[level]) inters.append(est_inters) assert len(inters[level]) == len(labels[level]), \ "Number of boundary intervals (%d) and labels (%d) do not " \ "match in level %d" % (len(inters[level]), len(labels[level]), level) # Create new estimation namespace = "multi_segment" if params["hier"] else "segment_open" ann = jams.Annotation(namespace=namespace) # Find estimation in file if os.path.isfile(file_struct.est_file): jam = jams.load(file_struct.est_file, validate=False) curr_ann = find_estimation(jam, boundaries_id, labels_id, params) if curr_ann is not None: curr_ann.data = ann.data # cleanup all data ann = curr_ann # This will overwrite the existing estimation else: jam.annotations.append(ann) else:
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).
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["framesync"] = framesync bound_config = {} if boundaries_id != "gt": bound_config = \ eval(msaf.algorithms.__name__ + "." + boundaries_id).config config.update(bound_config) if labels_id is not None: label_config = \ eval(msaf.algorithms.__name__ + "." + labels_id).config # Make sure we don't have parameter name duplicates
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.path.join(in_path, ds_config.features_dir))
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 List of levels to exclude. Empty list to include all levels. Returns ------- hier_bounds : list List of the segment boundary times in seconds for each level. hier_labels : list List of the segment labels for each level. hier_levels : list List of strings for the level identifiers. """ hier_bounds = [] hier_labels = [] hier_levels = [] jam = jams.load(jams_file) namespaces = ["segment_salami_upper", "segment_salami_function",
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
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 Output file path to save the results. """ inters =
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
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 segment_times -- array true segment times segment_labels -- array list of segment labels ''' try: segment_times, segment_labels = msaf.io.read_references(song) except: return None, None, None segment_times = np.asarray(segment_times) # Map to intervals segment_intervals = msaf.utils.times_to_intervals(segment_times) # Map beats to intervals beat_intervals = np.asarray(zip(beat_times[:-1], beat_times[1:])) # Map beats to segments beat_segment_ids = librosa.util.match_intervals(beat_intervals, segment_intervals) segment_beats = [] segment_times_out = [] segment_labels_out = [] # print segment_times, beat_segment_ids, len(beat_times), # len(beat_segment_ids) for i in range(segment_times.shape[0]): hits = np.argwhere(beat_segment_ids == i) if len(hits) > 0 and i
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 needed if self._audio_percussive is None: self._audio_harmonic, self._audio_percussive = self.compute_HPSS() # Compute beats tempo, frames = librosa.beat.beat_track( y=self._audio_percussive, sr=self.sr, hop_length=self.hop_length) # To times
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 annotations if they exist in correct folder if os.path.isfile(self.file_struct.ref_file): try: jam = jams.load(self.file_struct.ref_file) except TypeError: logging.warning( "Can't read JAMS file %s. Maybe it's not " "compatible with current JAMS version?" % self.file_struct.ref_file) return times, frames beat_annot = jam.search(namespace="beat.*")
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 seconds). pad: boolean If `True`, `beat_frames` is padded to span the full range. Returns ------- beatsync_feats: np.array The beat-synchronized features. `None` if the beat_frames was `None`. beatsync_times: np.array The beat-synchronized times. `None` if the beat_frames was `None`. """ if beat_frames is None: return None, None # Make beat synchronous beatsync_feats = librosa.util.utils.sync(self._framesync_features.T,
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.file_struct.features_file) as f: feats = json.load(f) # Store duration if self.dur is None: self.dur = float(feats["globals"]["dur"]) # Check that we have the correct global parameters assert(np.isclose( self.dur, float(feats["globals"]["dur"]), rtol=tol)) assert(self.sr == int(feats["globals"]["sample_rate"])) assert(self.hop_length == int(feats["globals"]["hop_length"])) assert(os.path.basename(self.file_struct.audio_file) == os.path.basename(feats["globals"]["audio_file"])) # Check for specific features params feat_params_err = FeatureParamsError( "Couldn't find features for %s id in file %s" % (self.get_id(), self.file_struct.features_file)) if self.get_id() not in feats.keys(): raise feat_params_err for param_name in self.get_param_names(): value = getattr(self, param_name) if hasattr(value, '__call__'): # Special case of functions if value.__name__ != \ feats[self.get_id()]["params"][param_name]: raise feat_params_err else: if str(value) != \ feats[self.get_id()]["params"][param_name]: raise feat_params_err # Store actual features self._est_beats_times = np.array(feats["est_beats"]) self._est_beatsync_times = np.array(feats["est_beatsync_times"]) self._est_beats_frames = librosa.core.time_to_frames(
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 need to create the file or overwite it # Metadata out_json = collections.OrderedDict({"metadata": { "versions": {"librosa": librosa.__version__, "msaf": msaf.__version__, "numpy": np.__version__}, "timestamp": datetime.datetime.today().strftime( "%Y/%m/%d %H:%M:%S")}}) # Global parameters out_json["globals"] = { "dur": self.dur, "sample_rate": self.sr, "hop_length": self.hop_length, "audio_file": self.file_struct.audio_file } # Beats out_json["est_beats"] = self._est_beats_times.tolist() out_json["est_beatsync_times"] = self._est_beatsync_times.tolist() if self._ann_beats_times is not None: out_json["ann_beats"] = self._ann_beats_times.tolist() out_json["ann_beatsync_times"] = self._ann_beatsync_times.tolist() except FeatureParamsError: # We have other features in the file, simply add these ones with open(self.file_struct.features_file) as f: out_json = json.load(f)
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
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(
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_times() frame_times = self._framesync_times
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._features is None: try: self.read_features() except (NoFeaturesFileError, FeaturesNotFound, WrongFeaturesFormatError, FeatureParamsError) as e: try: self._compute_all_features() self.write_features() except IOError: if isinstance(e, FeaturesNotFound) or \ isinstance(e, FeatureParamsError): msg = "Computation of the features
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_struct: msaf.io.FileStruct The file struct containing the files to extract the features from annot_beats: boolean Whether to use annotated (`True`) or estimated (`False`) beats framesync: boolean Whether to use framesync (`True`) or beatsync (`False`) features Returns ------- features: obj The actual features object that inherits from `msaf.Features` """ if not annot_beats and framesync: feat_type = FeatureTypes.framesync elif annot_beats and not framesync: feat_type = FeatureTypes.ann_beatsync elif not annot_beats and not framesync: feat_type =
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 for algorithm: %s " "(valid features are %s)." %
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 None: F = self._preprocess() est_labels = U.synchronize_labels(self.in_bound_idxs, est_idxs, est_labels, F.shape[0]) est_idxs = self.in_bound_idxs
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", action="store", help="Input dataset") parser.add_argument("-f", action="store", dest="feature", default="pcp", type=str, help="Type of features", choices=["pcp", "tonnetz", "mfcc", "cqt", "tempogram"]) parser.add_argument("-b", action="store_true", dest="annot_beats", help="Use annotated beats", default=False) parser.add_argument("-fs", action="store_true", dest="framesync", help="Use frame-synchronous features", default=False) parser.add_argument("-bid", action="store", help="Boundary algorithm identifier", dest="boundaries_id", default="gt", choices=["gt"] + io.get_all_boundary_algorithms()) parser.add_argument("-lid", action="store",
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:
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 function compute_results). """ if config["hier"]: ref_times, ref_labels, ref_levels = \ msaf.io.read_hier_references( ref_file, annotation_id=annotator_id, exclude_levels=["segment_salami_function"]) else: jam = jams.load(ref_file, validate=False) ann = jam.search(namespace='segment_.*')[annotator_id] ref_inter, ref_labels = ann.to_interval_values() # Read estimations with correct configuration est_inter, est_labels = io.read_estimations(est_file, boundaries_id, labels_id, **config) # Compute the results and return logging.info("Evaluating %s" % os.path.basename(est_file)) if config["hier"]: # Hierarchical assert len(est_inter) == len(est_labels), "Same number of levels " \ "are required in the boundaries and labels for the hierarchical " \ "evaluation." est_times = [] est_labels = [] # Sort based on how many segments per level est_inter = sorted(est_inter, key=lambda level: len(level)) for inter in est_inter:
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
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 of the boundaries algorithm. labels_id : str Identifier of the labels algorithm. config : dict Configuration of the algorithms to be evaluated. annotator_id : int Number identifiying the annotator. Returns ------- one_res : dict Dictionary of the results (see function compute_results). """ # Convert to file_struct if string is passed if isinstance(file_struct, six.string_types): file_struct = io.FileStruct(file_struct) est_file = file_struct.est_file ref_file = file_struct.ref_file # Sanity check assert os.path.basename(est_file)[:-4] == \
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 += "_boundsE%s_labelsE%s" % (boundaries_id, labels_id) file_name += "_annotatorE%d" % (annotator_id) sorted_keys = sorted(config.keys(), key=str.lower) for key in sorted_keys:
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' results. Parameters ---------- in_path : str Path to the dataset root folder. boundaries_id : str Boundaries algorithm identifier (e.g. siplca, cnmf) labels_id : str Labels algorithm identifier (e.g. siplca, cnmf) ds_name : str Name of the dataset to be evaluated (e.g. SALAMI). * stands for all. annot_beats : boolean Whether to use the annotated beats or not. framesync: str Whether to use framesync features or not (default: False -> beatsync) feature: str String representing the feature to be used (e.g. pcp, mfcc, tonnetz) hier : bool Whether to compute a hierarchical or flat segmentation. save: boolean Whether to save the results into the `out_file` csv file. out_file: str Path to the csv file to save the results (if `None` and `save = True` it will save the results in the default file name obtained by calling `get_results_file_name`). n_jobs: int Number of processes to run in parallel. Only available in collection mode. annotator_id : int Number identifiying the annotator. config: dict Dictionary containing custom configuration parameters for the algorithms. If None, the default parameters are used. Return ------ results : pd.DataFrame DataFrame containing the evaluations for each file. """ # Set up configuration based on algorithms parameters if config is None: config = io.get_configuration(feature, annot_beats, framesync, boundaries_id, labels_id) # Hierarchical segmentation config["hier"] = hier # Remove actual features config.pop("features", None) # Get out file in case we want to save results if out_file is None: out_file = get_results_file_name(boundaries_id, labels_id, config, annotator_id) # If out_file already exists, read and return them if os.path.exists(out_file): logging.warning("Results already exists,
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 specify? configparam: `ConfigParam` An object for getting and setting this configuration parameter. root: object Used for recursive calls -- do not provide an argument for this parameter. """ # This method also performs some of the work of initializing ConfigParam # instances if root is config: # only set the name in the first call, not the recursive ones configparam.fullname = name sections = name.split('.') if len(sections) > 1: # set up a subobject if not hasattr(root, sections[0]): # every internal node in the config tree is an instance of its own # unique class
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,
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_file compute_all_features(file_struct, framesync) else: # Collection
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
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,
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."""
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 - `"log"`: Logarithmic scaling is performed - `np.inf`: Maximum absolute value - `-np.inf`: Mininum absolute value - `0`: Number of non-zeros - float: Corresponding l_p norm. - None : No normalization is performed Returns ------- norm_X: np.array
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
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]:
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. fs: int Sample rate. offset: float Offset of the clicks with respect to the audio. """ # Generate clicks (this should be done by mir_eval, but its # latest release is not compatible with latest numpy) times = clicks + offset # 1 kHz tone, 100ms click = np.sin(2 * np.pi * np.arange(fs * .1) * 1000 / (1. * fs)) # Exponential decay click *= np.exp(-np.arange(fs * .1) / (fs * .01))
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 + 1. old_labels: np.array Labels associated to the old_bound_idxs. N: int Total number of frames. Returns ------- new_labels: np.array New labels, synchronized to the new boundary indeces. """ assert len(old_bound_idxs) - 1 == len(old_labels) # Construct unfolded labels array unfold_labels = np.zeros(N) for i, (bound_idx, label)
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 Number of frames in the whole track. frame_times: np.array Time stamp for each frame. dur: float Duration of the audio track. Returns ------- est_times: np.array Estimated segment boundaries in seconds. est_labels: np.array Estimated labels for each segment. """ assert est_idxs[0] == 0 and est_idxs[-1] == N - 1 assert len(est_idxs) - 1 == len(est_labels) # Add silences, if needed
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: list List containing hierarchical segment boundaries. thres: float > 0 Threshold to decide whether two values are the same. """ # Make sure we have correctly formatted hierarchies dur_h1 = hier1[0][-1] for hier in hier1: assert hier[-1] == dur_h1, "hier1 is not correctly " \
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 origin if idx=-1 vec = np.zeros((self.data.shape[0], 1)) if scipy.sparse.issparse(self.data): vec = scipy.sparse.csc_matrix(vec) else: vec = self.data[:, idx:idx+1] self._logger.info('compute distance to node ' + str(idx)) # slice data into smaller chunks
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(1, maxK) bics = [] for k in K: means, labels = self.run_kmeans(self.X, k) bic = self.compute_bic(self.X, means, labels, K=k, R=self.X.shape[0]) bics.append(bic) diff_bics = np.diff(bics) finalK = K[-1] if len(bics) == 1: finalK = 2 else: # Normalize bics = np.asarray(bics) bics -= bics.min() #bics /= bics.max() diff_bics -= diff_bics.min() #diff_bics /= diff_bics.max() #print
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."""
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)
python
{ "resource": "" }