Exemple #1
0
def example_filterbank():
    from pylab import plt
    import numpy as np

    x = _create_impulse(2000)
    gfb = GammatoneFilterbank(density=1)

    analyse = gfb.analyze(x)
    imax, slopes = gfb.estimate_max_indices_and_slopes()
    fig, axs = plt.subplots(len(gfb.centerfrequencies), 1)
    for (band, state), imx, ax in zip(analyse, imax, axs):
        ax.plot(np.real(band))
        ax.plot(np.imag(band))
        ax.plot(np.abs(band))
        ax.plot(imx, 0, 'o')
        ax.set_yticklabels([])
        [ax.set_xticklabels([]) for ax in axs[:-1]]

    axs[0].set_title('Impulse responses of gammatone bands')

    fig, ax = plt.subplots()

    def plotfun(x, y):
        ax.semilogx(x, 20*np.log10(np.abs(y)**2))

    gfb.freqz(nfft=2*4096, plotfun=plotfun)
    plt.grid(True)
    plt.title('Absolute spectra of gammatone bands.')
    plt.xlabel('Normalized Frequency (log)')
    plt.ylabel('Attenuation /dB(FS)')
    plt.axis('Tight')
    plt.ylim([-90, 1])
    plt.show()

    return gfb
Exemple #2
0
def example_filterbank():
    from pylab import plt
    import numpy as np

    x = _create_impulse(2000)
    gfb = GammatoneFilterbank(density=1)

    analyse = gfb.analyze(x)
    imax, slopes = gfb.estimate_max_indices_and_slopes()
    fig, axs = plt.subplots(len(gfb.centerfrequencies), 1)
    for (band, state), imx, ax in zip(analyse, imax, axs):
        ax.plot(np.real(band))
        ax.plot(np.imag(band))
        ax.plot(np.abs(band))
        ax.plot(imx, 0, 'o')
        ax.set_yticklabels([])
        [ax.set_xticklabels([]) for ax in axs[:-1]]

    axs[0].set_title('Impulse responses of gammatone bands')

    fig, ax = plt.subplots()

    def plotfun(x, y):
        ax.semilogx(x, 20 * np.log10(np.abs(y)**2))

    gfb.freqz(nfft=2 * 4096, plotfun=plotfun)
    plt.grid(True)
    plt.title('Absolute spectra of gammatone bands.')
    plt.xlabel('Normalized Frequency (log)')
    plt.ylabel('Attenuation /dB(FS)')
    plt.axis('Tight')
    plt.ylim([-90, 1])
    plt.show()

    return gfb
Exemple #3
0
def stochastic_volatility():
    S0 = 100.
    r = 0.05
    v0 = 0.1
    kappa = 3.0
    theta = 0.25
    sigma = 0.1
    rho = 0.6
    T = 1.0

    corr_mat = np.zeros((2, 2))
    corr_mat[0, :] = [1.0, rho]
    corr_mat[1, :] = [rho, 1.0]
    cho_mat = np.linalg.cholesky(corr_mat)

    M = 50
    I = 10000
    dt = T / M

    ran_num = npr.standard_normal((2, M + 1, I))
    v = np.zeros_like(ran_num[0])
    vh = np.zeros_like(v)
    v[0] = v0
    vh[0] = v0

    for t in range(1, M + 1):
        ran = np.dot(cho_mat, ran_num[:, t, :])
        vh[t] = (
            vh[t - 1] + kappa * (theta - np.maximum(vh[t - 1], 0)) * dt +
            sigma * np.sqrt(np.maximum(vh[t - 1], 0)) * math.sqrt(dt) * ran[1])

    v = np.maximum(vh, 0)
    S = np.zeros_like(ran_num[0])
    S[0] = S0
    for t in range(1, M + 1):
        ran = np.dot(cho_mat, ran_num[:, t, :])
        S[t] = S[t - 1] * np.exp((r - 0.5 * v[t]) * dt +
                                 np.sqrt(v[t]) * ran[0] * np.sqrt(dt))

    ig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 6))
    ax1.hist(S[-1], bins=50)
    ax1.set_xlabel('index level')
    ax1.set_ylabel('frequency')
    ax2.hist(v[-1], bins=50)
    ax2.set_xlabel('volatility')
    plt.show()

    fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(10, 6))
    ax1.plot(S[:, :100], lw=1)
    ax1.set_ylabel('index level')
    ax2.plot(v[:, :100], lw=1)
    ax2.set_xlabel('time')
    ax2.set_ylabel('volatility')
    plt.show()
Exemple #4
0
def main(data_folder="../data", figure_folder="../figures"):

    deviation_from_equilibrium = dict()
    for i in [(1, 0), (2, 0), (2, 1)]:

        deviation_from_equilibrium[i] = \
            json.load(open("{}/deviation_from_equilibrium_{}.json".format(data_folder, i), mode="r"))

    x = np.arange(len(list(deviation_from_equilibrium.values())[0]))

    fig, ax = plt.subplots()

    for i in deviation_from_equilibrium.keys():
        ax.plot(x,
                deviation_from_equilibrium[i],
                label='{} against {}'.format(i[0], i[1]))

    ax.legend(fontsize=12)  # loc='upper center
    ax.set_xlabel("generation")
    ax.set_ylabel("actual price / equilibrium price")

    ax.set_title(
        "Price Dynamics in Scarf Three-good Economy \n(relative deviation from equilibrium prices)"
    )

    if not path.exists(figure_folder):
        mkdir(figure_folder)
    plt.savefig("{}/figure.pdf".format(figure_folder))

    plt.show()
Exemple #5
0
def main():
    msft = yf.Ticker("MSFT")
    euro_security_process, euro_trials, euro_price_mean = european_monte_carlo_valuation(
        trials=10000,
        partitions=50,
        time=1.0,
        S0=msft.info.get("previousClose"),
        r=0.05,
        sigma=0.64,
        strike=210,
        option='call')

    simulated_returns_data = pd.DataFrame(euro_security_process[:, :200])
    simulated_returns = np.log(
        1 + simulated_returns_data.astype(float).pct_change())

    actual_returns_data = msft.history(period="1y")['Close']
    actual_returns_data = np.log(
        1 + actual_returns_data.astype(float).pct_change())

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 12))
    ax1.hist(simulated_returns.values.flatten(), bins=50)
    ax1.set_xlabel('Theoretical Returns')
    ax1.set_ylabel('Frequency')
    ax2.hist(actual_returns_data, bins=50)
    ax2.set_xlabel('Observed Returns')
    ax2.set_ylabel('Frequency')
    plt.show()
    def remove_extreme_value(self, df_input):
        if self.is_plot:
            del df_input["date"]
            del df_input["flag"]

            fig, (ax0, ax1) = plt.subplots(2, 1, sharey="all")
            ax0.set_title('BEFORE /20130201/non_ts.csv remove extreme value')
            df_input.plot(ax=ax0)

            desc = df_input.describe()
            mean_add_3std = desc.loc['mean'] + desc.loc['std'] * 3
            mean_minus_3std = desc.loc['mean'] - desc.loc['std'] * 3
            df_input = df_input.where(df_input < mean_add_3std, mean_add_3std, axis=1)
            df_input = df_input.where(df_input > mean_minus_3std, mean_minus_3std, axis=1)

            ax1.set_title('AFTER /20130201/non_ts.csv remove extreme value')
            df_input.plot(ax=ax1)
            plt.show()
        else:
            desc = df_input.describe()
            mean_add_3std = desc.loc['mean'] + desc.loc['std'] * 3
            mean_minus_3std = desc.loc['mean'] - desc.loc['std'] * 3
            df_input = df_input.where(df_input < mean_add_3std, mean_add_3std, axis=1)
            df_input = df_input.where(df_input > mean_minus_3std, mean_minus_3std, axis=1)

        return df_input
    def plot(cls, data, figure_folder, msg="", suffix=""):

        fig, ax = plt.subplots()

        plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.2)

        x = np.arange(len(data[:]))

        ax.plot(x, data[:, 0], c="red", linewidth=2, label="agent 01")
        ax.plot(x, data[:, 1], c="blue", linewidth=2, label="agent 12")
        ax.plot(x, data[:, 2], c="green", linewidth=2, label="agent 20")

        plt.ylim([-0.01, 1.01])

        plt.text(0, -0.23, "PARAMETERS. {}".format(msg))

        ax.legend(fontsize=12,
                  bbox_to_anchor=(1.1, 1.05))  # loc='upper center'
        ax.set_xlabel("$t$")
        ax.set_ylabel("Proportion of agents proceeding to indirect exchange")

        ax.set_title("Money emergence with a basal ganglia model")

        # Save fig
        if not exists(figure_folder):
            mkdir(figure_folder)
        fig_name = "{}/figure_{}.pdf".format(figure_folder,
                                             suffix.split(".p")[0])
        plt.savefig(fig_name)
        plt.close()
Exemple #8
0
def plot_weightings():
    """Plots all weighting functions defined in :module: splweighting."""
    from scipy.signal import freqz
    from pylab import plt, np

    sample_rate = 48000
    num_samples = 2 * 4096

    fig, ax = plt.subplots()

    for name, weight_design in sorted(_weighting_coeff_design_funsd.items()):
        b, a = weight_design(sample_rate)
        w, H = freqz(b, a, worN=num_samples)

        freq = w * sample_rate / (2 * np.pi)

        ax.semilogx(freq,
                    20 * np.log10(np.abs(H) + 1e-20),
                    label='{}-Weighting'.format(name))

    plt.legend(loc='lower right')
    plt.xlabel('Frequency / Hz')
    plt.ylabel('Damping / dB')
    plt.grid(True)
    plt.axis([10, 20000, -80, 5])
    return fig, ax
Exemple #9
0
def draw_plot(company_name, hyper_parameter, plot_data):

    point_list = ['C0o-', 'C1o-', 'C2o-', 'C3o-', 'C4o-', 'C5o-']
    x = np.arange(len(plot_data[0][1]))
    x_label = np.zeros(len(plot_data[0][1]))
    for i, val in enumerate(plot_data[0][1]):
        x_label[i] = val[0]

    fig, ax = plt.subplots(1, 1)
    for j, model in enumerate(plot_data):
        model_name = model[0]
        y = np.zeros(len(model[1]))
        for i, val in enumerate(model[1]):
            y[i] = val[1]

        ax.plot(x, y, point_list[j], label=model_name)

    ax.set_title(company_name + "'s MSE results w/ " + hyper_parameter,
                 fontdict={
                     'fontsize': 18,
                     'weight': 'bold'
                 })
    ax.set_ylabel('MSE', fontdict={'fontsize': 15, 'weight': 'bold'})
    ax.set_xlabel(hyper_parameter, fontdict={'fontsize': 15, 'weight': 'bold'})
    ax.set_xticks(x)
    ax.set_xticklabels(x_label)
    ax.legend()

    dir_path = 'MSE_figures\\' + company_name
    os.system('mkdir ' + dir_path)
    plt.savefig(dir_path + '\\' + company_name + '_' + hyper_parameter +
                '.png')
    def plot(cls, data, figure_folder, msg="", suffix=""):

        fig, ax = plt.subplots()

        plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.2)

        x = np.arange(len(data[:]))

        ax.plot(x, data[:, 0], c="red", linewidth=2, label="agent 01")
        ax.plot(x, data[:, 1], c="blue", linewidth=2, label="agent 12")
        ax.plot(x, data[:, 2], c="green", linewidth=2, label="agent 20")

        plt.ylim([-0.01, 1.01])

        plt.text(0, -0.23, "PARAMETERS. {}".format(msg))

        ax.legend(fontsize=12, bbox_to_anchor=(1.1, 1.05))  # loc='upper center'
        ax.set_xlabel("$t$")
        ax.set_ylabel("Proportion of agents proceeding to indirect exchange")

        ax.set_title("Money emergence with a basal ganglia model")

        # Save fig
        if not exists(figure_folder):
            mkdir(figure_folder)
        fig_name = "{}/figure_{}.pdf".format(figure_folder, suffix.split(".p")[0])
        plt.savefig(fig_name)
        plt.close()
Exemple #11
0
def ramd():
    sample_size = 500
    rn1 = npr.rand(sample_size, 3)
    rn2 = npr.randint(0, 10, sample_size)
    rn3 = npr.sample(size=sample_size)

    a = [0, 25, 50, 75, 100]

    rn4 = npr.choice(a, size=sample_size)

    fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2,
                                                 ncols=2,
                                                 figsize=(10, 8))

    ax1.hist(rn1, bins=25, stacked=True)
    ax1.set_title('rand')
    ax1.set_ylabel('frequency')

    ax2.hist(rn2, bins=25)
    ax2.set_title('randint')

    ax3.hist(rn3, bins=25)
    ax3.set_title('samople')
    ax3.set_ylabel("frequency")

    ax4.hist(rn4, bins=25)
    ax4.set_title('choice')
    plt.show()
def plot_weightings():
    """Plots all weighting functions defined in :module: splweighting."""
    from scipy.signal import freqz
    from pylab import plt, np

    sample_rate = 48000
    num_samples = 2*4096

    fig, ax = plt.subplots()

    for name, weight_design in sorted(
            _weighting_coeff_design_funsd.items()):
        b, a = weight_design(sample_rate)
        w, H = freqz(b, a, worN=num_samples)

        freq = w*sample_rate / (2*np.pi)

        ax.semilogx(freq, 20*np.log10(np.abs(H)+1e-20),
                    label='{}-Weighting'.format(name))

    plt.legend(loc='lower right')
    plt.xlabel('Frequency / Hz')
    plt.ylabel('Damping / dB')
    plt.grid(True)
    plt.axis([10, 20000, -80, 5])
    return fig, ax
Exemple #13
0
def plot_Mos_Mws(days, Mos=None, Mws=None, ylim = None, yticks=None):
    if Mos is None and Mws is None:
        raise ValueError('Set Mos or Mws.')
    if Mos is not None and Mws is not None:
        raise ValueError("Don't set both.")
    if Mws is not None:
        Mos = mw_to_mo(Mws)

    fig, ax1 = plt.subplots()
    ax1.plot(days, Mos,'-o')
    ax1.set_yscale('log')

    if yticks is not None:
        ax1.set_yticks(yticks)
    ax1.get_yaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())

    if ylim is not None:
        ax1.set_ylim(ylim)

    lim1 = ax1.get_ylim()

    ax1.set_xlabel('days after the mainshock')
    ax1.set_ylabel('Moment(Nm)')
    ax1.grid('on')

    ax2 = ax1.twinx()
    ax2.set_ylabel('Mw')
    ax2.set_ylim(mo_to_mw(lim1))
Exemple #14
0
def distribution():
    sample_size = 500
    rn1 = npr.standard_normal(sample_size)
    rn2 = npr.normal(100, 20, sample_size)
    rn3 = npr.chisquare(df=0.5, size=sample_size)
    rn4 = npr.poisson(lam=1.0, size=sample_size)

    fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2,
                                                 ncols=2,
                                                 figsize=(10, 8))

    ax1.hist(rn1, bins=25, stacked=True)
    ax1.set_title('Standard normal')
    ax1.set_ylabel('frequency')

    ax2.hist(rn2, bins=25)
    ax2.set_title('Normal 100,20')

    ax3.hist(rn3, bins=25)
    ax3.set_title('Chi squared')
    ax3.set_ylabel("frequency")

    ax4.hist(rn4, bins=25)
    ax4.set_title('Poisson')
    plt.show()
Exemple #15
0
def plot_example_graphs(graphs, rows=4, cols=4, figsize=(10, 10)):
    import matplotlib as mplt

    norm = mplt.colors.Normalize(0, 20)

    fig, axes = plt.subplots(rows, cols, squeeze=False, figsize=figsize)

    def flatten(x):
        arr = []
        for a in x:
            for b in a:
                arr.append(b)
        return arr

    axes = flatten(axes)
    for g, ax in zip(graphs, axes):
        if not g.number_of_nodes():
            continue
        ylabels = {n: ndata for n, ndata in g.nodes(data="y")}
        nodelist, nodedata = zip(*g.nodes(data=True))
        ylabels = {
            n: round(ndata["y"].flatten().item(), 2)
            for n, ndata in zip(nodelist, nodedata)
        }
        y = [round(ndata["y"].flatten().item(), 2) for ndata in nodedata]

        pos = GraphPlotter._topological_sort(g)
        nx.draw_networkx_labels(g, pos, labels=ylabels, ax=ax)
        nx.draw_networkx_nodes(g,
                               pos,
                               ax=ax,
                               node_color=mplt.cm.coolwarm(norm(y)))
        nx.draw_networkx_edges(g, pos, ax=ax)
    return fig, axes
Exemple #16
0
def phase_diagram(data,
                  labels,
                  n_good,
                  title=None,
                  ax=None,
                  letter=None,
                  n_ticks=3,
                  fig_name=None):

    if ax is None:
        print('No ax given, I will create a fig.')
        fig, ax = plt.subplots()

    im = ax.imshow(data, cmap="binary", origin="lower", vmin=0.2,
                   vmax=0.8)  # , vmin=0.5)

    # Create colorbar
    cbar = ax.figure.colorbar(im, ax=ax)

    step = int(len(labels) / n_ticks)
    lab_to_display = labels[::step]

    ax.set_xticklabels(lab_to_display)
    ax.set_yticklabels(lab_to_display)

    ticks = list(range(len(labels)))[::step]

    ax.set_xticks(ticks)
    ax.set_yticks(ticks)

    ax.tick_params(labelsize=8)

    ax.set_xlabel(f'$x_{n_good-2}$')
    ax.set_ylabel(f'$x_{n_good-1}$')

    ax.set_aspect(1)

    if title is not None:
        ax.set_title(title)

    if letter:
        ax.text(s=letter,
                x=-0.1,
                y=-0.2,
                horizontalalignment='center',
                verticalalignment='center',
                transform=ax.transAxes,
                fontsize=20)

    if 'fig' in locals():
        print('Saving fig.')
        # noinspection PyUnboundLocalVariable
        fig.tight_layout()

        if fig_name is None:
            fig_name = f'fig/phase_{n_good}.pdf'

        os.makedirs(os.path.dirname(fig_name), exist_ok=True)
        plt.savefig(fig_name)
Exemple #17
0
def get_axis(cNr):
    # fig, axes = plt.subplots(ncols=cNr[0], nrows=cNr[1], dpi=150, sharex=True);
    fig, axes = plt.subplots(ncols=cNr[0], nrows=cNr[1], sharex=True, figsize=(16*0.8, 9*0.8), dpi=80, facecolor='w', edgecolor='k');
    fig.subplots_adjust(right=0.95, bottom=0.1, top=0.95, hspace=0.2, wspace=0.02)    
    # fig.subplots_adjust(right=0.85, bottom=0.1, top=0.95, hspace=0.25)
    if sum(cNr)<=2:
        return axes
    else:
        return axes.ravel()
Exemple #18
0
    def __init__(self,
                 kernel,
                 xmin,
                 xmax,
                 ymin,
                 ymax,
                 base_accuracy,
                 max_iter,
                 interpolation='none',
                 splits=None,
                 *args):
        fig, ax = plt.subplots()

        self.base_accuracy = base_accuracy
        self.height = base_accuracy
        self.width = base_accuracy
        self.max_iter = max_iter
        self.kernel = kernel
        self.x = np.linspace(xmin, xmax, self.width)
        self.y = np.linspace(ymin, ymax, self.height)
        self.splits = splits
        self.args = args
        self.ax = ax
        self.fig = fig
        self.interpolation = interpolation
        self.image_array = None

        class ImageSaver(ToolBase):
            image_array = None
            description = 'Save the image only'

            def trigger(self, *args, **kwargs):
                path = filedialog.asksaveasfilename(initialfile='Fractal_1',
                                                    defaultextension='png',
                                                    filetypes=[('PNG', ".png")
                                                               ])

                if path:
                    image = Image.fromarray(self.image_array, mode='RGB')
                    image.save(path, "PNG", quality=95, optimize=False)

        tm = fig.canvas.manager.toolmanager
        self.image_saver = tm.add_tool("Save Image", ImageSaver)
        fig.canvas.manager.toolbar.add_tool(tm.get_tool("Save Image"),
                                            "toolgroup")

        self.slider_box = plt.axes([0.12, 0.02, 0.7, 0.03])
        self.slider = Slider(self.slider_box,
                             'Max iter:',
                             100,
                             50000,
                             valinit=max_iter,
                             valstep=10)
        self.slider.set_val(max_iter)
        self.slider.on_changed(self.on_slider_change)
        plt.subplots_adjust(bottom=0.1, top=0.95)
Exemple #19
0
def plotSigmoidTanh(fname=None):
    fig, ax = plt.subplots()
    xs = np.linspace(-10.0, 10.0, num = 50, endpoint=True)
    ys = [sigmoidTanh(x, 0.9) for x in xs]
    ax.plot(xs, ys, 'black')
    plt.title("y=sigmoid(s)")
    plt.grid(True)
    if fname:
        plt.savefig(fname)
    plt.show()
Exemple #20
0
def my_plot(fits, vectors, ndf):
    plt.rcParams['mathtext.fontset'] = 'stix' # 'cm'
    plt.rcParams["font.family"] = "Times New Roman"
    if True:
        # for fit in fits:
        #     print(fit)
        # ax = pg.plot_non_dominated_fronts(fits)

        # ax = my_plot_non_dominated_fronts(fits, comp=[0,1], marker='o', up_to_rank_no=3)        
        # ax = my_plot_non_dominated_fronts(fits, comp=[0,2], marker='o', up_to_rank_no=3)
        # ax = my_plot_non_dominated_fronts(fits, comp=[1,2], marker='o', up_to_rank_no=3)

        pass

        my_2p5d_plot_non_dominated_fronts(fits, comp=[0,1], marker='o', up_to_rank_no=1)
            # # for studying LSA population (whether or not the optimal is on Rank 1 Pareto Front)
            # x = fits[0][0]/1e3
            # y = fits[0][1]
            # z = fits[0][2]
            # ax.plot(x, y, color='k', marker='s')
            # ax.annotate(r'$x_{\rm optm}$', xy=(x, y), xytext=(x+1, y+0.0005), arrowprops=dict(facecolor='black', shrink=0.05),)

        # my_2p5d_plot_non_dominated_fronts(fits, comp=[0,2], marker='o', up_to_rank_no=1)
        # my_2p5d_plot_non_dominated_fronts(fits, comp=[1,2], marker='o', up_to_rank_no=1)

    else:
        # Obselete. Use ax.step instead to plot
        print('Valid for 2D objective function space only for now.')
        fig, axes = plt.subplots(ncols=2, nrows=1, dpi=150, facecolor='w', edgecolor='k');
        ax = axes[0]

        for index, xy in enumerate(vectors):
            ax.plot(*xy, 's', color='0')
            ax.text(*xy, '#%d'%(index), color='0')
        ax.title.set_text("Decision Vector Space")

        ax = axes[1]

        for index, front in enumerate(ndf):
            print('Rank/Tier', index, front)
            the_color = '%g'%(index/len(ndf))
            for individual in front: # individual is integer here
                ax.plot(*fits[individual], 'o',                 color=the_color)
                ax.text(*fits[individual], '#%d'%(individual),  color=the_color)

            front = front.tolist()
            front.sort(key = lambda individual: fits[individual][1]) # sort by y-axis value # individual is integer here
            for individual_A, individual_B in zip(front[:-1], front[1:]): # front is already sorted
                fits_A = fits[individual_A]
                fits_B = fits[individual_B]
                ax.plot([fits_A[0], fits_B[0]], 
                        [fits_B[1], fits_B[1]], color=the_color, lw=0.25) # 取高的点的Y
                ax.plot([fits_A[0], fits_A[0]], 
                        [fits_A[1], fits_B[1]], color=the_color, lw=0.25) # 取低的点的X
        ax.title.set_text("Pareto Front | Objective Function Space")
Exemple #21
0
def show_fashion_mnist(images, labels):

    # plt.set_matplotlib_formats('svg')
    # 这里的_表示我们忽略(不使用)的变量
    _, figs = plt.subplots(1, len(images), figsize=(12, 12))
    for f, img, lbl in zip(figs, images, labels):
        f.imshow(img.reshape((28, 28)).asnumpy())
        f.set_title(lbl)
        f.axes.get_xaxis().set_visible(False)
        f.axes.get_yaxis().set_visible(False)
    plt.show()
Exemple #22
0
def show_images(imgs, num_rows, num_cols, scale=2):
    '''
    画出多张图片
    '''
    figsize = (num_cols * scale, num_rows * scale)
    _, axes = plt.subplots(num_rows, num_cols, figsize=figsize)
    for i in range(num_rows):
        for j in range(num_cols):
            axes[i][j].imshow(imgs[i * num_cols + j])
            axes[i][j].axes.get_xaxis().set_visible(False)
            axes[i][j].axes.get_yaxis().set_visible(False)
    return axes
    def subplots(self, figNum, numRows, figTitle='', sharex=True, numCols=1):
        #         if not figNum in self.sharex.keys():
        #             self.sharex[figNum] = plt.subplot(numRows,1,plotNum)
        # #             plt.plot(time, data, options)
        if not figNum in self.f.keys():
            self.f[figNum] = cObj()
            self.f[figNum].fig, self.f[figNum].ax = plt.subplots(numRows,
                                                                 numCols,
                                                                 sharex=sharex)

        self.f[figNum].fig.canvas.set_window_title("%s__%s" %
                                                   (self.preTitle, figTitle))

        return self.f[figNum].fig, self.f[figNum].ax
def plotBeforeAfterFilter(originalS, myFilter, myFilter_time, filteredS, genere, filter_idx):
  fig, (ax_orig, ax_win, ax_winT, ax_filt) = plt.subplots(4, 1, sharex=True)
  ax_orig.plot(originalS)
  ax_orig.set_title('Original pulse')
  ax_orig.margins(0, 0.1)
  ax_win.plot(myFilter)
  ax_win.set_title('str(filter_idx)'+' Filter impulse response--FrequencyDomain')
  ax_win.margins(0, 0.1)
  ax_winT.plot(myFilter_time)
  ax_winT.set_title('str(filter_idx)'+' Filter impulse response--TimeDomain')
  ax_winT.margins(0, 0.1)
  ax_filt.plot(filteredS)
  ax_filt.set_title('Filtered signal')
  ax_filt.margins(0, 0.1)
  fig.tight_layout()
Exemple #25
0
def plotSigmoidBias(fname=None):
    fig, ax = plt.subplots()
    xs = np.linspace(-10.0, 10.0, num = 50, endpoint=True)
    ys = [sigmoid(1.0 * x - 5.0) for x in xs]
    ax.plot(xs, ys, 'black', linestyle='-', label='sig(1.0 * x - 1.0 * 5)')
    ys = [sigmoid(1.0 * x) for x in xs]
    ax.plot(xs, ys, 'black', linestyle='--', label='sig(1.0 * x + 1.0 * 0)')
    ys = [sigmoid(1.0 * x + 5.0) for x in xs]
    ax.plot(xs, ys, 'black', linestyle='-.', label='sig(1.0 * x + 1.0 * 5)')
    legend = ax.legend(loc='best', framealpha=0.5)
    plt.title("y=sig(s * w1 + 1.0 * w2)")
    plt.grid(True)
    if fname:
        plt.savefig(fname)
    plt.show()
Exemple #26
0
def my_plot_non_dominated_fronts(points,
                                 marker='o',
                                 comp=[0, 1],
                                 up_to_rank_no=None):
    # We plot
    fronts, _, _, _ = pg.fast_non_dominated_sorting(points)

    # We define the colors of the fronts (grayscale from black to white)
    if up_to_rank_no is None:
        cl = list(
            zip(np.linspace(0.1, 0.9, len(fronts)),
                np.linspace(0.1, 0.9, len(fronts)),
                np.linspace(0.1, 0.9, len(fronts))))
    else:
        cl = list(
            zip(np.linspace(0.1, 0.9, up_to_rank_no),
                np.linspace(0.1, 0.9, up_to_rank_no),
                np.linspace(0.1, 0.9, up_to_rank_no)))

    fig, ax = plt.subplots()

    count = 0
    for ndr, front in enumerate(fronts):
        count += 1
        # We plot the points
        for idx in front:
            ax.plot(points[idx][comp[0]],
                    points[idx][comp[1]],
                    marker=marker,
                    color=cl[ndr])
        # We plot the fronts
        # Frist compute the points coordinates
        x = [points[idx][comp[0]] for idx in front]
        y = [points[idx][comp[1]] for idx in front]
        # Then sort them by the first objective
        tmp = [(a, b) for a, b in zip(x, y)]
        tmp = sorted(tmp, key=lambda k: k[0])
        # Now plot using step
        ax.step([c[0] for c in tmp], [c[1] for c in tmp],
                color=cl[ndr],
                where='post')
        if up_to_rank_no is None:
            pass
        else:
            if count >= up_to_rank_no:
                break

    return ax
def plot_mat(data):
    # Three subplots sharing both x/y axes
    f, axarray = plt.subplots(16, sharex=True, sharey=True)
    for i, row in enumerate(data):
        axarray[i].plot(range(len(row)), row, 'g')
    # Fine-tune figure; make subplots close to each other and hide x ticks for
    # all but bottom plot.
    f.subplots_adjust(hspace=0)
    plt.setp([a.get_xticklabels() for a in f.axes], visible=False)
    plt.setp([a.get_yticklabels() for a in f.axes], visible=False)
    axarray[0].set_title('10 minute EEG Reading for Patient')
    axarray[int(len(axarray) / 2)].set_ylabel('Magnitude')
    axarray[-1].set_xlabel('Time')
    font = {'family': 'normal', 'weight': 'bold', 'size': 48}
    plt.rc('font', **font)
    plt.show()
Exemple #28
0
 def plotMap(self, fname=None):
     fig, ax = plt.subplots()
     ax.plot([self.o1[0], self.a[0], self.o2[0]],
             [self.o1[1], self.a[1], self.o2[1]],
             'r',
             label='Trajectory 0')
     ax.plot([self.o1[0], self.b[0], self.o2[0]],
             [self.o1[1], self.b[1], self.o2[1]],
             'b--',
             label='Trajectory 1')
     legend = ax.legend(loc='best', framealpha=0.5)
     plt.title("Map")
     plt.grid(True)
     if fname:
         plt.savefig(fname)
     plt.show()
def plot_baseline(data, plate_name, save_folder = r'Figures/'):
    """
    """
    colors = ((0.2, 0.2, 0.2),
              (0.5, 0.5, 0.5),
              (0.7, 0.7, 0.7),
              (0.3, 0.3, 0.3))

    names = data.keys()
    names.sort()
    fig, axs = plt.subplots(figsize=(8,3))
    for index, name in enumerate(names):
        for value in data[name]['original_data']:
            plot_color = colors[index % len(colors)]
            
            if abs(value - data[name]['mean'][0]) > data[name]['std'][0] * 2.0:
                axs.plot([value], [index], 'ko', markerfacecolor = [1,1,1])
            else:
                axs.plot([value], [index], 'ko', color = plot_color)

        axs.plot([data[name]['mean'][0] for _ in xrange(2)],
                 [index-0.25, index+0.25],
                  'k-')
        axs.plot([data[name]['mean'][0] - data[name]['std'][0] for _ in xrange(2)],
                 [index-0.25, index+0.25],
                 'k--')
        axs.plot([data[name]['mean'][0] + data[name]['std'][0] for _ in xrange(2)],
                 [index-0.25, index+0.25],
                 'k--')

    plt.yticks([i for i in xrange(len(names))], names, size = 10)
    plt.title(plate_name)
    plt.ylim(-0.5,len(names)-0.5)
    plt.xlabel('Fluorescent intensity')
    plt.tight_layout()

    save_filename = save_folder + 'baseline_average'

    pdf = PdfPages(save_filename.split('.')[0] + '.pdf')
    pdf.savefig(fig)
    pdf.close()

    plt.savefig(save_filename)
    #
    return None
def plot_mat(data):
    # Three subplots sharing both x/y axes
    f, axarray = plt.subplots(16, sharex=True, sharey=True)
    for i, row in enumerate(data):
        axarray[i].plot(range(len(row)), row, 'g')
    # Fine-tune figure; make subplots close to each other and hide x ticks for
    # all but bottom plot.
    f.subplots_adjust(hspace=0)
    plt.setp([a.get_xticklabels() for a in f.axes], visible=False)
    plt.setp([a.get_yticklabels() for a in f.axes], visible=False)
    axarray[0].set_title('10 minute EEG Reading for Patient')
    axarray[int(len(axarray) / 2)].set_ylabel('Magnitude')
    axarray[-1].set_xlabel('Time')
    font = {'family': 'normal',
            'weight': 'bold',
            'size': 48}
    plt.rc('font', **font)
    plt.show()
def convolve(arrays, melBank, genere, filter_idx):
  x = []
  melBank_time = np.fft.ifft(melBank) #need to transform melBank to time domain
  for eachClip in arrays:
    result = np.convolve(eachClip, melBank_time)
    x.append(result)
    plotBeforeAfterFilter(eachClip, melBank, melBank_time, result, genere, filter_idx)

  m = np.asmatrix(np.array(x))
  fig, ax = plt.subplots()
  ax.matshow(m.real) #each element has imaginary part. So just plot real part
  plt.axis('equal')
  plt.axis('tight')
  plt.title(genere)
  plt.tight_layout()
  # filename = "./figures/convolution/Convolution_"+"Filter"+str(filter_idx)+genere+".png"
  # plt.savefig(filename)
  plt.show()
Exemple #32
0
def animate(S0, u, d, p, T, N, P=10):
    '''
    S: data
    NumSims: simulation size
    numPaths: no. of simulated paths shown
    '''
    S = simulate(S0, u, d, p, T, N)
    fig, mainplot = plt.subplots(figsize=(10, 5))
    mainplot.plot(S[:, :P])
    plt.grid(True)
    plt.xlabel('time step')
    plt.ylabel('price')
    divider = make_axes_locatable(mainplot)
    axHist = divider.append_axes("right", 2.5, pad=0.1, sharey=mainplot)
    axHist.hist(S[-1, :N], bins=15, orientation='horizontal', normed=True)
    axHist.yaxis.set_ticks_position("right")
    axHist.xaxis.set_major_formatter(FuncFormatter('{0:.1%}'.format))
    plt.grid(True)
    plt.xlabel('probability')
    plt.show()
Exemple #33
0
def money_bar_plots(means, errors, labels, ax=None, letter=None):

    if ax is None:
        print('No ax given, I will create a fig.')
        fig, ax = plt.subplots()

    if letter:
        ax.text(s=letter,
                x=-0.1,
                y=-0.68,
                horizontalalignment='center',
                verticalalignment='center',
                transform=ax.transAxes,
                fontsize=20)

    # Hide spines
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)

    ax.tick_params(axis='y', labelsize=8)
    ax.tick_params(axis='x', length=0)

    # print(labels)

    # Set x labels
    labels_pos = np.arange(len(labels))
    ax.set_xticklabels(labels, rotation='vertical')
    ax.set_xticks(labels_pos)

    ax.set_ylim(0, 1)
    ax.set_yticks((0, 0.5, 1))

    ax.set_ylabel("Monetary behavior")

    # create
    ax.bar(labels_pos,
           means,
           errors=errors,
           edgecolor="white",
           align="center",
           color="black")
Exemple #34
0
 def plot(self, good, bad, dataset0, dataset1, fname=None):
     fig, ax = plt.subplots()
     ax.plot([self.o1[0], self.a[0], self.o2[0]],
             [self.o1[1], self.a[1], self.o2[1]],
             'r',
             label='Trajectory 0')
     ax.plot([self.o1[0], self.b[0], self.o2[0]],
             [self.o1[1], self.b[1], self.o2[1]],
             'b--',
             label='Trajectory 1')
     if dataset0.any():
         ax.plot(dataset0[:, 0],
                 dataset0[:, 1],
                 'ro',
                 label='Train Dataset 0')
     if dataset1.any():
         ax.plot(dataset1[:, 0],
                 dataset1[:, 1],
                 'b*',
                 label='Train Dataset 1')
     if good.any():
         ax.plot(good[:, 0],
                 good[:, 1],
                 'go',
                 markersize=10,
                 label='Correct prediction')
     if bad.any():
         ax.plot(bad[:, 0],
                 bad[:, 1],
                 'black',
                 linestyle='none',
                 marker='D',
                 markersize=10,
                 label='Incorrect prediction')
     legend = ax.legend(loc='best', framealpha=0.5)
     plt.title("Map")
     plt.grid(True)
     if fname:
         plt.savefig(fname)
     plt.show()
Exemple #35
0
def get_axis():
    fig, axes = plt.subplots(ncols=1,
                             nrows=1,
                             sharex=True,
                             figsize=(7, 4.7),
                             dpi=80,
                             facecolor='w',
                             edgecolor='k')  # 1 inch = 2.5cm
    fig.subplots_adjust(right=0.90,
                        bottom=0.15,
                        top=0.85,
                        hspace=0.2,
                        wspace=0.1)

    # gcf() means get the current fig, so  plt.gcf().axes() means create axes in current fig
    # grid on
    # plt.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)
    plt.grid(color='lightgray', linestyle='-', linewidth=0.5, alpha=0.3)

    #figure ax size setting

    return axes
Exemple #36
0
def plot_slip_and_rate_at_subflt(slip, nth_dip, nth_stk):
    epochs = slip.get_epochs()

    ts_slip = slip.get_cumu_slip_at_subfault(nth_dip, nth_stk)
    ts_rate = slip.get_slip_rate_at_subfault(nth_dip, nth_stk)

    fig, ax1 = plt.subplots()
    ln1 = ax1.plot(epochs, ts_slip, 'r^-', label='Slip')
    ax1.grid('on')
    ax1.set_ylabel('Slip/m')
    ax1.set_xlabel('Days after the mainshock')

    ax2 = ax1.twinx()
    ln2 = ax2.plot(epochs[1:], ts_rate, 'bo-', label='Rate')
    ax2.set_ylabel('Rate/(m/day)')

    fontP = FontProperties()
    fontP.set_size('small')

    lns = ln1 + ln2
    labs = [l.get_label() for l in lns]
    ax2.legend(lns, labs, loc=1, prop=fontP, bbox_to_anchor=(1.1, 1.05))
Exemple #37
0
def generate_random_samples():
    sample_size = 100

    rn1 = npr.rand(sample_size, 3)
    rn2 = npr.randint(1, 10, sample_size)
    rn3 = npr.sample(size=sample_size)
    a = list(range(0, 101, 25))
    rn4 = npr.choice(a, sample_size)

    fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2,
                                                 ncols=2,
                                                 figsize=(10, 8))
    ax1.hist(rn1, bins=25, stacked=True)
    ax1.set_title('rand')
    ax1.set_ylabel('frequency')
    ax2.hist(rn2, bins=25)
    ax2.set_title('randint')
    ax3.hist(rn3, bins=25)
    ax3.set_title('sample')
    ax3.set_ylabel('frequency')
    ax4.hist(rn4, bins=25)
    ax4.set_title('choice')
    plt.show()
def plot_slip_and_rate_at_subflt(slip, nth_dip, nth_stk):
    epochs = slip.get_epochs()

    ts_slip = slip.get_cumu_slip_at_subfault(nth_dip, nth_stk)
    ts_rate = slip.get_slip_rate_at_subfault(nth_dip, nth_stk)

    fig, ax1 = plt.subplots()
    ln1 = ax1.plot(epochs, ts_slip, 'r^-', label='Slip')
    ax1.grid('on')
    ax1.set_ylabel('Slip/m')
    ax1.set_xlabel('Days after the mainshock')

    ax2 = ax1. twinx()
    ln2 = ax2.plot(epochs[1:], ts_rate, 'bo-', label='Rate')
    ax2.set_ylabel('Rate/(m/day)')

    fontP = FontProperties()
    fontP.set_size('small')

    lns = ln1 + ln2
    labs = [l.get_label() for l in lns]
    ax2.legend(lns, labs, loc=1,
               prop = fontP,
               bbox_to_anchor=(1.1, 1.05))
Exemple #39
0
    _, y2 = ax2.transData.transform((0, v2))
    inv = ax2.transData.inverted()
    _, dy = inv.transform((0, 0)) - inv.transform((0, y1-y2))
    miny, maxy = ax2.get_ylim()
    ax2.set_ylim(miny+dy, maxy+dy)

site = 'J543'
cmpt = 'u'

epochs, ys = get_ts(site, cmpt)

vel = np.diff(ys)/np.diff(epochs)

from pylab import plt

fig, ax1 = plt.subplots()

pos1 = ax1.get_position() # get the original position 
pos2 = [pos1.x0, pos1.y0,  pos1.width/1.1 , pos1.height] 
ax1.set_position(pos2)

ax1.plot(np.asarray(epochs)/365., ys,'bx-',
         label='disp.')
ax1.legend(loc=0)
#ax1.set_ylim([-1e-6,2e-6])
#
#######################

ax2 = ax1.twinx()
ax2.plot(np.asarray(epochs[1:])/365., vel*365,'r',
         label=r'vel ($yr^{-1}$)')
step = int((Ns-window)/Nwindow)
time_bins = range(0, Ns-window, step)

pv = []
Fv = []
# For each frequency bin, estimate the stats
t_init = time()
for t in time_bins:
    covmats = covest.fit_transform(epochs_data[:, ::1, t:(t+window)])
    p_test = PermutationDistance(1000, metric='riemann', mode='pairwise')
    p, F = p_test.test(covmats, labels, verbose=False)
    pv.append(p)
    Fv.append(F[0])
duration = time() - t_init
# plot result
fig, axes = plt.subplots(1, 1, figsize=[6, 3], sharey=True)
sig = 0.05
times = np.array(time_bins)/float(Fs) + tmin

axes.plot(times, Fv, lw=2, c='k')
plt.xlabel('Time (sec)')
plt.ylabel('Score')

a = np.where(np.diff(np.array(pv) < sig))[0]
a = a.reshape(int(len(a)/2), 2)
st = (times[1] - times[0])/2.0
for p in a:
    axes.axvspan(times[p[0]]-st, times[p[1]]+st, facecolor='g', alpha=0.5)
axes.legend(['Score', 'p<%.2f' % sig])
axes.set_title('Pairwise distance - %.1f sec.' % duration)
 def createPdfPage( self ):
     print "Creating a new subplot grid"
     self.fig, self.axarr = plt.subplots(figsize=(8, 8), nrows=self.rows, ncols=self.columns )
Exemple #42
0
def runAnalysis( caseDirs , resultsDir , noReweight = False):
    
    # Do a reference for each one
    for refDir in caseDirs:

        # ID of reference case
        refID = refDir.split("/")[-1]
        
        # User info
        print "Doing PCA analysis with "+refDir+" as reference"
        
        # Get the PCA limits of component 1-2 plot
        limit = 10
        with open(refDir+"/analysis/data/pca_limits_1", "r") as fi:
            limit = int(float(fi.read()))
            limit += 0.01
        
        # Go through the case dirs to plot
        for caseDir in caseDirs:
            
            print "Using "+caseDir+" as case"
            
            # ID of case
            caseID = caseDir.split("/")[-1]
            
            ## PCA PLOTTING ON REF DIR PCA COMPONENTS
            #########################################
            
            # Create & run cpptraj for plotting all cases on the axes of the first eigenvector
            # Good URLs for PCA in CPPTRAJ:
            # http://archive.ambermd.org/201404/0243.html
                        
            # PCA plotter
            pcaHandler = pcaFuncs.PCA( 
                resultsDir+"/plots/pcaComparison/PCA_"+caseID+"_on_"+refID+".pdf"
            )    
            
            # Create new submission file
            TEMPLATE = open( caseDir+"/ccptraj_analysis_pca.ptraj", 'r')
            TEMP = TEMPLATE.read().replace("[PCAREFERENCE]", refDir  )
            TEMPLATE.close()
                                  
            # Write the submission file
            FILE = open(caseDir+"/ccptraj_analysis_pca.ptraj","w");        
            FILE.write( TEMP );
            FILE.close();
            
            # Run the cpptraj utility
            os.system( "$AMBERHOME/bin/cpptraj -p "+caseDir+"/md-files/peptide_nowat.prmtop -i "+caseDir+"/ccptraj_analysis_pca.ptraj" )
        
            # Do the plots of energy landscapes & distributions
            pcaHandler.plotPCA( 
                "Case: "+caseID+". Ref case: "+refID,   # Plot Title
                caseDir+"/analysis/data/" ,        # Data Dir
                "global_pca",                      # Eigenvector file
                eigenVectorCount = 2,              # Only plot two
                plotDistibution = False,           # Do not plot the distribution
                limits = limit
            )
            
            # Save the plot
            pcaHandler.savePlot()
            
            ## REWEIGHTING OF PCA PLOTS ON RED DIR PCA COMPONENTS
            #####################################################

            # Check if we should do a reweighted version
            if noReweight == False:
                if os.path.isfile( caseDir+"/md-logs/weights.dat" ):
                    
                    # User info
                    print "aMD weights found. Now attempting 2D reweighting"   
                    
                    # Prepare input file
                    numLines = 0
                    with open(caseDir+"/analysis/data/global_pca", "r") as fi:
                        with open(caseDir+"/analysis/data/global_pca_singleColumn", "w") as fo:
                            next(fi)
                            for line in fi:
                                numLines += 1
                                fo.write( line.split()[1]+"\t"+line.split()[2]+"\n" )

                    # Set the discretization
                    reqBins = 100         
                    discretization = (2*limit) / reqBins    
                    
                    # Get the max value of normal plot
                    maxValue = math.ceil(pcaHandler.getLatestMax())
                    
                    # Run the reweighting procedure
                    command = "python $PLMDHOME/src/PyReweighting/PyReweighting-2D.py \
                                -input "+caseDir+"/analysis/data/global_pca_singleColumn \
                                -name "+caseDir+"/analysis/data/global_pca_singleColumn_reweighted \
                                -Xdim -"+str(limit)+" "+str(limit)+" \
                                -Ydim -"+str(limit)+" "+str(limit)+" \
                                -discX "+str(discretization)+" \
                                -discY "+str(discretization)+" \
                                -cutoff 10 \
                                -Emax "+str(maxValue)+" \
                                -job amdweight_CE \
                                -weight "+refDir+"/md-logs/weights.dat | tee -a reweight_variable.log"
                    print "Running command:", command
                    os.system( command )
                    
                    # Create long file for PCA module
                    with open(caseDir+"/analysis/data/global_pca_reweightedDone", "w") as fo:
                        with open(caseDir+"/analysis/data/global_pca_singleColumn_reweighted-pmf-c2.dat", "r") as fi:
                            frame = 0
                            for line in fi:
                                temp = line.split()
                                entries = int(float(temp[2])*10)
                                for i in range(0,entries):
                                    fo.write( str(frame) + "\t" + temp[0] + "\t" + temp[1] +"\n" )
                                    frame += 1

                    # Print block analysis 'family' : 'Arial',
                    fig, ax = plt.subplots(figsize=(8, 8), nrows=1, ncols=1 )
                    font = {'weight' : 'normal','size' : 10}
                    plt.rc('font', **font)
                    
                    # Now plot the 2d histogram
                    hist = np.load(caseDir+"/analysis/data/global_pca_singleColumn_reweighted_c2EnergyHist.npy")   
                    xedges = np.load(caseDir+"/analysis/data/global_pca_singleColumn_reweighted_c2edgesX.npy")   
                    yedges = np.load(caseDir+"/analysis/data/global_pca_singleColumn_reweighted_c2edgesY.npy")   
                    
                    # Remove points above limit
                    for jy in range(len(hist[0,:])):
                        for jx in range(len(hist[:,0])):
                            if hist[jx,jy] >= maxValue:
                                hist[jx,jy] = float("inf")
                    
                    # Do plot
                    img = plt.imshow(hist.transpose(),  interpolation='nearest', origin='lower',extent=[yedges[0], yedges[-1],xedges[0], xedges[-1]] , rasterized=True )
                    
                    # create an axes on the right side of ax. The width of cax will be 5%
                    # of ax and the padding between cax and ax will be fixed at 0.05 inch.
                    divider = make_axes_locatable(ax)
                    cax = divider.append_axes("right", size="5%", pad=0.05)   
                    
                    # Create colorbar
                    colorbar = plt.colorbar(img, ax=ax, cax = cax)
                    colorbar.set_label("Kcal / mol")
                    
                    # Set title, labels etc
                    plt.legend()
                    ax.set_xlabel("PC1", fontsize=12)
                    ax.set_ylabel("PC2", fontsize=12)
                    
                    ax.set_title( "PCA. Case: "+caseID+" Reweighted. Ref case: "+refID )
                    plt.rc('font', **font) 
                    
                    # Save figure
                    fig.savefig(resultsDir+"/plots/pcaComparison/PCA_"+caseID+"_on_"+refID+"_reweighted.pdf")
                    

            ## CLUSTER PLOTS ON PCA COMPONENTS
            ##################################

            # Do both hier and dbscan
            for clusterType in ["dbscan","hier"]:            
                
                # Instantiate the class
                if os.path.isfile(caseDir+"/analysis/data/cluster_"+clusterType+"_out"):   
                    
                    print "Doing the "+clusterType+" cluster equivalent of the PCA plot"
                
                    # Start the cluster handler. Load the file declaring cluster for each frame
                    clusterHandler = cluster.clusterBase( caseDir+"/analysis/data/cluster_"+clusterType+"_out" )
                    
                    # Separate the dataset.
                    # global_pca is the projection file for this case on the ref modes
                    numPCAdataSets = clusterHandler.separateDataSet( 
                        caseDir+"/analysis/data/global_pca",            # Input file
                        caseDir+"/analysis/data/cluster_"+clusterType+"_pca_",   # Output files
                        xColumn = 1
                    ) 
                    
                    # Create lists of labels and files for plotting
                    clusterLabels = []
                    clusterFiles = []
                    offset = 1 if clusterType == "hier" else 0
                    for i in range( 0+offset, numPCAdataSets+offset):
                        clusterLabels.append( "Cluster "+str(i) )
                        clusterFiles.append( caseDir+"/analysis/data/cluster_"+clusterType+"_pca_d2_c"+str(i) )
                    
                    # First one is noise
                    if offset == 0:
                        clusterLabels[0] = "Noise"                 
                    
                    myPlot.plotData( 
                        resultsDir+"/plots/pcaComparison/" , 
                        clusterType+"_"+caseID+"_on_"+refID, 
                        clusterLabels, 
                        clusterFiles , 
                        "PC2",
                        xUnit = "PC1",
                        scatter = True,
                        legendLoc = 4,
                        figWidth = 8,
                        figHeight = 8,
                        tightXlimits = False,
                        legendFrame = 1,
                        legendAlpha = 1,
                        xLimits = [-limit,limit],
                        yLimits = [-limit,limit]
                    )
def plot_slip_overview(slip,
                    output_file,
                    if_x_log=False,
                    xlim=[0, 1344],
                    ylim = [0,100],
                    yticks = [20, 40, 60],
                    xticks = [1, 10, 100, 1000],
                    xticklabels = [r'$10^0$', r'$10^1$', r'$10^2$', r'$10^3$'],
                    rotation = 45,
                    fontsize = 10,
                    ):
    num_subflts_strike = slip.num_subflt_along_strike
    num_subflts_dip = slip.num_subflt_along_dip

    epochs = slip.get_epochs()

    fig, axes = plt.subplots(num_subflts_dip,
                             num_subflts_strike,
                             sharex=True, sharey=True)
    for ii in range(num_subflts_dip):
        for jj in range(num_subflts_strike):
            ax = axes[ii][jj]
            slip_subflt = slip.get_cumu_slip_at_subfault(ii,jj)
            plt.sca(ax)
            plt.fill_between(x=epochs, y1=slip_subflt, y2=0, color='r')
            if if_x_log:
                ax.set_xscale('log')
            plt.xlim(xlim)
            plt.ylim(ylim)
            plt.grid('on')
            plt.box('on')

            plt.tick_params(axis='both',which='both',
                            bottom='off', top='off', left='off', right='off',
                            labelbottom='off', labeltop='off', labelleft='off', labelright='off')

    fig.subplots_adjust(hspace=0, wspace=0)

    for ax in axes[-1,::2]:
        plt.sca(ax)
        plt.tick_params(axis='x',which='major',
                            bottom='on', top='off', left='off', right='off',
                            labelbottom='on', labeltop='off', labelleft='off', labelright='off')
        ax.set_xticks(xticks)
        ax.set_xticklabels(xticklabels, rotation=rotation, fontsize=fontsize)
        plt.xlabel('day')

    for ax in axes[0,1::2]:
        plt.sca(ax)
        plt.tick_params(axis='x',which='major',
                            bottom='off', top='on', left='off', right='off',
                            labelbottom='off', labeltop='on', labelleft='off', labelright='off')
        ax.set_xticks(xticks)
        ax.set_xticklabels(xticklabels, rotation=rotation, fontsize=fontsize)
        plt.xlabel('day')

    for ax in axes[::2,0]:
        plt.sca(ax)
        plt.tick_params(axis='y',which='major',
                            bottom='off', top='off', left='on', right='off',
                            labelbottom='off', labeltop='off', labelleft='on', labelright='off')
        ax.set_yticks(yticks)
        #ax.set_yticklabels(range(0,100,20))
        for tick in ax.yaxis.get_major_ticks():
            tick.label.set_fontsize(10)
            tick.label.set_rotation('horizontal')
        plt.ylabel('slip/m')

    for ax in axes[::2,-1]:
        plt.sca(ax)
        plt.tick_params(axis='y',which='major',
                            bottom='off', top='off', left='off', right='on',
                            labelbottom='off', labeltop='off', labelleft='off', labelright='on')
        ax.set_yticks(yticks)
        #ax.set_yticklabels(range(0,100,20))
        for tick in ax.yaxis.get_major_ticks():
            tick.label.set_fontsize(10)
            tick.label.set_rotation('horizontal')
        plt.ylabel('slip/m')
        ax.yaxis.set_label_position("right")

    fig.set_size_inches(33,10)
    plt.savefig(output_file)
    plt.close()
def plot_mean_curve(time_data, data, additions, plate_name, save_folder = r'Figures/'):
    """
    """
    if not os.path.isdir(save_folder):
        os.makedirs(save_folder)

    for block in data:
        #
        group = group_similar(data[block].keys())
        names = data[block].keys()
        names.sort()
        # -----------------
        # Plot each group individualy
        # -----------------
        data_per_inch = 5.0

        y_len = int(math.sqrt(len(names)))
        x_len = int(np.ceil(len(names) / float(y_len)))

        fig, axs = plt.subplots(y_len, x_len, sharex=True, sharey=True,
                                figsize=(x_len*data_per_inch,y_len*data_per_inch), dpi=300)

        y_min = data[block][names[0]]['original_data'].min()
        y_max = data[block][names[0]]['original_data'].max()

        for i, name in enumerate(names):
            if data[block][name]['original_data'].min() < y_min:
                y_min = data[block][name]['original_data'].min()
            if data[block][name]['original_data'].max() > y_max:
                y_max = data[block][name]['original_data'].max()
        y_range = y_max - y_min
                
        for i, name in enumerate(names):
            px = i / x_len
            py = i % x_len
            if y_len > 1:
                position = (px, py)
            else:
                position = py

            time = time_data[block][name]
            mean = np.array(data[block][name]['mean'])
            std = np.array(data[block][name]['std'])
            all_curve = data[block][name]['original_data']

            axs[position].plot(time, [1.0 for _ in time], 'k-')
            for curve in all_curve:
                axs[position].plot(time, curve, color = [0.7 for _ in xrange(3)])
            axs[position].plot(time, mean, color = [0.2 for _ in xrange(3)], linewidth = 2.5, label = name)
            axs[position].plot(time, mean+std, 'k--', color = [0.2 for _ in xrange(3)], linewidth = 2.5)
            axs[position].plot(time, mean-std, 'k--', color = [0.2 for _ in xrange(3)], linewidth = 2.5)

            for addition in additions[:block+1]:
                axs[position].plot([addition[0] for _ in xrange(2)], [0.0,3.0], 'k-')
                axs[position].text(addition[0], 0.98, addition[1], rotation=270)
            
            if i % x_len == 0:
                axs[position].set_ylabel('Normalized fluorescence', size = 14)
            if i / x_len == y_len - 1:
                axs[position].set_xlabel('Time / sec', size = 14)
                
            axs[position].set_xlim(0, time[-1])

            for j, text in enumerate(name.split(';')):
                axs[position].text(10, y_max - y_range*j*0.1, text, size = 14)

        axs[position].set_ylim(y_min-y_range*0.1, y_max+y_range*0.1)
        
#        plt.suptitle(plate_name)
        plt.subplots_adjust(wspace = 0.01, hspace = 0.01)
        plt.tight_layout()
        plt.savefig(save_folder + 'block_' + str(block + 1))
    #
    return None