Exemplo n.º 1
0
def mutate(genotype, num_rows, num_cols, arr, constraints, mut_rate=0.15):
    segments = find_segments(genotype)
    r = random()
    if r < 0.45 and max(segments) >= constraints[0]:
        v_from, v_to = merge_2_similar_segments(arr, segments, num_rows,
                                                num_cols)
        seg_1, seg_2 = segments[v_from], segments[v_to]

        if seg_1 != seg_2:
            # Set all seg 2 pixels to seg 1
            segment_indices = np.flatnonzero(segments == seg_2)
            segments[segment_indices] = seg_1
            genotype = segment_mst(arr, segments, seg_1, np.array(genotype),
                                   num_rows, num_cols, 0)

    elif r < 0.9 and max(segments) < constraints[1]:
        start = time.time()
        if random() < 0.5:
            segment_id = get_worst_segment(arr, segments, num_rows, num_cols)
        else:
            segment_id = np.random.choice(segments)
        genotype = segment_mst(arr, segments, segment_id, np.array(genotype),
                               num_rows, num_cols, 1)

    else:
        rand_i = randint(0, len(genotype) - 1)
        mutate_random_edge(rand_i, num_rows, num_cols)

    return genotype
Exemplo n.º 2
0
    def __init__(self, arr, genotype=None):

        self.rows = arr.shape[0]
        self.cols = arr.shape[1]
        # Generate initial phenotype
        if genotype is None:
            self.genotype = mst(arr, self.rows, self.cols)
        else:
            self.genotype = genotype

        self.segments = find_segments(self.genotype)
        self.edge_value = edge_value(arr, self.segments, self.rows, self.cols)
        self.connectivity = connectivity(arr, self.segments, self.rows,
                                         self.cols)
        self.deviation = overall_deviation(arr, self.segments, self.cols)
        self.fitness = 10 * self.edge_value - 8500 * self.connectivity - 2 * self.deviation
Exemplo n.º 3
0
    def __init__(self, arr, genotype=None):

        self.rows = arr.shape[0]
        self.cols = arr.shape[1]
        # Generate initial phenotype
        if genotype is None:
            self.genotype = mst(arr, self.rows, self.cols)

        else:
            self.genotype = genotype

        self.segments = find_segments(self.genotype)
        self.num_segments = max(self.segments) + 1
        self.edge_value = -edge_value(arr, self.segments, self.rows,
                                      self.cols)  # negative to minimize
        self.connectivity = connectivity(arr, self.segments, self.rows,
                                         self.cols)
        self.deviation = overall_deviation(arr, self.segments, self.cols)
Exemplo n.º 4
0
def process(wav_file, outfile, csv_file=None, bpm=None, tol=0.35,
            ssm_read_pk=False, read_pk=False, rho=2, is_ismir=False,
            tonnetz=False, sonify=False):
    """Main process to find the patterns in a polyphonic audio file.

    Parameters
    ----------
    wav_file : str
        Path to the wav file to be analyzed.
    csv_file : str
        Path to the csv containing the midi_score of the input audio file
        (needed to produce a result that can be read for JKU dataset).
    outfile : str
        Path to file to save the results.
    bpm : int
        Beats per minute of the piece. If None, bpms are read from the JKU.
    tol : float
        Tolerance to find the segments in the SSM.
    ssm_read_pk : bool
        Whether to read the SSM from a pickle file.
    read_pk : bool
        Whether to read the segments from a pickle file.
    rho : int
        Positive integer to compute the score of the segments.
    is_ismir : bool
        Produce the plots that appear on the ISMIR paper.
    tonnetz : bool
        Whether to use Tonnetz or Chromas.
    sonify : bool
        Whether to sonify the patterns or not.
    """

    # Get the correct bpm if needed
    if bpm is None:
        bpm = get_bpm(wav_file)

    # Algorithm parameters
    min_notes = 8
    max_diff_notes = 4
    h = bpm / 60. / 8.  # Hop size /8 works better than /4, but it takes longer
                        # to process

    # Obtain the Self Similarity Matrix
    X = compute_ssm(wav_file, h, ssm_read_pk, is_ismir, tonnetz)

    # Read CSV file
    if csv_file is not None:
        logging.info("Reading the CSV file for MIDI pitches...")
        midi_score = utils.read_csv(csv_file)

    patterns = []
    csv_patterns = []
    while patterns == [] or csv_patterns == []:
        # Find the segments inside the self similarity matrix
        logging.info("Finding segments in the self-similarity matrix...")
        max_diff = int(max_diff_notes / float(h))
        min_dur = int(np.ceil(min_notes / float(h)))
        #print min_dur, min_notes, h, max_diff
        if not read_pk:
            segments = []
            while segments == []:
                logging.info("\ttrying tolerance %.2f" % tol)
                segments = utils.find_segments(X, min_dur, th=tol, rho=rho)
                tol -= 0.05
            utils.write_cPickle(wav_file + "-audio.pk", segments)
        else:
            segments = utils.read_cPickle(wav_file + "-audio.pk")

        # Obtain the patterns from the segments and split them if needed
        logging.info("Obtaining the patterns from the segments...")
        patterns = obtain_patterns(segments, max_diff)

        # Decrease tolerance in case we couldn't find any patterns
        tol -= 0.05

        # Get the csv patterns if they exist
        if csv_file is not None:
            csv_patterns = patterns_to_csv(patterns, midi_score, h)
        else:
            csv_patterns = [0]

    # Sonify patterns if needed
    if sonify:
        logging.info("Sonifying Patterns...")

        utils.sonify_patterns(wav_file, patterns, h)

    # Formatting csv patterns and save results
    if csv_file is not None:
        logging.info("Writting results into %s" % outfile)
        utils.save_results(csv_patterns, outfile=outfile)
    else:
        # If not csv, just print the results on the screen
        print_patterns(patterns, h)

    if is_ismir:
        ismir.plot_segments(X, segments)

    # Alright, we're done :D
    logging.info("Algorithm finished.")