Search is not available for this dataset
text
stringlengths
75
104k
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(...
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...
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...
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 ...
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...
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 ...
def _update_pipeline_status(self): """ Parses the .nextflow.log file for signatures of pipeline status and sets the :attr:`status_info` attribute. """ prev_status = self.status_info with open(self.log_file) as fh: for line in fh: if "Sessio...
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...
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 ...
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...
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 ...
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...
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...
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...
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...
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...
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...
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(...
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 ...
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...
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...
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 ...
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...
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...
def main(sample_id, fastq_pair, gsize, minimum_coverage, opts): """ Main executor of the integrity_coverage template. Parameters ---------- sample_id : str Sample Identification string. fastq_pair : list Two element list containing the paired FastQ files. gsize : float or int ...
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...
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...
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...
def check_filtered_assembly(coverage_info, coverage_bp, minimum_coverage, genome_size, contig_size, max_contigs, sample_id): """Checks whether a filtered assembly passes a size threshold Given a minimum coverage threshold, this function evaluates whether ...
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 ...
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...
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...
def main(sample_id, assembly_file, gsize, opts, assembler): """Main executor of the process_spades template. Parameters ---------- sample_id : str Sample Identification string. assembly_file : str Path to the assembly file generated by Spades. gsize : int Estimate of gen...
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',...
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...
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_...
def factorize(self): """ Factorize s.t. CUR = data Updated Values -------------- .C : updated values for C. .U : updated values for U. .R : updated values for R. """ [prow, pcol] = self.sample_probability() self._rid = self.s...
def factorize(self): """ Factorize s.t. CUR = data Updated Values -------------- .C : updated values for C. .U : updated values for U. .R : updated values for R. """ [prow, pcol] = self.sample_probability() self._rid = self.sam...
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...
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...
def update_w(self): """ compute new W """ def select_hull_points(data, n=3): """ select data points for pairwise projections of the first n dimensions """ # iterate over all projections and select data points idx = np.array([]) # iterate over...
def factorize(self, show_progress=False, compute_w=True, compute_h=True, compute_err=True, niter=1): """ Factorize s.t. WH = data Parameters ---------- show_progress : bool print some extra information to stdout. compute_h : ...
def update_w(self): """ compute new W """ def select_next(iterval): """ select the next best data sample using robust map or simply the max iterval ... """ if self._robust_map: k = np.argsort(iterval)[::-1] d_sub = self.data[:,k[:self...
def factorize(self, show_progress=False, compute_w=True, compute_h=True, compute_err=True, robust_cluster=3, niter=1, robust_nselect=-1): """ Factorize s.t. WH = data Parameters ---------- show_progress : bool print some extra informatio...
def process(self): """Main process. Returns ------- est_idxs : np.array(N) or list Estimated times for the segment boundaries in frame indeces. List if hierarchical segmentation. est_labels : np.array(N-1) or list Estimated labels for the segme...
def processFlat(self): """Main process.for flat segmentation. Returns ------- est_idxs : np.array(N) Estimated times for the segment boundaries in frame indeces. est_labels : np.array(N-1) Estimated labels for the segments. """ self.config[...
def processHierarchical(self): """Main process.for hierarchial segmentation. Returns ------- est_idxs : list List with np.arrays for each layer of segmentation containing the estimated indeces for the segment boundaries. est_labels : list List ...
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
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
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
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...
def pick_peaks(nc, L=16): """Obtain peaks from a novelty curve using an adaptive threshold.""" offset = nc.mean() / 20. nc = filters.gaussian_filter1d(nc, sigma=4) # Smooth out nc th = filters.median_filter(nc, size=L) + offset #th = filters.gaussian_filter(nc, sigma=L/2., mode="nearest") + offse...
def processFlat(self): """Main process. Returns ------- est_idxs : np.array(N) Estimated indeces the segment boundaries in frames. est_labels : np.array(N-1) Estimated labels for the segments. """ # Preprocess to obtain features F =...
def factorize(self, show_progress=False, compute_w=True, compute_h=True, compute_err=True, niter=1): """ Factorize s.t. WH = data Parameters ---------- show_progress : bool print some extra information to stdout. niter : int ...
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=...
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....
def pick_peaks(nc, L=16, offset_denom=0.1): """Obtain peaks from a novelty curve using an adaptive threshold.""" offset = nc.mean() * float(offset_denom) th = filters.median_filter(nc, size=L) + offset #th = filters.gaussian_filter(nc, sigma=L/2., mode="nearest") + offset #import pylab as plt #p...
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
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) ...
def processFlat(self): """Main process. Returns ------- est_idxs : np.array(N) Estimated times for the segment boundaries in frame indeces. est_labels : np.array(N-1) Estimated labels for the segments. """ # Structural Features params ...
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...
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:...
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...
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: ...
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...
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...
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...
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 ...
def processFlat(self): """Main process. Returns ------- est_idx : np.array(N) Estimated indeces for the segment boundaries in frames. est_labels : np.array(N-1) Estimated labels for the segments. """ # Preprocess to obtain features, times, ...
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 ...
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...
def compute_features(self): """Actual implementation of the features. Returns ------- cqt: np.array(N, F) The features, each row representing a feature vector for a give time frame/beat. """ linear_cqt = np.abs(librosa.cqt( self._audio...
def compute_features(self): """Actual implementation of the features. Returns ------- mfcc: np.array(N, F) The features, each row representing a feature vector for a give time frame/beat. """ S = librosa.feature.melspectrogram(self._audio, ...
def compute_features(self): """Actual implementation of the features. Returns ------- pcp: np.array(N, F) The features, each row representing a feature vector for a give time frame/beat. """ audio_harmonic, _ = self.compute_HPSS() pcp_cqt ...
def compute_features(self): """Actual implementation of the features. Returns ------- tonnetz: np.array(N, F) The features, each row representing a feature vector for a give time frame/beat. """ pcp = PCP(self.file_struct, self.feat_type, self.sr,...
def compute_features(self): """Actual implementation of the features. Returns ------- tempogram: np.array(N, F) The features, each row representing a feature vector for a give time frame/beat. """ return librosa.feature.tempogram(self._audio, sr=s...
def read_estimations(est_file, boundaries_id, labels_id=None, **params): """Reads the estimations (boundaries and/or labels) from a jams file containing the estimations of an algorithm. Parameters ---------- est_file : str Path to the estimated file (JAMS file). boundaries_id : str ...
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 --...
def align_times(times, frames): """Aligns the times to the closest frame times (e.g. beats). Parameters ---------- times: np.ndarray Times in seconds to be aligned. frames: np.ndarray Frame times in seconds. Returns ------- aligned_times: np.ndarray Aligned time...
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...
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 ...
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__ + "." ...
def get_all_label_algorithms(): """Gets all the possible label (structural grouping) algorithms in MSAF. Returns ------- algo_ids : list List of all the IDs of label algorithms (strings). """ algo_ids = [] for name in msaf.algorithms.__all__: module = eval(msaf.algorithms.__...
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...
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...
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 ...
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: ...
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...
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)
def processFlat(self): """Main process. Returns ------- est_idxs : np.array(N) Estimated indeces the segment boundaries in frame indeces. est_labels : np.array(N-1) Estimated labels for the segments. """ # Preprocess to obtain features (arr...
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...
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 ...
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...
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 ...
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....
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 ...
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]
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)
def _compute_all_features(self): """Computes all the features (beatsync, framesync) from the audio.""" # Read actual audio waveform self._audio, _ = librosa.load(self.file_struct.audio_file, sr=self.sr) # Get duration of audio file self.dur ...
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...