Esempio n. 1
0
def broken_axis(df, leftpad=pd.Timedelta("7H"), sunHours=0):
    d2n = mdates.date2num

    allDays = pd.date_range(df.index[0].date(), df.index[-1], freq="1D")
    sundays = allDays[allDays.day_name() == "Sunday"]

    if len(sundays) == 0:
        return brokenaxes(xlims=[(d2n(df.index[0]), d2n(df.index[-1]))])

    if sunHours == 0:
        sundayStarts = [sun.replace(hour=0) - pd.Timedelta(hours=1, minutes=2) for sun in sundays]
        sundayEnds = [sun.replace(hour=23, minute=59) + pd.Timedelta(minutes=2) for sun in sundays]
    else:
        sundayStarts = [sun.replace(hour=sunHours) for sun in sundays]
        sundayEnds = [sun.replace(hour=24-sunHours) for sun in sundays]



    xParts = [(d2n(df.index[0] - leftpad), d2n(sundayStarts[0]))]
    for i in range(len(sundayStarts)-1):
        xParts.append( (d2n(sundayEnds[i]), d2n(sundayStarts[i+1])) )

    xParts.append( (d2n(sundayEnds[len(sundayStarts)-1]), d2n(df.index[-1])) )

    bax = brokenaxes(xlims=xParts, wspace=.02, d=.005)

    return bax
Esempio n. 2
0
def test_subplots():
    sps1, sps2 = GridSpec(2, 1)

    bax = brokenaxes(xlims=((0.1, 0.3), (0.7, 0.8)), subplot_spec=sps1)
    x = np.linspace(0, 1, 100)
    bax.plot(x, np.sin(x * 30), ls=":", color="m")

    x = np.random.poisson(3, 1000)
    bax = brokenaxes(xlims=((0, 2.5), (3, 6)), subplot_spec=sps2)
    bax.hist(x, histtype="bar")
def plot_spectra(data):

    X = data["data"]
    yc = data["cancer_label"]
    wn = data["wavenumber"]

    #plot with broken axis
    nnc = np.where(yc == 0)
    ncan = np.where(yc == 1)
    Mean1 = np.mean(X[nnc], axis=0)
    Mean2 = np.mean(X[ncan], axis=0)

    w1 = 1800
    w2 = 2800
    i1 = np.argmin(abs(wn - w1))
    i2 = np.argmin(abs(wn - w2))
    wn1 = wn[:i1]
    wn2 = wn[i2:]
    x = wn
    lower_CI = np.mean(X, axis=0) - np.std(X, axis=0)
    upper_CI = np.mean(X, axis=0) + np.std(X, axis=0)

    sps1, sps2 = GridSpec(2, 1)
    fig = plt.figure(figsize=(10, 6))
    fig.subplots_adjust(hspace=0.5)

    bax = brokenaxes(xlims=((min(wn1), max(wn1)), (min(wn2) - 20, max(wn2))),
                     hspace=0.15,
                     subplot_spec=sps1)
    bax.plot(x, Mean1, color="blue", linewidth=2, label="NTHY")
    bax.plot(x, Mean2, color="red", linewidth=2, label="FTC")
    bax.fill_between(wn, lower_CI, upper_CI, color='#539caf', alpha=0.4)
    bax.legend(loc="upper left")
    bax.set_ylabel('Intensity [au]')
    bax.set_xlabel('Wavenumber [cm-1]')
    bax.tick_params(axis='both',
                    labelleft=False,
                    labelbottom=False,
                    bottom=False)

    bax = brokenaxes(xlims=((min(wn1), max(wn1)), (min(wn2) - 20, max(wn2))),
                     hspace=0.15,
                     subplot_spec=sps2)
    bax.axhline(y=0, color='black', linestyle='--', alpha=0.3)
    bax.plot(x, Mean1 - Mean2, color="red", linewidth=2)
    bax.fill_between(wn,
                     lower_CI - np.mean(X, axis=0),
                     upper_CI - np.mean(X, axis=0),
                     color='#539caf',
                     alpha=0.4)
    bax.set_ylabel('$\\Delta$ Intensity [au]')
    bax.set_ylim(-1.5, 1.5)
    bax.tick_params(axis='y', labelleft=False)

    plt.show()
def band_edge_plot(files, margin=0.03, title="VBM and CBM"):
    mean = lambda x: sum(x) / len(x)
    vbm = mean(plot_function(files, valence_band_max, valsonly=True))
    cbm = mean(plot_function(files, conduction_band_min, valsonly=True))
    baxes = bax.brokenaxes(ylims=((vbm - margin, vbm + margin),
                                  (cbm - margin, cbm + margin)),
                           hspace=0.05)
    plot_function(files,
                  valence_band_max,
                  title=title,
                  timestep=0.03,
                  xlabel="time (ps)",
                  ylabel="Energy (eV)",
                  display=False,
                  axes=baxes,
                  colors=["b"])
    plot_function(files,
                  conduction_band_min,
                  title=title,
                  timestep=0.03,
                  xlabel="time (ps)",
                  ylabel="Energy (eV)",
                  display=True,
                  axes=baxes,
                  colors=["g"])
Esempio n. 5
0
	def plot(self,x,y,bar_width=0.001,dpi=300,Save=True):
		plt.rc('font', family='Times New Roman',size=26)
		# fig, ax = plt.subplots(figsize=(10, 8))
		# fig.subplots_adjust(bottom=0.2,left=0.2)
		fig = plt.figure(figsize=(10,8))
		fig.subplots_adjust(bottom=0.2,left=0.2)		
		'''打截断'''
		bax = brokenaxes(ylims=((0,80),(1100,1170)),hspace=0.06,despine=False)
		bax.bar(x, y, bar_width,hatch='\\\\',color='white',edgecolor='blue')

	
		# bax.set_xlabel('Eigenvector Amplitude',fontsize=26,fontweight='bold')
		# bax.set_ylabel('Count',fontsize=26,fontweight='bold')

		# bax.set_title('$\mathregular{\mathit{f}}$ =0.365THz')
		# plt.xticks([0,0.02,0.04,0.06,0.08,0.10,0.12],[0,0.02,0.04,0.06,0.08,0.10,0.12])
		# plt.yticks([0,200,400,600,800,1000,1200],[0,200,400,600,800,1000,1200])
		# plt.yticks([0,5,10,15,20],[0,5,10,15,20])
		# plt.yticks([0,2,4,6,8,10],[0,2,4,6,8,10])

		if Save==True:
 			plt.savefig(self.data+'.tiff',dpi=dpi)

		plt.show()
		return
Esempio n. 6
0
def test_legend():
    fig = plt.figure(figsize=(5, 2))
    bax = brokenaxes(
        xlims=((0, 0.1), (0.4, 0.7)), ylims=((-1, 0.7), (0.79, 1)), hspace=0.05
    )
    x = np.linspace(0, 1, 100)
    h1 = bax.plot(x, np.sin(10 * x), label="sin")
    h2 = bax.plot(x, np.cos(10 * x), label="cos")
    bax.legend(handles=[h1, h2], labels=["1", "2"])
Esempio n. 7
0
def breakaxis(gs1):
    return brokenaxes(
        subplot_spec=gs1,
        ylims=((-15 / 5 * 2, 90 / 5 * 2), (90 / 5 * 2, 750 / 5 * 2)),
        height_ratios=(50 / (90 + 15), 400 / (750 - 90) * 3),
        hspace=0.15,
        wspace=0.075,
        d=0.005,
    )
Esempio n. 8
0
def plots(images_dir, predict_dir):
    """Plots histograms of uncertainty values."""

    bu = np.load(predict_dir + "/bayesian/bayesian_unc.npy").flatten()
    du = np.load(predict_dir + "/dropout/dropout_unc.npy").flatten()

    # Removes extreme outliers so plot isn't stretched out.
    xlim = round(max(np.percentile(bu, 99.95), np.percentile(du, 99.95)), 2)
    bu = bu[bu < xlim]
    du = du[du < xlim]

    # Automatically calculates y-axis heights.
    bu_max = np.count_nonzero(bu == 0.)
    bu_mid = np.partition(np.histogram(bu, bins=50)[0], -2)[-2]
    du_max = np.count_nonzero(du == 0.)
    du_mid = np.partition(np.histogram(du, bins=50)[0], -2)[-2]

    # Plots histogram of Bayesian uncertainty map.
    fig = plt.figure()
    if bu_mid > 0:
        bax = brokenaxes(ylims=((0, bu_mid), (bu_max - (bu_mid / 5), bu_max)))
        bax.hist(bu, bins=50)
    else:
        plt.hist(bu, bins=50)

    plt.title("Distribution of Bayesian uncertainty map")
    # plt.xlabel("Uncertainty value")
    # plt.ylabel("Count")
    plt.savefig(images_dir + "/bayesian/bayesian_unc_dist.png")
    plt.clf()

    # Plots histogram of dropout uncertainty map.
    fig = plt.figure()
    if du_mid > 0:
        bax = brokenaxes(ylims=((0, du_mid), (du_max - (du_mid / 5), du_max)))
        bax.hist(du, bins=50)
    else:
        plt.hist(du, bins=50)

    plt.title("Distribution of dropout uncertainty map")
    # plt.xlabel("Uncertainty value")
    # plt.ylabel("Count")
    plt.savefig(images_dir + "/dropout/dropout_unc_dist.png")
    plt.clf()
Esempio n. 9
0
def test_standard():
    fig = plt.figure(figsize=(5, 2))
    bax = brokenaxes(
        xlims=((0, 0.1), (0.4, 0.7)), ylims=((-1, 0.7), (0.79, 1)), hspace=0.05
    )
    x = np.linspace(0, 1, 100)
    bax.plot(x, np.sin(10 * x), label="sin")
    bax.plot(x, np.cos(10 * x), label="cos")
    bax.legend(loc=3)
    bax.set_xlabel("time")
    bax.set_ylabel("value")
Esempio n. 10
0
def smahtplot(time, flux, subplot_spec=None):

    if subplot_spec is None: plt.figure()

    ind0 = [0] + list(
        np.where(np.diff(time) > 10)[0] + 1)  #start indices of data chunks
    ind1 = list(np.where(
        np.diff(time) > 10)[0]) + [len(time) - 1]  #end indices of data chunks
    xlims = [(time[i], time[j]) for i, j in zip(ind0, ind1)]

    bax = brokenaxes(xlims=xlims, subplot_spec=subplot_spec)
    bax.plot(time, flux, 'b.')

    return bax
Esempio n. 11
0
            def plot_bars(gs1, bufdurs, losses1, add_xticklabel=True):
                i_break = np.amax(np.nonzero(np.array(bufdurs) < 0.3)[0])
                bax = brokenaxes(
                    subplot_spec=gs1,
                    xlims=((-1, i_break + 0.5), (i_break + 0.5,
                                                 len(bufdurs) - 0.5)),
                    ylims=((-3, 20), (20, 1250 / 5)),
                    height_ratios=(50 / 100, 500 / (1250 - 100)),
                    hspace=0.15,
                    wspace=0.075,
                    d=0.005,
                )
                bax.bar(np.arange(len(bufdurs)), losses1[i_subj, :], color='k')

                ax11 = bax.axs[3]  # type: plt.Axes
                ax11.set_xticks([bufdurs.index(0.6), bufdurs.index(1.2)])
                if i_subj == 0 and add_xticklabel:
                    ax11.set_xticklabels(['0.6', '1.2'])
                else:
                    ax11.set_xticklabels([])

                ax00 = bax.axs[0]  # type: plt.Axes
                ax00.set_yticks([500, 1000])

                ax10 = bax.axs[2]  # type: plt.Axes
                ax10.set_yticks([0, 50])
                plt.sca(ax10)
                plt2.detach_axis('x', amin=-0.4, amax=i_break + 0.5)
                for ax in [ax10, ax11]:
                    plt.sca(ax)
                    plt.axhline(0, linewidth=0.5, color='k', linestyle='--')
                    for sign in [-1, 1]:
                        plt.axhline(sign * thres_strong,
                                    linewidth=0.5,
                                    color='silver',
                                    linestyle='--')
                ax10.set_xticks([bufdurs.index(0.), bufdurs.index(0.2)])
                if i_subj == 0:
                    if add_xticklabel:
                        ax10.set_xticklabels(['0', '0.2'])
                    else:
                        ax10.set_xticklabels([])
                else:
                    ax10.set_yticklabels([])
                    ax10.set_xticklabels([])
                    ax00.set_yticklabels([])
                return bax
Esempio n. 12
0
def brokenplot(time, y, yerr=None, dt=10, ax=None, time_format='BJD_TDB'):
    '''
    Parameters
    ----------
    time : array of float
        e.g. time array (usually in days)
    y : array of float
        e.g. flux or RV array (usually as normalized flux or RV in km/s)
    yerr : array of float
        e.g. flux or RV error array (usually as normalized flux or RV in km/s)
    dt : float, optional
        The gap size after which axes will be broken. The default is 10 (usually in days).
    ax : TYPE, optional
        DESCRIPTION. The default is None.
    time_format : str
        The format of your time array. 
        Must be either 'BJD_TDB' or 'TJD' (TESS Julian Date). 
        The default is 'BJD_TDB'.

    Returns
    -------
    bax : brokenaxes instance
        Just like an pyplot.Axes instance
    '''

    if ax is None: fig, ax = plt.subplots(figsize=(12, 3))
    time, y, yerr = clean_up(time, y, yerr, time_format)

    ind0 = [0] + list(
        np.where(np.diff(time) > dt)[0] + 1)  #start indices of data chunks
    ind1 = list(np.where(
        np.diff(time) > dt)[0]) + [len(time) - 1]  #end indices of data chunks
    xlims = [(time[i] - (time[j] - time[i]) / 100.,
              time[j] + (time[j] - time[i]) / 100.)
             for i, j in zip(ind0, ind1)]

    ax.set_axis_off()  #empty the axis before brokenaxes does its magic
    bax = brokenaxes(xlims=xlims, subplot_spec=ax.get_subplotspec())
    bax.errorbar(time, y, yerr=yerr, fmt='b.', ms=2)
    # bax.ticklabel_format(axis='y', style='sci', useOffset=True)
    # plt.gca().yaxis.set_major_locator(plt.MaxNLocator(3))
    guess_labels(bax, time, y)
    bax.set_ylabel('Flux\n')

    return bax
Esempio n. 13
0
def plotBeds(name, NHSdata):

    if name in mergered_trusts.keys():
        fig = plotMergedBedData(name, NHSdata)

    else:
        names, dates, all_beds = NHSdata

        beds = all_beds[names == name][0]

        dates = dates[beds != "-"]
        beds = beds[beds != "-"]
        # format name to match waiting data
        names = proc.capitaliseFirst(names)
        # rescale large numbers to be in thousands
        if max(beds) > 1000:
            rescale = 1 / 1000
        else:
            rescale = 1

        ylabel = "# of Overnight Beds" + "\n(Thousands)" * (rescale
                                                            == 1 / 1000)

        fig = plt.figure(figsize=(6, 4))
        if min(beds) > 300 and (max(beds) - min(beds)) < min(beds) / 3:
            bax = brokenaxes(ylims=((0, 0.005 * max(beds) * rescale),
                                    (0.95 * min(beds) * rescale,
                                     1.02 * max(beds) * rescale)),
                             hspace=0.08)
            bax.set_ylabel(ylabel, labelpad=50)
        else:
            bax = fig.add_subplot(111)
            bax.set_ylim(0, 1.1 * max(beds) * rescale)
            bax.set_ylabel(ylabel)

        bax.bar(dates, beds * rescale, width=0.18, color=NHSblue)

        xup = int(np.ceil(max(dates))) + 1
        xdown = int(np.floor(min(dates)))
        xint = range(xdown, xup,
                     2 * (xup - xdown > 5) + 1 * (xup - xdown <= 5))

        bax.set_xticks(xint)

    return fig
Esempio n. 14
0
def test_log():
    fig = plt.figure(figsize=(5, 5))
    bax = brokenaxes(
        xlims=((1, 500), (600, 10000)),
        ylims=((1, 500), (600, 10000)),
        hspace=0.15,
        xscale="log",
        yscale="log",
    )

    x = np.logspace(0.0, 4, 100)
    bax.loglog(x, x, label="$y=x=10^{0}$ to $10^{4}$")

    bax.legend(loc="best")
    bax.grid(axis="both", which="major", ls="-")
    bax.grid(axis="both", which="minor", ls="--", alpha=0.4)
    bax.set_xlabel("x")
    bax.set_ylabel("y")
Esempio n. 15
0
def plot_computation_time():

    readdir = Path("results/computation_time")
    reps, nums = ["single", "ten", "hundred", "thousand"], [1, 10, 100, 1000]
    mins = ["5min", "30min"]

    no_jit = []
    for rep in reps:
        with open(readdir / "5min" / ("no-jit-%s.csv" % rep)) as f:
            no_jit.append(float(f.read()))

    jit = []
    for rep in reps:
        with open(readdir / "5min" / ("jit-%s.csv" % rep)) as f:
            jit.append(float(f.read()))

    jit_parallel = []
    for rep in reps:
        with open(readdir / "5min" / ("jit-parallel-%s.csv" % rep)) as f:
            jit_parallel.append(float(f.read()))

    labels = ["n=1", "n=10", "n=100", "n=1000"]
    colors = ["tab:blue", "tab:orange", "tab:green", "tab:red"]
    fig = plt.figure()
    sns.set_style("whitegrid")
    bax = brokenaxes(ylims=((0, 4.9), (30, 32)), hspace=0.1)
    for i in range(4):
        bax.bar(
            [i, i + 5, i + 10],
            [no_jit[i], jit[i], jit_parallel[i]],
            color=colors[i],
            label=labels[i],
        )

    # bax.grid(alpha=0.3)
    bax.legend()
    bax.set_ylabel("Time (s)")
    bax.set_xticks([2, 6, 10])
    bax.set_xticklabels(
        labels=["", "", "No jit", "", "Jit", "", "", "Jit parallel"])

    plt.savefig(readdir / "computation_time.pdf")
Esempio n. 16
0
def make_plot():
    x = np.linspace(0, 5 * 2 * np.pi, 300)
    y1 = np.sin(x) * 100
    y2 = np.sin(x + np.pi) * 5 + 90
    y3 = 30 * np.exp(-x) - 50
    y4 = 90 + (1 - np.exp(6 / x))

    bax = brokenaxes(ylims=[(-100, 0), (80, 100)],
                     xlims=[(0, 5), (10, 30)],
                     height_ratios=[1, 3],
                     width_ratios=[3, 5])

    bax.plot(x, y1, label="Big sin")
    bax.plot(x, y2, label="Small sin")
    bax.plot(x, y3, label="Exponential 1")
    bax.plot(x, y4, '--', label="Exponential 2")

    bax.legend(loc="lower right")
    bax.set_title("Example for different scales for the x and y axis")

    return bax
Esempio n. 17
0
def plot_cluster_stat(tab, feature, clusters=(0,1), fig_size=(2.5,2), xticks=None, capsize=8, plot_box=False, 
                      ylabel=None, to_save="", signif=None, 
                      brokenaxes_dict=None, **kwargs):
    """Plot bar plot of feature for 2 clusters.
    Parameters:
    tab: DataFrame. Should contain columns {`feature`, 'cluster'}.
    feature: String. A column in `tab`.
    capsize: cap size of errorbar. Default 8 points.
    plot_box: Draw boxplot instead of barplot with errorbar.
    ylabel: ylabel.
    to_save: filename to save.
    signif: significant marker, default: None.
    brokenaxes_dict: Dictionary. Parameters passed to `brokenaxes()`.
                    If None, not draw broken axes. Default: None.
    **kwargs: other parameters passed to `matplotlib.pyplot.bar()` or `matplotlib.pyplot.boxplot()`."""
    plt.figure(figsize=fig_size)
    if brokenaxes_dict is None:
        ax = plt.gca()
    else:
        ax = brokenaxes(**brokenaxes_dict)
    if plot_box:
        x = [ind+1 for ind, _ in enumerate(clusters)]
        y = [tab[tab['cluster']==c][feature].dropna().values for c in clusters]
        box_prop=ax.boxplot(y, **kwargs)
    else:
        x = [ind for ind, _ in enumerate(clusters)]
        y = [np.nanmean(tab[tab['cluster']==c][feature]) for c in clusters]
        err = [sem(tab[tab['cluster']==c][feature], nan_policy='omit') for c in clusters]
        ax.bar(x, y, yerr=err, capsize=capsize, **kwargs)
    if xticks is None:
        xticks = ['cluster {}'.format(c+1) for c in clusters]
    plt.xticks(x, xticks)
    if ylabel is None:
        ylabel=feature
    plt.ylabel(ylabel)
    plt.tight_layout()
    if bool(to_save):
        to_save_figure(to_save)
def DrawFigure(xvalues, yvalues, legend_labels, x_label, y_label, x_min, x_max, y_min, y_max, filename, allow_legend):
    # you may change the figure size on your own.
    fig = plt.figure(figsize=(8, 3))
    bax = brokenaxes(xlims=((1, 1000), (5000, 10000)), hspace=.05)

    FIGURE_LABEL = legend_labels

    if not os.path.exists(FIGURE_FOLDER):
        os.makedirs(FIGURE_FOLDER)

    x_values = xvalues
    y_values = yvalues

    lines = [None] * (len(FIGURE_LABEL))
    for i in range(len(y_values)):
        bax.plot(x_values, y_values[i], label=FIGURE_LABEL[i])
    bax.loglog(x, x)
    # sometimes you may not want to draw legends.
    if allow_legend == True:
        bax.legend(loc="best")

    plt.savefig(FIGURE_FOLDER + "/" + filename + ".eps", bbox_inches='tight', format='eps')
    ConvertEpsToPdf(FIGURE_FOLDER + "/" + filename)
Esempio n. 19
0
def test_datetime():
    fig = plt.figure(figsize=(5, 5))
    xx = [datetime.datetime(2020, 1, x) for x in range(1, 20)]

    yy = np.arange(1, 20)

    bax = brokenaxes(
        xlims=(
            (
                datetime.datetime(2020, 1, 1),
                datetime.datetime(2020, 1, 3),
            ),
            (
                datetime.datetime(2020, 1, 6),
                datetime.datetime(2020, 1, 20),
            ),
        )
    )

    bax.plot(xx, yy)
    fig.autofmt_xdate()

    [x.remove() for x in bax.diag_handles]
    bax.draw_diags()
                                                                     55320),
                    (55510, 55516), (55698, 55703), (55874, 55875), (55893,
                                                                     55895),
                    (55900, 55901), (56776, 56781), (57179, 57187.5), (57334,
                                                                       57337),
                    (57364, 57365), (57370, 57371), (57514, 57515), (57518,
                                                                     57522.5),
                    (57527.5, 57530.5), (57533.5, 57534.5), (57695, 57698.5),
                    (57705, 57706), (57876.5, 57878), (57880.5, 57881.5),
                    (58076, 58077.5), (58239.5, 58241), (58247.5, 58249),
                    (58443, 58444.5), (58609, 58610), (58816, 58817))

            fig_brkax = plt.figure(figsize=(60, 8))
            bax = brokenaxes(xlims=lims,
                             wspace=0.2,
                             tilt=90,
                             diag_color='red',
                             d=0.0015)
            bax.errorbar(data_lc['MJD'].values,
                         data_lc['RATE'].values,
                         data_lc['ERROR'].values,
                         linestyle='',
                         markersize=0.05,
                         marker='.')
            my_ticks = [
                51689, 51690, 51849, 51851, 51861, 51864, 52037, 52038, 52398,
                52400, 52582, 52584, 52592, 52594, 52609, 52612, 52791, 52793,
                52797, 52798, 52957, 52959, 52983, 52985, 53131, 53132, 53681,
                53685, 53854, 53856, 53883, 53884, 54074, 54075, 54228, 54231,
                54423, 54426, 54593, 54594, 54617, 54618, 54792, 54794, 54976,
                54977, 55151, 55153, 55319, 55320, 55510, 55516, 55698, 55703,
def main(inargs):
    """Run the program."""

    df = pd.read_csv(inargs.infile)
    #df.set_index(df['model'] + ' (' + df['run'] + ')', drop=True, inplace=True)
    df.set_index(df['model'], drop=True, inplace=True)
    fig = plt.figure(figsize=[18.5, 21])  # width, height
    gs = GridSpec(3, 2)

    # EEI conservation
    eei_ax = fig.add_subplot(gs[0, 0])
    plot_broken_comparison(eei_ax,
                           df,
                           '(a) planetary energy imbalance',
                           'netTOA (J yr-1)',
                           'thermal OHC (J yr-1)',
                           'W m-2',
                           legend=True)
    handles, labels = get_legend_info(
        eei_ax, df[['netTOA (J yr-1)', 'thermal OHC (J yr-1)']])

    # Ocean energy conservation
    xlims = [(-41.05, -40.82), (-0.55, 0.71)]
    ylims = [(-0.55, 0.66)]
    wspace = hspace = 0.08
    ocean_energy_ax = brokenaxes(xlims=xlims,
                                 ylims=ylims,
                                 hspace=hspace,
                                 wspace=wspace,
                                 subplot_spec=gs[0, 1],
                                 d=0.0)
    #ocean_energy_ax = fig.add_subplot(gs[0, 1])
    plot_broken_comparison(ocean_energy_ax,
                           df,
                           '(b) ocean energy conservation',
                           'hfdsgeou (J yr-1)',
                           'thermal OHC (J yr-1)',
                           'W m-2',
                           xpad=25,
                           ypad=45,
                           broken=True)
    handles, labels = update_legend_info(
        ocean_energy_ax, df[['hfdsgeou (J yr-1)', 'thermal OHC (J yr-1)']],
        handles, labels)

    # Ocean mass conservation
    xlims = [(-7, 4), (472, 474), (492, 495)]
    ylims = [(-0.7, 0.25)]
    hspace = 0.1
    ocean_mass_ax = brokenaxes(xlims=xlims,
                               ylims=ylims,
                               hspace=hspace,
                               subplot_spec=gs[1, 0],
                               d=0.0)
    #ocean_mass_ax = fig.add_subplot(gs[1, 0])
    plot_broken_comparison(ocean_mass_ax,
                           df,
                           '(c) ocean mass conservation',
                           'wfo (kg yr-1)',
                           'masso (kg yr-1)',
                           'kg yr-1',
                           scale_factor=-15,
                           broken=True,
                           xpad=30,
                           ypad=50)
    handles, labels = update_legend_info(
        ocean_mass_ax, df[['wfo (kg yr-1)', 'masso (kg yr-1)']], handles,
        labels)

    # Salt conservation
    xlims = [(-0.73, 0.35), (3.55, 3.7)]
    ylims = [(-0.8, 3.1)]
    hspace = wspace = 0.1
    salt_ax = brokenaxes(xlims=xlims,
                         ylims=ylims,
                         hspace=hspace,
                         wspace=wspace,
                         subplot_spec=gs[1, 1],
                         d=0.0)
    #salt_ax = fig.add_subplot(gs[1, 1])
    plot_broken_comparison(salt_ax,
                           df,
                           '(d) salt conservation',
                           'masso (kg yr-1)',
                           'soga (kg yr-1)',
                           'kg yr-1',
                           scale_factor=-15,
                           xpad=30,
                           ypad=40,
                           broken=True)
    handles, labels = update_legend_info(
        salt_ax, df[['masso (kg yr-1)', 'soga (kg yr-1)']], handles, labels)

    # Atmosphere mass conservation
    atmos_mass_ax = fig.add_subplot(gs[2, :])
    plot_broken_comparison(atmos_mass_ax,
                           df,
                           '(e) atmospheric mass conservation',
                           'massa (kg yr-1)',
                           'wfa (kg yr-1)',
                           'kg yr-1',
                           scale_factor=-12,
                           ypad=20)
    handles, labels = update_legend_info(atmos_mass_ax, df[['wfa (kg yr-1)']],
                                         handles, labels)

    fig.legend(handles, labels, loc='center left', bbox_to_anchor=(0.815, 0.5))
    plt.tight_layout(rect=(0, 0, 0.8, 1))

    for variable, data in cmip6_data_points.items():
        record_quartiles(variable, data, 'cmip6')
    for variable, data in cmip5_data_points.items():
        record_quartiles(variable, data, 'cmip5')

    plt.savefig(inargs.outfile, dpi=400)
    log_file = re.sub('.png', '.met', inargs.outfile)
    log_text = cmdprov.new_log(git_repo=repo_dir, extra_notes=quartiles)
    cmdprov.write_log(log_file, log_text)
Esempio n. 22
0
def generate_epsilon_vs_cost(funcs, name):

    x_epsilons_raw = list()
    y_costs_raw = list()
    x_epsilons_raw_wide = list()
    y_costs_raw_wide = list()
    x_epsilons_ml2 = list()
    y_costs_ml2 = list()
    x_epsilons_ml2_wide = list()
    y_costs_ml2_wide = list()
    x_epsilons_ml = list()
    y_costs_ml = list()
    x_epsilons_lib = list()
    y_costs_lib = list()

    for f in funcs:
        if "raw" in f["cname"] and "wide" in f["cname"]:
            x_epsilons_raw_wide.append(f["epsilon"])
            y_costs_raw_wide.append(f["cost"])
        elif "raw" in f["cname"]:
            x_epsilons_raw.append(f["epsilon"])
            y_costs_raw.append(f["cost"])
        elif "ml2" in f["cname"] and "wide" in f["cname"]:
            x_epsilons_ml2_wide.append(f["epsilon"])
            y_costs_ml2_wide.append(f["cost"])
        elif "ml2" in f["cname"]:
            x_epsilons_ml2.append(f["epsilon"])
            y_costs_ml2.append(f["cost"])
        elif "ml" in f["cname"]:
            x_epsilons_ml.append(f["epsilon"])
            y_costs_ml.append(f["cost"])
        else:
            x_epsilons_lib.append(f["epsilon"])
            y_costs_lib.append(f["cost"])

    all_costs = sorted([f["cost"] for f in funcs])
    crlibm = all_costs[-1]
    next_max = all_costs[-2]

    all_eps = sorted([f["epsilon"] for f in funcs])
    max_eps = all_eps[-1]

    fig = plt.figure()
    bax = brokenaxes(xlims=None,
                     ylims=((0, next_max+1), (crlibm-1, crlibm+1)),
		     hspace=.05,
                     d=0)

    bax.axhline(crlibm-1, color="black", linestyle="--", linewidth=4)

    bax.scatter(x_epsilons_raw,      y_costs_raw,      color="blue",   alpha=0.7, s=100)
    bax.scatter(x_epsilons_raw_wide, y_costs_raw_wide, color="cyan",   alpha=0.7, s=100)
    bax.scatter(x_epsilons_ml2,      y_costs_ml2,      color="orange", alpha=0.7, s=100)
    bax.scatter(x_epsilons_ml2_wide, y_costs_ml2_wide, color="orange", alpha=0.7, s=100)
    bax.scatter(x_epsilons_ml,       y_costs_ml,       color="purple", alpha=0.7, s=100)
    bax.scatter(x_epsilons_lib,      y_costs_lib,      color="green",  alpha=0.7, s=100)


    bax.set_xscale('log')
    xmin, xmax = bax.set_xlim()
    bax.set_xlim(xmax[1], xmin[0])

    if True:
        bax.axis("off")
        [a.set_ticks([]) for a in bax.get_xaxis()]
        [a.set_ticks([]) for a in bax.get_yaxis()]

    fig.savefig("{}.png".format(name.replace(" ", "_")),
                bbox_inches="tight",
                pad_inches=0)
Esempio n. 23
0
"""
Basic usage
===========

This example presents the basic usage of brokenaxes

"""


import matplotlib.pyplot as plt
from brokenaxes import brokenaxes
import numpy as np

fig = plt.figure(figsize=(5,2))
bax = brokenaxes(xlims=((0, .1), (.4, .7)), ylims=((-1, .7), (.79, 1)), hspace=.05)
x = np.linspace(0, 1, 100)
bax.plot(x, np.sin(10 * x), label='sin')
bax.plot(x, np.cos(10 * x), label='cos')
bax.legend(loc=3)
bax.set_xlabel('time')
bax.set_ylabel('value')
Esempio n. 24
0
#2º)FIGURES PLOT

#2D PLOT
#fig, ax = plt.subplots(2, sharex=True)        #Create figure with 2 subplots
#fig.canvas.set_window_title('Spatiotemporal')                 #Set Figure Window Title
#fig.suptitle('Spatiotemporal', fontsize = 14)
ms = 20
lw = 3.5

# FIGURE 1: DUTY FACTOR
#Create figure
fig = plt.figure()
fig.canvas.set_window_title('DUTY FACTOR')
fig.suptitle('Duty Factor', fontsize=20)
bax = brokenaxes(ylims=((0, 10), (40, 80)))

# Calculate Polynomial Parameters of 2º Degree

X_Duty_Joelho = Duty_Joelho_Speed_Column  #Speed X
Y_Duty_Joelho = Duty_Joelho_All_Speed_Mean  #Duty Factor Y
Z_2_Duty_Joelho, error_2_Duty_Joelho, _, _, _ = np.polyfit(X_Duty_Joelho,
                                                           Y_Duty_Joelho,
                                                           2,
                                                           full=True)
f_2_Duty_Joelho = np.poly1d(Z_2_Duty_Joelho)
# calculate new x's and y's
X_2_Duty_Joelho = np.linspace(min(X_Duty_Joelho), max(X_Duty_Joelho), 50)
Y_2_Duty_Joelho = f_2_Duty_Joelho(X_2_Duty_Joelho)

X_Duty_Quadril = Duty_Quadril_Speed_Column  #Speed X
Esempio n. 25
0
# 横坐标
x0 = np.arange(0,100)
x1 = np.arange(0,100)
x2 = np.arange(0,100)
x3 = np.arange(0,100)
x4 = np.arange(0,100)
x5 = np.arange(0,100)
x6 = np.arange(0,100)

# 图的大小
fig = plt.figure(dpi=300)

# 切切切

# bax = brokenaxes(xlims=((0, .1), (.4, .7)), ylims=((-1, .7), (.79, 1)), hspace=.05, despine=False)
bax1 = brokenaxes(ylims=((0.3, 1),(6.5,6.8), (8.4, 8.9)))  # hspace 间隔图上显示大小
bax1.plot(x0, pts0,label='DP-DNN')
bax1.plot(x1, pts1,label='MNN')
bax1.plot(x2, pts2,label='MI-NN')
bax1.plot(x3, pts3,label='LSTM')
bax1.plot(x4, pts4,label='GWR')
bax1.plot(x5, pts5,label='B-OLSR')
bax1.plot(x6, pts6,label='EN')

bax1.legend(loc='center left', bbox_to_anchor=(0.2, 1.12),ncol=3)
bax1.set_xlabel('实验次数',fontproperties=myfont)
bax1.set_ylabel('RE')


plt.show()
Esempio n. 26
0
def make_plot(model_number,
              logx=None,
              logy=None,
              withtext=None,
              stdout=False,
              brokenx=None,
              Z_2=None,
              xcut=None,
              r_pu=None,
              standardlines=True):
    '''
    withtext: includes summary text from integration on plot

    stdout: write "withtext" text to stdout

    xcut: mainly for model #1, overplotted over different axes

    standardlines:
        if True: plots "inferred", "true (selected)", and "true (single)" rates.
        if False, plots "inferred", "frac (single)", "frac (primary)", "frac
            (secondary)" and "true (single)".
        by default, True
    '''

    assert Z_2 > -1
    Z_0 = 0.5

    plt.close('all')

    # Make summary plot
    fname = '../data/numerics/results_model_{:d}_Zsub2_{:.2f}_rpu_{:.1f}.out'.format(
        model_number, Z_2, r_pu)

    df = pd.read_csv(fname)

    if not brokenx:
        f, ax = plt.subplots(figsize=(4, 4))
    else:
        #cf https://github.com/bendichter/brokenaxes/blob/master/brokenaxes.py
        f = plt.figure(figsize=(4, 4))
        bigax = brokenaxes(
            xlims=((0.695, .715), (.985, 1.005)),
            d=0.0,
            #d=0.02,
            tilt=87.5,
            hspace=.0,
            despine=True)
        ax = bigax

    if model_number == 3 or model_number == 4:
        xvals = np.append(0, df['bin_left'])
        ytrueselected = np.append(0, df['true_Λ'])
        ytruesingle = np.append(0, df['true_single_Λ'])
        yinferred = np.append(0, df['inferred_Λ'])
    elif model_number == 1 or model_number == 2:
        xvals = np.append(df['bin_left'], [1, 1.1])
        ytrueselected = np.append(df['true_Λ'], [0, 0])
        ytruesingle = np.append(df['true_single_Λ'], [0, 0])
        yinferred = np.append(df['inferred_Λ'], [0, 0])

    colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728']

    lambdastr = 'apparent'  #r'$\Lambda_{\mathrm{a}}(r_{\mathrm{a}})$'
    ax.step(xvals,
            yinferred,
            where='post',
            label=lambdastr,
            c=colors[0],
            zorder=2)

    if standardlines:

        #ax.step(xvals, ytrueselected, where='post', label='true (selected)',
        #        c=colors[1])

        ax.step(
            xvals,
            ytruesingle,
            where='post',
            label='true',  #'$\Lambda(r)$',
            linestyle='--',
            c=colors[1],
            zorder=3)

    elif not standardlines:

        yfracsingle = np.append(0, df['frac_inferred_single_Λ'])
        yfracprimary = np.append(0, df['frac_inferred_primary_Λ'])
        yfracsecondary = np.append(0, df['frac_inferred_secondary_Λ'])

        ax.step(xvals,
                yfracsingle,
                where='post',
                label='frac (single)',
                linestyle=':',
                c=colors[0])
        ax.step(xvals,
                yfracprimary,
                where='post',
                label='frac (primary)',
                linestyle='-.',
                c=colors[0])
        ax.step(xvals,
                yfracsecondary,
                where='post',
                label='frac (secondary)',
                linestyle='--',
                c=colors[0])
        ax.step(xvals,
                ytruesingle,
                where='post',
                label='true (single)',
                linestyle='-',
                c=colors[1])

    if brokenx:
        leg = ax.legend(loc='upper left', fontsize='medium')
        leg.get_frame().set_linewidth(0.)
        leg.get_frame().set_facecolor('none')
    else:
        ax.legend(loc='best', fontsize='medium')

    ax.set_xlabel('planet radius', fontsize='large')

    ax.set_ylabel('number of planets per star', fontsize='large')

    if logx:
        ax.set_xscale('log')
    if logy:
        ax.set_yscale('log')

    if logx or logy:
        outname = '../results/occ_rate_vs_radius_logs_model_'+\
                 repr(model_number)
    else:
        outname = '../results/occ_rate_vs_radius_model_'+\
                 repr(model_number)
    if brokenx:
        outname += '_brokenx'

    if not standardlines:
        outname += '_fraclines'

    if not brokenx:
        if (model_number == 1 or model_number == 2) and not (logx or logy):
            ax.set_xlim([0.5, 1.02])
        elif (model_number == 1 or model_number == 2) and (logx or logy):
            ax.set_xlim([-0.02, 1.02])

    if xcut:
        ax.set_xlim([-0.3, 5.3])

    if model_number == 3:
        # Assess HJ rate difference.
        from scipy.integrate import trapz

        #Howard 2012 boundary #1 and boundary #2:
        for lower_bound in [5.6, 8]:
            inds = df['bin_left'] > lower_bound
            #Λ_HJ_true = trapz(df[inds]['true_Λ'], df[inds]['bin_left'])
            #Λ_HJ_inferred = trapz(df[inds]['inferred_Λ'], df[inds]['bin_left'])
            Λ_HJ_true_sel = np.sum(df[inds]['true_Λ'])
            Λ_HJ_true_sing = np.sum(df[inds]['true_single_Λ'])
            Λ_HJ_inferred = np.sum(df[inds]['inferred_Λ'])

            #Λ_true = trapz(df['true_Λ'], df['bin_left'])
            #Λ_inferred = trapz(df['inferred_Λ'], df['bin_left'])
            Λ_true_sel = np.sum(df['true_Λ'])
            Λ_true_sing = np.sum(df['true_single_Λ'])
            Λ_inferred = np.sum(df['inferred_Λ'])

            txt = \
            '''
            with $r>${:.1f}$R_\oplus$,
            selected $\Lambda$_HJ_true:      {:.4f} planets per star
            single   $\Lambda$_HJ_true:      {:.4f} planets per star
            $\Lambda$_HJ_inferred:  {:.4f} planets per star
            true(selected)/inferred:  {:.2f}.
            true(single)/inferred:  {:.2f}.

            Integrated over all $r$,
            selected $\Lambda$_true:         {:.3f} planets per star
            single $\Lambda$_true:           {:.3f} planets per star
            $\Lambda$_inferred:     {:.3f} planets per star
            true(selected)/inferred:  {:.2f}.
            true(single)/inferred:  {:.2f}.
            '''.format(
            lower_bound,
            Λ_HJ_true_sel,
            Λ_HJ_true_sing,
            Λ_HJ_inferred,
            Λ_HJ_true_sel/Λ_HJ_inferred,
            Λ_HJ_true_sing/Λ_HJ_inferred,
            Λ_true_sel,
            Λ_true_sing,
            Λ_inferred,
            Λ_true_sel/Λ_inferred,
            Λ_true_sing/Λ_inferred,
            )
            if stdout:
                print(txt)

        if withtext:
            ax.text(0.96,
                    0.5,
                    txt,
                    horizontalalignment='right',
                    verticalalignment='center',
                    transform=ax.transAxes,
                    fontsize='x-small')
            outname += '_withtext'

        else:
            txt = '$Z_2/Z_0 =\ ${:.1f}'.format(Z_2 / Z_0)
            ax.text(0.96,
                    0.5,
                    txt,
                    horizontalalignment='right',
                    verticalalignment='center',
                    transform=ax.transAxes,
                    fontsize='x-small')

        if isinstance(Z_2, float) or isinstance(Z_2, int):
            outname += '_Zsub2_{:.2f}'.format(Z_2)

        if isinstance(r_pu, float) or isinstance(r_pu, int):
            outname += '_rpu_{:.1f}'.format(r_pu)

    if xcut:
        outname += '_xcut'

    f.savefig(outname + '.pdf', bbox_inches='tight')
Esempio n. 27
0
            loc=0,
            borderaxespad=0,
            fontsize=7)

# -----------------------------------
# 4. Plot BIC- based model comparison
# -----------------------------------

# Prepare plot
gs02 = gridspec.GridSpecFromSubplotSpec(2,
                                        6,
                                        subplot_spec=gs[2:4, 0:6],
                                        wspace=2,
                                        hspace=0.5)
ax_0 = brokenaxes(ylims=((-2.2, -2.11), (-1.225, -1.05)),
                  hspace=.15,
                  d=0.01,
                  subplot_spec=gs02[0, 0:2])

# Plot cumulated BIC's
ax_0.bar(0, BIC_A0, color='k', alpha=1, edgecolor='k')
ax_0.bar(1, BIC_A1, color=blue_1)
ax_0.bar(2, BIC_A2, color=blue_2)
ax_0.bar(3, BIC_A3, color=blue_3)
ax_0.bar(4, BIC_A4, color=green_1)
ax_0.bar(5, BIC_A5, color=green_2)
ax_0.bar(6, BIC_A6, color=green_3)
ax_0.set_ylabel('Sum BIC')
ax_0.set_xticks([0, 1, 2, 3, 4, 5, 6])
rc('text', usetex=True)
f.text(0.08,
       0.51,
Esempio n. 28
0
def pltfig(all_loss, all_acc):
    netlist = [
        'mobilenet', 'resnet', 'shufflenet', 'squeezenet', 'alexnet',
        'densenet', 'googlenet', 'MNASNet', 'VGG'
    ]
    ##### 不同网络间的图像
    id = 0
    for temploss in all_loss:
        id += 1
        ### 画loss图
        plt.figure()
        # for j in range(len(temploss)):
        #     plt.plot(list(range(300)),np.array(list(map(float,temploss[j][1:]))))
        #     # plt.draw()
        bax = brokenaxes(ylims=((-0.001, .04), (.06, .07)),
                         hspace=.05,
                         despine=False)
        for j in range(len(temploss)):
            # plt.plot(range(0,len(Alllos[i])), Alllos[i], label=netlist[i])
            # plt.legend()
            bax.plot(list(range(300)),
                     np.array(list(map(float, temploss[j][1:]))),
                     label=netlist[j])
            bax.legend()
        # plt.xlabel('Loss vs. iters')
        # plt.ylabel('Loss')
        bax.set_xlabel('Loss vs. iters', labelpad=2)
        bax.set_ylabel('Loss')
        plt.savefig(
            os.path.join(
                '/media/liqiang/windata/project/classification/plugin/newresult',
                'ex' + str(id) + 'train_' + "loss.jpg"))
        plt.close()
        ### 画acc图
    ida = 0
    for tempacc in all_acc:
        ida += 1
        ### 画loss图
        plt.figure()
        # for j in range(len(temploss)):
        #     plt.plot(list(range(300)),np.array(list(map(float,temploss[j][1:]))))
        #     # plt.draw()
        for j in range(len(tempacc)):
            # plt.plot(range(0,len(Alllos[i])), Alllos[i], label=netlist[i])
            # plt.legend()
            plt.plot(list(range(300)),
                     np.array(list(map(float, tempacc[j][1:]))),
                     label=netlist[j])
            plt.legend()
        # plt.xlabel('Loss vs. iters')
        # plt.ylabel('Loss')
        plt.xlabel('Accuracy vs. iters')
        plt.ylabel('Accuracy')
        plt.savefig(
            os.path.join(
                '/media/liqiang/windata/project/classification/plugin/newresult',
                'ex' + str(ida) + 'train_' + "acc.jpg"))
        plt.close()
    #### 同一网络图像
    ### 画loss图
    for m in range(9):
        plt.figure()
        k = 0
        for temploss in all_loss:
            k += 1
            # for j in range(len(temploss)):
            #     plt.plot(list(range(300)),np.array(list(map(float,temploss[j][1:]))))
            #     # plt.draw()
            plt.plot(list(range(300)),
                     np.array(list(map(float, temploss[m][1:]))),
                     label='exp' + str(k))
            plt.legend(loc='upper right')
            # plt.xlabel('Loss vs. iters')
            # plt.ylabel('Loss')
        plt.xlabel('Loss vs. iters')
        plt.ylabel('Loss')
        plt.title(netlist[m])
        plt.savefig(
            os.path.join(
                '/media/liqiang/windata/project/classification/plugin/newresult',
                netlist[m] + '_train_' + "loss.jpg"))
        plt.close()
    ### acc
    for n in range(9):
        plt.figure()
        l = 0
        for tempacc in all_acc:
            l += 1
            plt.plot(list(range(300)),
                     np.array(list(map(float, tempacc[n][1:]))),
                     label='exp' + str(l))
            plt.legend()
            # plt.xlabel('Loss vs. iters')
            # plt.ylabel('Loss')
        plt.xlabel('Accuracy vs. iters')
        plt.ylabel('Accuracy')
        plt.title(netlist[n])
        plt.savefig(
            os.path.join(
                '/media/liqiang/windata/project/classification/plugin/newresult',
                netlist[n] + '_train_' + "acc.jpg"))
        plt.close()
Esempio n. 29
0
                data[dataset]["baseline_acc"].append((axs, ays))

import pdb; pdb.set_trace()
# latexify(fig_width=2.25, fig_height=1.5)
from matplotlib import rc
rc("text", usetex=False)
for dataset in datasets:
    fig = plt.figure()
    # max1x, max1y = data[dataset]["max1"]
    # max2x, max2y = data[dataset]["max2"]
    max2x = 0.7
    max2y = 0.7
    max1x = 1.0
    max1y = 1.0
    ax = brokenaxes(xlims=((-.05, max2x + .05), (max1x - .1, max1x + .15)),
                    ylims=((-.05, max2y + .05), (max1y - .1, max1y + .1)),
                    hspace=0.05, wspace=0.05, fig=fig)
    ax.set_xlabel(r"task 1 loss")
    ax.set_ylabel(r"task 2 loss")
    for i, (xs, ys) in enumerate(data[dataset]["baseline_loss"]):
        label = "baseline\nloss" if i == 0 and dataset == "fashion" else ""
        ax.plot(xs, ys, lw=2, alpha=0.4, c='k')

    colors = []
    for i, (r, l) in enumerate(zip(data[dataset]["rs"],
                                   data[dataset]["rlens"])):
        label = r"$r^{-1}$ Ray" if i == 0 and dataset == "fashion" else ""
        r_inv = np.sqrt(1 - r**2)
        lines = ax.plot([0, .9 * l * r_inv[0]], [0, .9 * l * r_inv[1]],
                        lw=1, alpha=0.5, ls='--', dashes=(10, 2), label=label)
        colors.append(lines[0][0].get_color())
def train():
    # net = alexnet()
    # print(net)
    # use_gpu = True
    
    # if use_gpu:
    #     net = net.cuda()
    # x, y = Generations(200)
     
    torch_device = torch.device('cuda')

    # train_x, train_y, test_x, test_y, val_x, val_y = getData()
    #load net
    layer = 1   #channels
    use_gpu = True #是否使用gpu
    pretrained = False #是否使用与训练模型
    batch_size = 30

    netlist = ['mobilenet','resnet','shufflenet','squeezenet','alexnet','densenet','googlenet','mnastnet','vgg16']
    # netlist = ['mobilenet','resnet','shufflenet','squeezenet','alexnet','densenet','googlenet','mnastnet']
    # netlist = ['mobilenet','resnet','vgg16']
    # netlist = ['googlenet']
    Allacc = []
    Alllos = []
    val_Allacc = []
    val_Alllos = []
    test_Allacc = []
    test_Alllos = []
    for netname in netlist:
        if netname=='mobilenet':
            net = modelnet.mobilenet(layer,use_gpu,pretrained)
        elif netname=='resnet':
            net = modelnet.resnet(layer,use_gpu,pretrained)
        elif netname=='shufflenet':
            net = modelnet.shufflenet(layer,use_gpu,pretrained)
        elif netname=='squeezenet':
            net = modelnet.squeezenet(layer,use_gpu,pretrained)
        elif netname=='alexnet':
            net = modelnet.alexnet(layer,use_gpu,pretrained)
        elif netname=='densenet':
            net = modelnet.densenet(layer,use_gpu,pretrained)
        elif netname=='googlenet':
            net = modelnet.googlenet(layer,use_gpu,pretrained)
        elif netname=='mnastnet':
            net = modelnet.mnasnet(layer,use_gpu,pretrained)
        elif netname=='vgg16':
            net = modelnet.vgg16(layer,use_gpu,pretrained)
        # print(netname)
        print(net)
        # Loss and Optimizer
        criterion = torch.nn.CrossEntropyLoss()
        optimizer = torch.optim.Adam(net.parameters(),lr=1e-3)
        # optimizer = torch.optim.Adam(net.classifier.parameters())
        # Train the model
        y0 = np.zeros(3000,dtype=np.int)
        y1 = np.ones(3000, dtype=np.int)
        y2 = np.ones(3000, dtype=np.int)*2
        y_label = np.concatenate((y0,y1,y2),axis=0)
        scale = 0
        loc   = 1
        
        ##生成测试图像
        maxacc = []
        Accuracy_list = []
        Loss_list     = []
        val_Accuracy_list = []
        val_Loss_list     = []
        test_Accuracy_list = []
        test_Loss_list     = []
        tempacc = 0
        num_i = 4
        for epoch in range(1):
            # optimizer = torch.optim.Adam(net.parameters())
            #打乱数据和标签
            num = random.randint(1,2000)
            random.seed(num)
            random.shuffle(y_label)
            index_in_epoch = 0
            running_loss = 0.0
            running_correct = 0
            batch = 0
            for iters in range(int(y_label.__len__()/batch_size)):
                batch += 1
                mask = np.random.normal(size=(224,224), scale=scale, loc=loc) #loc表示均值,scale表示方差,size表示输出的size
                batch_x, batch_y, index_in_epoch = _next_batch(y_label, batch_size, index_in_epoch,mask,num_i)
                # for step, (inputs, labels) in enumerate(trainset_loader):
                # batch_xs = preprocess(batch_xs,layer)
                # batch_x = np.array([t.numpy() for t in batch_xs])
                # optimizer.zero_grad()  # 梯度清零                
                labels = batch_y.copy() 
 
                tempdata = np.reshape(batch_x,(batch_size, 1, 224, 224))
                batch_xx = torch.tensor(tempdata, dtype=torch.float)
                if use_gpu==True:
                    # batch_xx = batch_xx.to(torch_device)
                    batch_xx,labels = Variable(torch.tensor(batch_xx).cuda()), Variable(torch.tensor(labels).cuda())
                else:
                    batch_xx,labels = Variable(batch_xx), Variable(labels)
                optimizer.zero_grad()
                output = net(batch_xx)
                if netname=='googlenet':
                    if len(output)==3:
                        output = output.logits
                _,pred = torch.max(output.data, 1)
                # loss = criterion(output, onehotLab(labels, False))
                loss = criterion(output, labels)
                loss = loss.requires_grad_()
                loss.backward()
                optimizer.step()                
                running_loss += loss.data
                # running_loss += loss.item()
                running_correct += torch.sum(pred == labels)      
                if running_correct.item()/(batch_size*batch) > 0:
                    print("Batch {}, Train Loss:{:.6f}, Train ACC:{:.4f}".format(
                    batch, running_loss/(batch_size*batch), running_correct.item()/(batch_size*batch)))
                    # print('预测标签:{}, 真实标签:{}'.format(pred, labels))
                maxacc.append(running_correct.item()/(batch_size*batch))
                Accuracy_list.append(running_correct.item()/(batch_size*batch))
                Loss_list.append(running_loss/(batch_size*batch))
        
            '''
            print('#######################  运行验证集   ################')
            val_Accuracy, val_Loss = val_train(net,netname,criterion,mask,batch_size,use_gpu)
            #更新精度并保存模型
            if val_Accuracy - tempacc > 0:
                tempacc = val_Accuracy
                torch.save(net,os.path.join('/media/liqiang/windata/project/classification/plugin/model',netname+'_'+'net.pkl'))
            val_Accuracy_list.append(val_Accuracy)
            val_Loss_list.append(val_Loss)
            print('#######################  验证集结束   ################')
            print('#######################  运行测试集   ################')
            test_Accuracy, test_Loss = test_train(netname,criterion,mask,batch_size,use_gpu)
            test_Accuracy_list.append(test_Accuracy)
            test_Loss_list.append(test_Loss)      
            print('#######################  测试集结束   ################')  
            '''  
        #保存网络结构
        torch.save(net,os.path.join('/media/liqiang/windata/project/classification/plugin/model','ex4'+netname+'_'+'net.pkl'))        
        print('预测标签:{}, 真实标签:{}'.format(pred, labels))
        y1 = Accuracy_list
        y2 = Loss_list
        Allacc.append(y1)
        Alllos.append(y2)
        val_Allacc.append(val_Accuracy_list)
        val_Alllos.append(val_Loss_list)
        test_Allacc.append(test_Accuracy_list)
        test_Alllos.append(test_Loss_list)
        
    ###保存训练集训练曲线
    for i in range(len(netlist)):
        plt.plot(range(0,len(Allacc[i])), Allacc[i],label=netlist[i])        
        plt.legend()
    plt.xlabel('Accuracy vs. iters')
    plt.ylabel('Accuracy')
    plt.savefig(os.path.join('/media/liqiang/windata/project/classification/plugin/result','ex4'+'train_'+"accuracy.jpg"))
    plt.show()
    plt.close()
    fig = plt.figure()
    bax = brokenaxes(ylims=((-0.001, .04), (.06, .07)), hspace=.05, despine=False)
    for i in range(len(netlist)):
        # plt.plot(range(0,len(Alllos[i])), Alllos[i], label=netlist[i])
        # plt.legend()
        bax.plot(range(0,len(Alllos[i])), Alllos[i], label=netlist[i])
        bax.legend()
    # plt.xlabel('Loss vs. iters')
    # plt.ylabel('Loss')  
    bax.set_xlabel('Loss vs. iters')
    bax.set_ylabel('Loss')
    # plt.yscale('log')
    # plt.ylim([-0.01,0.06])         
    plt.savefig(os.path.join('/media/liqiang/windata/project/classification/plugin/result','ex4'+'train_'+"loss.jpg"))
    plt.show()
    plt.close()

    '''