Search is not available for this dataset
text
stringlengths
75
104k
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._...
def select_features(cls, features_id, file_struct, annot_beats, framesync): """Selects the features from the given parameters. Parameters ---------- features_id: str The identifier of the features (it must be a key inside the `features_registry`) file_str...
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...
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...
def process(in_path, annot_beats=False, feature="mfcc", framesync=False, boundaries_id="gt", labels_id=None, n_jobs=4, config=None): """Sweeps parameters across the specified algorithm.""" results_file = "results_sweep_boundsE%s_labelsE%s.csv" % (boundaries_id, ...
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", ...
def main(): """Main function to parse the arguments and call the main process.""" parser = argparse.ArgumentParser( description="Runs the speficied algorithm(s) on the input file and " "the results using the MIREX format.", formatter_class=argparse.ArgumentDefaultsHelpFormatter) pars...
def print_results(results): """Print all the results. Parameters ---------- results: pd.DataFrame Dataframe with all the results """ if len(results) == 0: logging.warning("No results to print!") return res = results.mean() logging.info("Results:\n%s" % res)
def compute_results(ann_inter, est_inter, ann_labels, est_labels, bins, est_file, weight=0.58): """Compute the results using all the available evaluations. Parameters ---------- ann_inter : np.array Annotated intervals in seconds. est_inter : np.array Estimated i...
def compute_gt_results(est_file, ref_file, boundaries_id, labels_id, config, bins=251, annotator_id=0): """Computes the results by using the ground truth dataset identified by the annotator parameter. Return ------ results : dict Dictionary of the results (see functio...
def compute_information_gain(ann_inter, est_inter, est_file, bins): """Computes the information gain of the est_file from the annotated intervals and the estimated intervals.""" ann_times = utils.intervals_to_times(ann_inter) est_times = utils.intervals_to_times(est_inter) return mir_eval.beat.infor...
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 ...
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 += ...
def process(in_path, boundaries_id=msaf.config.default_bound_id, labels_id=msaf.config.default_label_id, annot_beats=False, framesync=False, feature="pcp", hier=False, save=False, out_file=None, n_jobs=4, annotator_id=0, config=None): """Main process to evaluate algorithms' resul...
def parse_config_string(config_string, issue_warnings=True): """ Parses a config string (comma-separated key=value components) into a dict. """ config_dict = {} my_splitter = shlex.shlex(config_string, posix=True) my_splitter.whitespace = ',' my_splitter.whitespace_split = True for kv_pa...
def fetch_val_for_key(key, delete_key=False): """Return the overriding config value for a key. A successful search returns a string value. An unsuccessful search raises a KeyError The (decreasing) priority order is: - MSAF_FLAGS - ~./msafrc """ # first try to find it in the FLAGS tr...
def AddConfigVar(name, doc, configparam, root=config): """Add a new variable to msaf.config Parameters ---------- name: str String of the form "[section0.[section1.[etc]]]option", containing the full name for this configuration variable. string: str What does this variable s...
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 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 frobenius_norm(self): """ Frobenius norm (||data - WH||) of a data matrix and a low rank approximation given by WH Returns: frobenius norm: F = ||data - WH|| """ # check if W and H exist if hasattr(self,'H') and hasattr(self,'W') and not scipy.sparse.iss...
def compute_all_features(file_struct, framesync): """Computes all features for the given file.""" for feature_id in msaf.features_registry: logging.info("Computing %s for file %s" % (feature_id, file_struct.audio_file)) feats = Features.select_f...
def process(in_path, out_file, n_jobs, framesync): """Computes the features for the selected dataset or file.""" if os.path.isfile(in_path): # Single file mode # Get (if they exitst) or compute features file_struct = msaf.io.FileStruct(in_path) file_struct.features_file = out_fil...
def main(): """Main function to parse the arguments and call the main process.""" parser = argparse.ArgumentParser( description="Extracts a set of features from a given dataset " "or audio file and saves them into the 'features' folder of " "the dataset or the specified single file.", ...
def features(file_struct, annot_beats=False, framesync=False): '''Feature-extraction for audio segmentation Arguments: file_struct -- msaf.io.FileStruct paths to the input files in the Segmentation dataset Returns: - X -- ndarray beat-synchronous feature matrix: ...
def gaussian_cost(X): '''Return the average log-likelihood of data under a standard normal ''' d, n = X.shape if n < 2: return 0 sigma = np.var(X, axis=1, ddof=1) cost = -0.5 * d * n * np.log(2. * np.pi) - 0.5 * (n - 1.) * np.sum(sigma) return cost
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. """ # Preprocess...
def processHierarchical(self): """Main process for hierarchical segmentation. Returns ------- est_idxs : list List containing estimated times for each layer in the hierarchy as np.arrays est_labels : list List containing estimated labels for ea...
def lognormalize(F, floor=0.1, min_db=-80): """Log-normalizes features such that each vector is between min_db to 0.""" assert min_db < 0 F = min_max_normalize(F, floor=floor) F = np.abs(min_db) * np.log10(F) # Normalize from min_db to 0 return F
def min_max_normalize(F, floor=0.001): """Normalizes features such that each vector is between floor to 1.""" F += -F.min() + floor F = F / F.max(axis=0) return F
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 ...
def get_time_frames(dur, anal): """Gets the time frames and puts them in a numpy array.""" n_frames = get_num_frames(dur, anal) return np.linspace(0, dur, num=n_frames)
def remove_empty_segments(times, labels): """Removes empty segments if needed.""" assert len(times) - 1 == len(labels) inters = times_to_intervals(times) new_inters = [] new_labels = [] for inter, label in zip(inters, labels): if inter[0] < inter[1]: new_inters.append(inter) ...
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. ...
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...
def process_segmentation_level(est_idxs, est_labels, N, frame_times, dur): """Processes a level of segmentation, and converts it into times. Parameters ---------- est_idxs: np.array Estimated boundaries in frame indeces. est_labels: np.array Estimated labels. N: int Numb...
def align_end_hierarchies(hier1, hier2, thres=0.5): """Align the end of the hierarchies such that they end at the same exact second as long they have the same duration within a certain threshold. Parameters ---------- hier1: list List containing hierarchical segment boundaries. hier2: l...
def _distance(self, idx): """ compute distances of a specific data point to all other samples""" if scipy.sparse.issparse(self.data): step = self.data.shape[1] else: step = 50000 d = np.zeros((self.data.shape[1])) if idx == -1: # set vec to o...
def update_w(self): """ compute new W """ EPS = 10**-8 self.init_sivm() # initialize some of the recursively updated distance measures .... d_square = np.zeros((self.data.shape[1])) d_sum = np.zeros((self.data.shape[1])) d_i_times_d_j = np.zeros((self.data.shape[...
def estimate_K_xmeans(self, th=0.2, maxK = 10): """Estimates K running X-means algorithm (Pelleg & Moore, 2000).""" # Run initial K-means means, labels = self.run_kmeans(self.X, self.init_K) # Run X-means algorithm stop = False curr_K = self.init_K while not sto...
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(...
def get_clustered_data(self, X, labels, label_index): """Returns the data with a specific label_index, using the previously learned labels.""" D = X[np.argwhere(labels == label_index)] return D.reshape((D.shape[0], D.shape[-1]))
def run_kmeans(self, X, K): """Runs k-means and returns the labels assigned to the data.""" wX = vq.whiten(X) means, dist = vq.kmeans(wX, K, iter=100) labels, dist = vq.vq(wX, means) return means, labels
def compute_bic(self, D, means, labels, K, R): """Computes the Bayesian Information Criterion.""" D = vq.whiten(D) Rn = D.shape[0] M = D.shape[1] if R == K: return 1 # Maximum likelihood estimate (MLE) mle_var = 0 for k in range(len(means)): ...
def generate_2d_data(self, N=100, K=5): """Generates N*K 2D data points with K means and N data points for each mean.""" # Seed the random np.random.seed(seed=int(time.time())) # Amount of spread of the centroids spread = 30 # Generate random data X ...
def factorize(self): """Do factorization s.t. data = dot(dot(data,beta),H), under the convexity constraint beta >=0, sum(beta)=1, H >=0, sum(H)=1 """ # compute new coefficients for reconstructing data points self.update_w() # for CHNMF it is sometimes useful to only ...
def resample_mx(X, incolpos, outcolpos): """ Y = resample_mx(X, incolpos, outcolpos) X is taken as a set of columns, each starting at 'time' colpos, and continuing until the start of the next column. Y is a similar matrix, with time boundaries defined by outcolpos. Each column of Y is a duratio...
def magnitude(X): """Magnitude of a complex matrix.""" r = np.real(X) i = np.imag(X) return np.sqrt(r * r + i * i);
def json_to_bounds(segments_json): """Extracts the boundaries from a json file and puts them into an np array.""" f = open(segments_json) segments = json.load(f)["segments"] bounds = [] for segment in segments: bounds.append(segment["start"]) bounds.append(bounds[-1] + segments[-...
def json_bounds_to_bounds(bounds_json): """Extracts the boundaries from a bounds json file and puts them into an np array.""" f = open(bounds_json) segments = json.load(f)["bounds"] bounds = [] for segment in segments: bounds.append(segment["start"]) f.close() return np.asarr...
def json_to_labels(segments_json): """Extracts the labels from a json file and puts them into an np array.""" f = open(segments_json) segments = json.load(f)["segments"] labels = [] str_labels = [] for segment in segments: if not segment["label"] in str_labels: str_la...
def json_to_beats(beats_json_file): """Extracts the beats from the beats_json_file and puts them into an np array.""" f = open(beats_json_file, "r") beats_json = json.load(f) beats = [] for beat in beats_json["beats"]: beats.append(beat["start"]) f.close() return np.asarray(b...
def compute_ffmc2d(X): """Computes the 2D-Fourier Magnitude Coefficients.""" # 2d-fft fft2 = scipy.fftpack.fft2(X) # Magnitude fft2m = magnitude(fft2) # FFTshift and flatten fftshift = scipy.fftpack.fftshift(fft2m).flatten() #cmap = plt.cm.get_cmap('hot') #plt.imshow(np.log1p(scip...
def frobenius_norm(self): """ Frobenius norm (||data - USV||) for a data matrix and a low rank approximation given by SVH using rank k for U and V Returns: frobenius norm: F = ||data - USV|| """ if scipy.sparse.issparse(self.data): err = self....
def factorize(self, niter=10, compute_w=True, compute_h=True, compute_err=True, show_progress=False): """ Factorize s.t. WH = data Parameters ---------- niter : int number of iterations. show_progress : bool ...
def cnmf(S, rank, niter=500, hull=False): """(Convex) Non-Negative Matrix Factorization. Parameters ---------- S: np.array(p, N) Features matrix. p row features and N column observations. rank: int Rank of decomposition niter: int Number of iterations to be used Ret...
def compute_labels(X, rank, R, bound_idxs, niter=300): """Computes the labels using the bounds.""" try: F, G = cnmf(X, rank, niter=niter, hull=False) except: return [1] label_frames = filter_activation_matrix(G.T, R) label_frames = np.asarray(label_frames, dtype=int) #labels =...
def filter_activation_matrix(G, R): """Filters the activation matrix G, and returns a flattened copy.""" #import pylab as plt #plt.imshow(G, interpolation="nearest", aspect="auto") #plt.show() idx = np.argmax(G, axis=1) max_idx = np.arange(G.shape[0]) max_idx = (max_idx, idx.flatten()) ...
def get_segmentation(X, rank, R, rank_labels, R_labels, niter=300, bound_idxs=None, in_labels=None): """ Gets the segmentation (boundaries and labels) from the factorization matrices. Parameters ---------- X: np.array() Features matrix (e.g. chromagram) rank: in...
def processFlat(self): """Main process. Returns ------- est_idxs : np.array(N) Estimated indeces for the segment boundaries in frames. est_labels : np.array(N-1) Estimated labels for the segments. """ # C-NMF params niter = self.con...
def get_boundaries_module(boundaries_id): """Obtains the boundaries module given a boundary algorithm identificator. Parameters ---------- boundaries_id: str Boundary algorithm identificator (e.g., foote, sf). Returns ------- module: object Object containing the selected bo...
def get_labels_module(labels_id): """Obtains the label module given a label algorithm identificator. Parameters ---------- labels_id: str Label algorithm identificator (e.g., fmc2d, cnmf). Returns ------- module: object Object containing the selected label module. N...
def run_hierarchical(audio_file, bounds_module, labels_module, frame_times, config, annotator_id=0): """Runs hierarchical algorithms with the specified identifiers on the audio_file. See run_algorithm for more information. """ # Sanity check if bounds_module is None: rai...
def run_flat(file_struct, bounds_module, labels_module, frame_times, config, annotator_id): """Runs the flat algorithms with the specified identifiers on the audio_file. See run_algorithm for more information. """ # Get features to make code nicer features = config["features"].features ...
def run_algorithms(file_struct, boundaries_id, labels_id, config, annotator_id=0): """Runs the algorithms with the specified identifiers on the audio_file. Parameters ---------- file_struct: `msaf.io.FileStruct` Object with the file paths. boundaries_id: str Ident...
def process_track(file_struct, boundaries_id, labels_id, config, annotator_id=0): """Prepares the parameters, runs the algorithms, and saves results. Parameters ---------- file_struct: `msaf.io.FileStruct` FileStruct containing the paths of the input files (audio file, ...
def process(in_path, annot_beats=False, feature="pcp", framesync=False, boundaries_id=msaf.config.default_bound_id, labels_id=msaf.config.default_label_id, hier=False, sonify_bounds=False, plot=False, n_jobs=4, annotator_id=0, config=None, out_bounds="out_bounds.wav", out...
def update_w(self): """ alternating least squares step, update W under the convexity constraint """ def update_single_w(i): """ compute single W[:,i] """ # optimize beta using qp solver from cvxopt FB = base.matrix(np.float64(np.dot(-self.data.T, W_hat[:,i...
def main(): ''' Main Entry point for translator and argument parser ''' args = command_line() translate = partial(translator, args.source, args.dest, version=' '.join([__version__, __build__])) return source(spool(set_task(translate, translit=args.translit)), args.t...
def coroutine(func): """ Initializes coroutine essentially priming it to the yield statement. Used as a decorator over functions that generate coroutines. .. code-block:: python # Basic coroutine producer/consumer pattern from translate import coroutine @coroutine def ...
def accumulator(init, update): """ Generic accumulator function. .. code-block:: python # Simplest Form >>> a = 'this' + ' ' >>> b = 'that' >>> c = functools.reduce(accumulator, a, b) >>> c 'this that' # The type of the initial value determines outp...
def write_stream(script, output='trans'): """ :param script: Translated Text :type script: Iterable :param output: Output Type (either 'trans' or 'translit') :type output: String """ first = operator.itemgetter(0) sentence, _ = script printer = partial(print, file=sys.stdout, en...
def set_task(translator, translit=False): """ Task Setter Coroutine End point destination coroutine of a purely consumer type. Delegates Text IO to the `write_stream` function. :param translation_function: Translator :type translation_function: Function :param translit: Transliteration Sw...
def spool(iterable, maxlen=1250): """ Consumes text streams and spools them together for more io efficient processes. :param iterable: Sends text stream for further processing :type iterable: Coroutine :param maxlen: Maximum query string size :type maxlen: Integer """ words = int()...
def source(target, inputstream=sys.stdin): """ Coroutine starting point. Produces text stream and forwards to consumers :param target: Target coroutine consumer :type target: Coroutine :param inputstream: Input Source :type inputstream: BufferedTextIO Object """ for line in inputstream...
def push_url(interface): ''' Decorates a function returning the url of translation API. Creates and maintains HTTP connection state Returns a dict response object from the server containing the translated text and metadata of the request body :param interface: Callable Request Interface :t...
def translator(source, target, phrase, version='0.0 test', charset='utf-8'): """ Returns the url encoded string that will be pushed to the translation server for parsing. List of acceptable language codes for source and target languages can be found as a JSON file in the etc directory. Some so...
def translation_table(language, filepath='supported_translations.json'): ''' Opens up file located under the etc directory containing language codes and prints them out. :param file: Path to location of json file :type file: str :return: language codes :rtype: dict ''' fullpath = a...
def print_table(language): ''' Generates a formatted table of language codes ''' table = translation_table(language) for code, name in sorted(table.items(), key=operator.itemgetter(0)): print(u'{language:<8} {name:\u3000<20}'.format( name=name, language=code )) retu...
def remove_nodes(network, rm_nodes): """ Create DataFrames of nodes and edges that do not include specified nodes. Parameters ---------- network : pandana.Network rm_nodes : array_like A list, array, Index, or Series of node IDs that should *not* be saved as part of the Network....
def network_to_pandas_hdf5(network, filename, rm_nodes=None): """ Save a Network's data to a Pandas HDFStore. Parameters ---------- network : pandana.Network filename : str rm_nodes : array_like A list, array, Index, or Series of node IDs that should *not* be saved as part o...
def network_from_pandas_hdf5(cls, filename): """ Build a Network from data in a Pandas HDFStore. Parameters ---------- cls : class Class to instantiate, usually pandana.Network. filename : str Returns ------- network : pandana.Network """ with pd.HDFStore(filename)...
def bbox(self): """ The bounding box for nodes in this network [xmin, ymin, xmax, ymax] """ return [self.nodes_df.x.min(), self.nodes_df.y.min(), self.nodes_df.x.max(), self.nodes_df.y.max()]
def set(self, node_ids, variable=None, name="tmp"): """ Characterize urban space with a variable that is related to nodes in the network. Parameters ---------- node_ids : Pandas Series, int A series of node_ids which are usually computed using get...
def aggregate(self, distance, type="sum", decay="linear", imp_name=None, name="tmp"): """ Aggregate information for every source node in the network - this is really the main purpose of this library. This allows you to touch the data specified by calling set and perfor...
def get_node_ids(self, x_col, y_col, mapping_distance=None): """ Assign node_ids to data specified by x_col and y_col Parameters ---------- x_col : Pandas series (float) A Pandas Series where values specify the x (e.g. longitude) location of dataset. ...
def plot( self, data, bbox=None, plot_type='scatter', fig_kwargs=None, bmap_kwargs=None, plot_kwargs=None, cbar_kwargs=None): """ Plot an array of data on a map using matplotlib and Basemap, automatically matching the data to the Pandana network node positions...
def set_pois(self, category, maxdist, maxitems, x_col, y_col): """ Set the location of all the pois of this category. The pois are connected to the closest node in the Pandana network which assumes no impedance between the location of the variable and the location of the closest ...
def nearest_pois(self, distance, category, num_pois=1, max_distance=None, imp_name=None, include_poi_ids=False): """ Find the distance to the nearest pois from each source node. The bigger values in this case mean less accessibility. Parameters ---------- ...
def low_connectivity_nodes(self, impedance, count, imp_name=None): """ Identify nodes that are connected to fewer than some threshold of other nodes within a given distance. Parameters ---------- impedance : float Distance within which to search for other con...
def pdna_network_from_bbox( lat_min=None, lng_min=None, lat_max=None, lng_max=None, bbox=None, network_type='walk', two_way=True, timeout=180, memory=None, max_query_area_size=50 * 1000 * 50 * 1000): """ Make a Pandana network from a bounding lat/lon box request to the Overpass API. ...
def process_node(e): """ Process a node element entry into a dict suitable for going into a Pandas DataFrame. Parameters ---------- e : dict Returns ------- node : dict """ uninteresting_tags = { 'source', 'source_ref', 'source:ref', 'history...
def make_osm_query(query): """ Make a request to OSM and return the parsed JSON. Parameters ---------- query : str A string in the Overpass QL format. Returns ------- data : dict """ osm_url = 'http://www.overpass-api.de/api/interpreter' req = requests.get(osm_url,...
def build_node_query(lat_min, lng_min, lat_max, lng_max, tags=None): """ Build the string for a node-based OSM query. Parameters ---------- lat_min, lng_min, lat_max, lng_max : float tags : str or list of str, optional Node tags that will be used to filter the search. See http:/...
def node_query(lat_min, lng_min, lat_max, lng_max, tags=None): """ Search for OSM nodes within a bounding box that match given tags. Parameters ---------- lat_min, lng_min, lat_max, lng_max : float tags : str or list of str, optional Node tags that will be used to filter the search. ...
def equal(x, y): """ Shortcut function for ``unittest.TestCase.assertEqual()``. Arguments: x (mixed) y (mixed) Raises: AssertionError: in case of assertion error. Returns: bool """ if PY_3: return test_case().assertEqual(x, y) or True assert x ...
def matches(x, y, regex_expr=False): """ Tries to match a regular expression value ``x`` against ``y``. Aliast``unittest.TestCase.assertEqual()`` Arguments: x (regex|str): regular expression to test. y (str): value to match. regex_expr (bool): enables regex string based expressi...
def isregex_expr(expr): """ Returns ``True`` is the given expression value is a regular expression like string with prefix ``re/`` and suffix ``/``, otherwise ``False``. Arguments: expr (mixed): expression value to test. Returns: bool """ if not isinstance(expr, str): ...
def isregex(value): """ Returns ``True`` if the input argument object is a native regular expression object, otherwise ``False``. Arguments: value (mixed): input value to test. Returns: bool """ if not value: return False return any((isregex_expr(value), isinsta...
def compare(self, value, expectation, regex_expr=False): """ Compares two values with regular expression matching support. Arguments: value (mixed): value to compare. expectation (mixed): value to match. regex_expr (bool, optional): enables string based regex...
def fluent(fn): """ Simple function decorator allowing easy method chaining. Arguments: fn (function): target function to decorate. """ @functools.wraps(fn) def wrapper(self, *args, **kw): # Trigger method proxy result = fn(self, *args, **kw) # Return self instan...