def frequency_distribution(blockades_file, detailed):
    """
    Plots the frequency distribution
    """
    blockades = read_mat(blockades_file)
    blockades = sp._fractional_blockades(blockades)
    blockades = sp._filter_by_duration(blockades, 0.5, 20)

    peaks_count = {}
    for blockade in blockades:
        if detailed:
            detailed_plots(blockade)

        signal = blockade.eventTrace[1000:-1000]
        xx, yy = sp.find_peaks(signal)
        peaks_count[blockade] = len(xx) / blockade.ms_Dwell * 5 / 4

    mean = np.mean(peaks_count.values())
    errors = map(lambda e: peaks_count[e] - mean, blockades)
    lengths = map(lambda e: e.ms_Dwell, blockades)

    f, (s1, s2) = plt.subplots(2)
    s1.scatter(lengths, errors)
    s2.hist(peaks_count.values(), bins=100)
    plt.show()
def frequency_distribution(blockades_file, detailed):
    """
    Plots the frequency distribution
    """
    blockades = read_mat(blockades_file)
    blockades = sp._fractional_blockades(blockades)
    blockades = sp._filter_by_duration(blockades, 0.5, 20)

    peaks_count = {}
    for blockade in blockades:
        if detailed:
            detailed_plots(blockade)

        signal = blockade.eventTrace[1000:-1000]
        xx, yy = sp.find_peaks(signal)
        peaks_count[blockade] = len(xx) / blockade.ms_Dwell * 5 / 4

    mean = np.mean(peaks_count.values())
    errors = map(lambda e: peaks_count[e] - mean, blockades)
    lengths = map(lambda e: e.ms_Dwell, blockades)

    f, (s1, s2) = plt.subplots(2)
    s1.scatter(lengths, errors)
    s2.hist(peaks_count.values(), bins=100)
    plt.show()
def detailed_plots(blockade):
    """
    Plots extra information about a single blockade
    """
    #FFT
    fft = fftpack.rfft(blockade.eventTrace)

    #Getting mean distance between peaks
    xx, yy = sp.find_peaks(blockade.eventTrace)
    diff_1 = sorted(np.array(xx)[1:] - np.array(xx)[:-1])
    diff_2 = sorted(np.array(xx)[2:] - np.array(xx)[:-2])
    diff_3 = sorted(np.array(xx)[3:] - np.array(xx)[:-3])
    diff = diff_1 + diff_2 + diff_3
    diff = np.array(diff) * blockade.ms_Dwell
    d_hist, bin_edges = np.histogram(diff, bins=100, range=(100, 1000))

    window = signal.gaussian(21, std=1)
    smooth_diff = np.convolve(d_hist, window, mode="same")
    smooth_diff = savitsky_golay(smooth_diff, 5, 3)

    #Guessing gcds of peak distance distributino
    hist_x, hist_y = sp.find_peaks(smooth_diff)
    char_peaks = map(lambda x: int(bin_edges[x + 1]), hist_x)
    gcd_plot, gcds = gcd_fuzz(char_peaks)

    f, (s1, s2, s3, s4) = plt.subplots(4)
    s1.plot(blockade.eventTrace)
    s1.scatter(xx, yy)
    s1.set_xlim(0, 10000)
    s1.set_ylabel("Blockade")

    s2.plot(np.linspace(0, 1000 / blockade.ms_Dwell, 1000),
            savitsky_golay(fft ** 2, 31, 3)[:1000])
    s2.set_yscale("log")
    s2.set_ylabel("FFT")

    s3.plot(bin_edges[1:], smooth_diff)
    s3.set_ylabel("Peak dist. distr.")

    s4.plot(gcd_plot)
    s4.set_ylabel("Peak dist. gcd")

    plt.show()
def detailed_plots(blockade):
    """
    Plots extra information about a single blockade
    """
    #FFT
    fft = fftpack.rfft(blockade.eventTrace)

    #Getting mean distance between peaks
    xx, yy = sp.find_peaks(blockade.eventTrace)
    diff_1 = sorted(np.array(xx)[1:] - np.array(xx)[:-1])
    diff_2 = sorted(np.array(xx)[2:] - np.array(xx)[:-2])
    diff_3 = sorted(np.array(xx)[3:] - np.array(xx)[:-3])
    diff = diff_1 + diff_2 + diff_3
    diff = np.array(diff) * blockade.ms_Dwell
    d_hist, bin_edges = np.histogram(diff, bins=100, range=(100, 1000))

    window = signal.gaussian(21, std=1)
    smooth_diff = np.convolve(d_hist, window, mode="same")
    smooth_diff = savitsky_golay(smooth_diff, 5, 3)

    #Guessing gcds of peak distance distributino
    hist_x, hist_y = sp.find_peaks(smooth_diff)
    char_peaks = map(lambda x: int(bin_edges[x + 1]), hist_x)
    gcd_plot, gcds = gcd_fuzz(char_peaks)

    f, (s1, s2, s3, s4) = plt.subplots(4)
    s1.plot(blockade.eventTrace)
    s1.scatter(xx, yy)
    s1.set_xlim(0, 10000)
    s1.set_ylabel("Blockade")

    s2.plot(np.linspace(0, 1000 / blockade.ms_Dwell, 1000),
            savitsky_golay(fft**2, 31, 3)[:1000])
    s2.set_yscale("log")
    s2.set_ylabel("FFT")

    s3.plot(bin_edges[1:], smooth_diff)
    s3.set_ylabel("Peak dist. distr.")

    s4.plot(gcd_plot)
    s4.set_ylabel("Peak dist. gcd")

    plt.show()
def frequency_plot(blockade_files):
    """
    Draws the plot
    """
    datasets_names = []
    frequencies = []
    for file in blockade_files:
        blockades = read_mat(file)
        blockades = sp._fractional_blockades(blockades)
        blockades = sp._filter_by_duration(blockades, 0.5, 20)

        dataset_freqs = []
        for blockade in blockades:
            xx, yy = sp.find_peaks(blockade.eventTrace[1000:-1000])
            dataset_freqs.append(len(xx) / blockade.ms_Dwell * 5 / 4)

        frequencies.append(dataset_freqs)
        datasets_names.append(os.path.basename(file).split(".")[0])

    x_axis = np.arange(min(sum(frequencies, [])) - 10, max(sum(frequencies, [])) + 10, 0.1)
    matplotlib.rcParams.update({"font.size": 16})
    fig = plt.subplot()

    colors = ["blue", "green", "red", "cyan"]
    for distr, name, color in zip(frequencies, datasets_names, colors):
        density = gaussian_kde(distr)
        density.covariance_factor = lambda: 0.25
        density._compute_covariance
        gauss_dens = density(x_axis)

        fig.spines["right"].set_visible(False)
        fig.spines["top"].set_visible(False)
        fig.get_xaxis().tick_bottom()
        fig.get_yaxis().tick_left()
        fig.set_ylim(0, 0.16)

        fig.plot(x_axis, gauss_dens, antialiased=True, linewidth=2, color=color, alpha=0.7, label=name)
        fig.fill_between(x_axis, gauss_dens, alpha=0.5, antialiased=True, color=color)

    fig.set_xlabel("Fluctuation frequency, 1/ms")
    legend = fig.legend(loc="upper left", frameon=False)
    for label in legend.get_lines():
        label.set_linewidth(3)
    for label in legend.get_texts():
        label.set_fontsize(16)
    plt.show()
def gcd_fuzz(numbers):
    """
    Computes "approximate" common divisor
    """
    vals = []
    for div in xrange(1, 300):
        rems = []
        for num in numbers:
            rem = min(num % div, (num // div + 1) * div - num)
            rems.append((float(rem)))

        vals.append(np.mean(rems) / div)

    gcd_x, gcd_y = sp.find_peaks(vals, minimum=True, ranged=True)
    gcds = filter(lambda x: 40 < x < 500, gcd_x)

    return vals, gcds
def gcd_fuzz(numbers):
    """
    Computes "approximate" common divisor
    """
    vals = []
    for div in xrange(1, 300):
        rems = []
        for num in numbers:
            rem = min(num % div, (num // div + 1) * div - num)
            rems.append((float(rem)))

        vals.append(np.mean(rems) / div)

    gcd_x, gcd_y = sp.find_peaks(vals, minimum=True, ranged=True)
    gcds = filter(lambda x: 40 < x < 500, gcd_x)

    return vals, gcds