fig, ax=plt.subplots()
plt.plot([],[], color = 'm', label = 'Nuclear', linewidth=5)
plt.plot([],[], color = 'y', label = 'Coal', linewidth=5)
plt.plot([],[], color = 'c', label = 'NG', linewidth=5)
plt.plot([],[], color = 'r', label = 'Other', linewidth=5)
plt.plot([],[], color = 'g', label = 'PV', linewidth=5)
plt.plot([],[], color = 'b', label = 'Wind', linewidth=5)
plt.plot([],[], color = 'k', label = 'Discharge', linewidth=5)
plt.plot(X,-Over_el, label = 'Surplus', linewidth=1)
plt.plot(X,negative_el, label = 'charge', linewidth=1)

ax.stackplot(X, Nuke_el, Coal_el ,  NG_el , Other_el , PV_el, Wind_el, positive_el, colors=['m','y','c','r', 'g', 'b','k'])
ax.plot(X, D_el, 'r--', linewidth=3)
ax.stackplot(X, negative_el,-Over_el, colors=['y','b'])


begin=3864
end=4032
spacing = 24
minorLocator = MultipleLocator(spacing)
ax.set_xlim([begin,end])
ax.set_xlabel('hour')
ax.set_ylabel('MWh/h')
ax.xaxis.set_minor_locator(minorLocator)
plt.xticks(np.arange(begin, end, 24))
plt.grid()
plt.title('Electricity Balance')
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.savefig('hourlybalance.png',bbox_inches='tight')
plt.show()
Exemplo n.º 2
0
#!/usr/bin/python
#-*-coding:utf-8-*-
import sys
import numpy as np
import simtool

import matplotlib
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
matplotlib.use('Agg')
print 'matplotlib.use("Agg")'
import matplotlib.pyplot as plt
xmajorLocator = MultipleLocator(5)  #将x主刻度标签设置为20的倍数
xmajorFormatter = FormatStrFormatter('%5d')  #设置x轴标签文本的格式
xminorLocator = MultipleLocator(0.5)  #将x轴次刻度标签设置为5的倍数

ymajorLocator = MultipleLocator(10)  #将y轴主刻度标签设置为0.5的倍数
ymajorFormatter = FormatStrFormatter('%10d')  #设置y轴标签文本的格式
yminorLocator = MultipleLocator(1)  #将此y轴次刻度标签设置为0.1的倍数


def getbinspdfcdf(sample_list):
    if len(sample_list) <= 0:
        return (0, ), (0, ), (0, ),
    bins = np.linspace(min(sample_list), max(sample_list), 100)
    pdf = np.histogram(sample_list, bins=bins, normed=False)[0]
    pdf = pdf * 1.0 / sum(pdf)
    cdf = [sum(pdf[:i]) for i in xrange(1, len(pdf) + 1)]
    return bins[1:], pdf, cdf


#ss: Simulation List
Exemplo n.º 3
0
ax.set(xlim=(0, 5000))
ax2.set(xlim=(0, 5000))
#ax2.set(xlim=(126, 128))
#ax.spines['right'].set_visible(False)
#ax2.spines['left'].set_visible(False)
ax.yaxis.tick_left()
#ax2.yaxis.tick_right()

ax.set_yscale('log')
ax.set_ylabel('Count\n(GMP)')
ax.set_xlabel('time (us)')
ax2.set_yscale('log')
ax2.set_ylabel('Count\n(libint)')
ax2.set_xlabel('time (us)')
ax.xaxis.set_minor_locator(MultipleLocator(500))
ax.tick_params(which='minor', length=8)
ax.tick_params(which='major', length=6)
ax2.xaxis.set_minor_locator(MultipleLocator(500))
ax2.tick_params(which='minor', length=8)
ax2.tick_params(which='major', length=6)

fig.set_size_inches(18.5, 10)
fig.tight_layout()

# Only edit the labels _now_
fig.canvas.draw()
labels = [item.get_text() for item in ax.get_xticklabels(which='both')]
labels[-1] = "longer"
ax.set_xticklabels(labels)
fig.canvas.draw()
Exemplo n.º 4
0
 freq = np.fft.rfftfreq(2**n, Ly) * 2**n
 cs = ax.imshow(kl_1[0:2**(n - 5), 0:2**(n - 4)],
                interpolation="none",
                cmap='Spectral',
                origin='lower',
                extent=[0, freq[2**(n - 4)], 0, freq[2**(n - 5)]],
                vmax=np.max(kl_1),
                vmin=0)
 ax.set(xlabel='Wavenumber y-axis [1/m]', ylabel='Wavenumber z-axis [1/m]')
 ax.set_title('FFT2 [Adimentionalized field units]')
 cbar = fig.colorbar(cs)
 plt.subplots_adjust(left=0.14,
                     bottom=0.2,
                     right=1,
                     top=0.9,
                     wspace=0.0,
                     hspace=0.0)
 #plt.show()
 ax.set_xlim(0, freq[2**(n - 4)])
 ax.set_ylim(0, freq[2**(n - 5)])
 ax.xaxis.set_minor_locator(AutoMinorLocator(3))
 ax.yaxis.set_minor_locator(AutoMinorLocator(3))
 ax.xaxis.set_major_locator(MultipleLocator(20))
 ax.yaxis.set_major_locator(MultipleLocator(20))
 # Turn grid on for both major and minor ticks and style minor slightly
 # differently.
 ax.grid(which='major', color='#CCCCCC', linestyle='-')
 ax.grid(which='minor', color='#CCCCCC', linestyle=':')
 #plt.grid()
 #plt.show()
 plt.savefig('Poiseuille_FFT2_Vort', dpi=600)
Exemplo n.º 5
0
plt.errorbar(x,
             y,
             xerr=0.04,
             yerr=0.005,
             ls="--",
             marker="o",
             color="k",
             fmt=None)
a = np.arange(min(x) - 10, max(x) + 10, 0.001)
p = np.poly1d(np.polyfit(x, y, 1))
print('Уравнение', np.poly1d(np.polyfit(x, y, 1)))
plt.plot(a, p(a), color='k')
plt.xlim(0.7, 1.3)
plt.ylim(0.04, 0.11)

xminorLocator = MultipleLocator(0.025)
yminorLocator = MultipleLocator(0.005)
xmajorLocator = MultipleLocator(0.125)
ymajorLocator = MultipleLocator(0.025)
ax = plt.subplot()
ax.xaxis.set_minor_locator(xminorLocator)
ax.yaxis.set_minor_locator(yminorLocator)
ax.xaxis.set_major_locator(xmajorLocator)
ax.yaxis.set_major_locator(ymajorLocator)
plt.grid(which='major', ls='-', lw=0.5, c='k')
plt.grid(which='minor', ls='--', lw=0.5, c='grey')
plt.title("Рис.5: График зависимости d(1/D)")
plt.xlabel(u"1/D, 1/мм")
plt.ylabel(u"d, мм")
plt.show()
Exemplo n.º 6
0
left_axis.tick_params(axis='both',
                      which='minor',
                      direction='inout',
                      length=minor_grid_tick_length)
#
###
#
# axis domain and range
#
plot.xlim(xmin, xmax)
left_axis.axis(ymin=ymin, ymax=ymax)
###
#
# axis ticks
#
left_axis.xaxis.set_major_locator(MultipleLocator(xmajortick))
left_axis.xaxis.set_minor_locator(MultipleLocator(xminortick))
left_axis.yaxis.set_major_locator(MultipleLocator(ymajortick))
left_axis.yaxis.set_minor_locator(MultipleLocator(yminortick))
#
###
#
# log scale option
# xmin,ymin !=0 for log scale
#
#left_axis.set_xscale('log')
left_axis.set_yscale('log')
#
###
#
# annotation
import csv
import math
from pylab import *
from matplotlib.ticker import MultipleLocator

majorGap = 20
xMajorLocator = MultipleLocator(majorGap)  # 将x主刻度标签设置为20的倍数
xMinorLocator = MultipleLocator(5)  # 将x轴次刻度标签设置为5的倍数

cate = 6255

brandBuyLimitNum = 500
brandList = []
brandInfoFile = "brandFeatureOfCate" + str(cate) + ".csv"
brandSrc = csv.reader(open(brandInfoFile, 'r'))
i = 0   # 跳过标题栏
for row in brandSrc:
    if i == 0:
        i = i + 1
        continue
    row[5] = float(row[5])
    if row[5] >= brandBuyLimitNum:
        brandList.append(row[0])

for brand in brandList:
    # 寻找品牌购买前的最大浏览时间和最小浏览时间
    brandMinViewTime = 0
    brandMaxViewTime = 0

    userInfoFile = "userFeatureOfCate" + str(cate) + ".csv"
    userInfo = csv.reader(open(userInfoFile, 'r'))
Exemplo n.º 8
0
def group_comp_simp(df, phases, rois=['rACC', 'sgACC']):
    comp = pd.DataFrame(index=pd.MultiIndex.from_product(
        [rois, phases], names=['roi', 'encode_phase']))
    phase_pal = sns.color_palette(
        ['black', 'darkmagenta', 'lightgreen', 'seagreen'], desat=1)

    for roi in rois:
        for phase in phases:

            c = df.loc[('healthy', roi, phase), 'rsa'].values
            cci, cdist = pg.compute_bootci(c,
                                           func='mean',
                                           n_boot=1000,
                                           return_dist=True,
                                           method='cper',
                                           decimals=3,
                                           seed=42)

            p = df.loc[('ptsd', roi, phase), 'rsa'].values
            cci, pdist = pg.compute_bootci(p,
                                           func='mean',
                                           n_boot=1000,
                                           return_dist=True,
                                           method='cper',
                                           decimals=3,
                                           seed=42)

            dif = cdist - pdist

            comp.loc[(roi, phase), 'point'] = dif.mean()

            # tres = pg.ttest(c,p,paired=False,correction=False)
            comp.loc[(roi, phase),
                     'ci_l'] = np.percentile(dif, 5)  #tres['CI95%'][0][0]
            comp.loc[(roi, phase),
                     'ci_u'] = np.percentile(dif, 100)  #tres['CI95%'][0][1]
            comp.loc[(roi, phase),
                     'p'] = 1 - np.mean(dif > 0)  #tres['p-val'][0]
        comp.loc[roi, 'corrp'] = pg.multicomp(list(comp.loc[roi, 'p'].values),
                                              method='fdr_bh')[1]

    comp['sig'] = comp.corrp.apply(pconvert)

    fig, ax = plt.subplots(1, 2, sharey=True, sharex=True, figsize=(10.5, 4.5))
    for i, roi in enumerate(rois):
        dat = comp.loc[roi].reset_index()
        Ax = ax[i]

        sns.barplot(data=dat,
                    y='encode_phase',
                    x='point',
                    palette=phase_pal,
                    ax=Ax,
                    seed=42,
                    errcolor='black',
                    orient='h')
        # X_together = [[x-.2,x+.2] for x in Ax.get_xticks()]
        # X = [x for t in X_together for x in t]
        X = Ax.get_yticks()
        Ax.hlines(X,
                  dat.ci_l.values,
                  dat.ci_u.values,
                  linewidth=5,
                  color='black').set_capstyle('round')
        Ax.vlines(0,
                  Ax.get_ylim()[0],
                  Ax.get_ylim()[1],
                  color='grey',
                  linestyle='--',
                  linewidth=3)

        # Ax.legend_.remove()

        # Ax.set_ylim(ymin,ymax)
        Ax.xaxis.set_major_locator(MultipleLocator(.1))
        Ax.xaxis.set_minor_locator(MultipleLocator(.05))

        sns.despine(ax=Ax, trim=True)

        for i, x in enumerate(X):
            Ax.annotate(comp.loc[roi, 'sig'].values[i],
                        xy=(x - .05, Ax.get_ylim()[1] - .1))

    ax[0].set_xlabel('∆ fisher z(r)')
    ax[1].set_xlabel('∆ fisher z(r)')
Exemplo n.º 9
0
ax.plot(df2[col_ni], df2[col], 'k--', label='Herzbach 2005')

# for item, col, col_ni in zip(ax, col_list, col_list_ni_r):
#     item.plot(df['r'],df[col],'k-',label='This Work')
#     item.plot(df2[col_ni],df2[col],'k--',label='Herzbach 2005')

# ax[0].tick_params(axis='both',direction='out')
ax.tick_params(axis='both', which='major', length=6)
ax.tick_params(axis='both', which='minor', length=2)
ax.tick_params(axis='x', which='both', direction='in')
ax.legend(title=col, )
# ax.legend(prop={'weight':'normal'}, title= fr'{title}').get_frame().set_edgecolor('k')
ax.legend(prop={'weight': 'normal'}, title=fr'{col}', frameon=False)

# for item, val,val2 in zip(ax,major_tick,minor_tick):
ax.xaxis.set_major_locator(MultipleLocator(1))
ax.yaxis.set_major_locator(MultipleLocator(1))
ax.xaxis.set_minor_locator(MultipleLocator(0.5))
ax.yaxis.set_minor_locator(MultipleLocator(0.5))
# item.yaxis.set_major_formatter(FormatStrFormatter('%d'))

ax.set_xlim([3, 6])
ax.set_ylim([0, 3])
# ax[1].set_ylim([0,3.5])
# ax[2].set_ylim([0,1.5])
# ax[2].set_xlabel(r'$\bf{r(}$Å$\bf{)}$',fontweight='normal')
ax.set_xlabel(r'r(Å)', fontweight='normal')
ax.set_ylabel(r'g$_{ij}$(r)', fontweight='normal')
# ax[1].set_ylabel('g(r)',fontweight='bold')

# For common y axis title
Exemplo n.º 10
0
def main():

    # Plot VLE envelopes
    clrs = seaborn.color_palette('bright', n_colors=len(df))
    np.random.seed(11)
    np.random.shuffle(clrs)

    fig, ax = plt.subplots(figsize=(8, 6))
    temps = R125.expt_liq_density.keys()
    for temp in temps:
        ax.scatter(
            df.filter(regex=(f"liq_density_{float(temp):.0f}K")),
            np.tile(temp, len(df)),
            c=clrs,
            s=160,
            alpha=0.2,
        )
        ax.scatter(
            df.filter(regex=(f"vap_density_{float(temp):.0f}K")),
            np.tile(temp, len(df)),
            c=clrs,
            s=160,
            alpha=0.2,
        )
    ax.scatter(
        df.filter(regex=("sim_rhoc")),
        df.filter(regex=("sim_Tc")),
        c=clrs,
        s=160,
        alpha=0.2,
    )

    tc, rhoc = calc_critical(df_gaff)
    ax.scatter(
        df_gaff["rholiq_kgm3"],
        df_gaff["T_K"],
        c='gray',
        s=120,
        alpha=0.7,
        label="GAFF",
        marker='s',
    )
    ax.scatter(
        df_gaff["rhovap_kgm3"],
        df_gaff["T_K"],
        c='gray',
        s=120,
        alpha=0.7,
        marker='s',
    )
    ax.scatter(
        rhoc,
        tc,
        c='gray',
        s=120,
        alpha=0.7,
        marker='s',
    )
    ax.scatter(
        R125.expt_liq_density.values(),
        R125.expt_liq_density.keys(),
        color="black",
        marker="x",
        linewidths=3,
        s=300,
        label="Experiment",
        zorder=-1,
    )
    ax.scatter(
        R125.expt_vap_density.values(),
        R125.expt_vap_density.keys(),
        color="black",
        marker="x",
        linewidths=3,
        s=300,
        zorder=-1,
    )
    ax.scatter(R125.expt_rhoc,
               R125.expt_Tc,
               color="black",
               marker="x",
               linewidths=3,
               s=300,
               zorder=-1)

    ax.set_xlim(-100, 1550)
    ax.xaxis.set_major_locator(MultipleLocator(400))
    ax.xaxis.set_minor_locator(AutoMinorLocator(4))

    ax.set_ylim(220, 380)
    ax.yaxis.set_major_locator(MultipleLocator(40))
    ax.yaxis.set_minor_locator(AutoMinorLocator(4))

    ax.tick_params("both",
                   direction="in",
                   which="both",
                   length=4,
                   labelsize=26,
                   pad=10)
    ax.tick_params("both", which="major", length=8)
    ax.xaxis.set_ticks_position("both")
    ax.yaxis.set_ticks_position("both")

    ax.set_ylabel("T (K)", fontsize=32, labelpad=15)
    ax.set_xlabel(r"$\mathregular{\rho}$ (kg/m$\mathregular{^3}$)",
                  fontsize=32,
                  labelpad=12)
    for axis in ['top', 'bottom', 'left', 'right']:
        ax.spines[axis].set_linewidth(2.0)

    ax.legend(loc="lower left",
              bbox_to_anchor=(0.1, 1.0),
              ncol=3,
              fontsize=20,
              handletextpad=0.1,
              markerscale=0.8)
    ax.text(0.6, 0.8, "HFC-125", fontsize=34, transform=ax.transAxes)
    fig.subplots_adjust(bottom=0.3, top=0.85, left=0.25, right=0.95)
    fig.savefig("ffo_pdfs/vle-r125.pdf")

    # Plot Vapor Pressure
    fig, ax = plt.subplots(figsize=(8, 6))

    for temp in temps:
        ax.scatter(
            1000 / np.tile(temp, len(df)),
            df.filter(regex=(f"Pvap_{float(temp):.0f}K")),
            c=clrs,
            s=160,
            alpha=0.2,
        )
    ax.scatter(
        1000 / df_gaff["T_K"],
        df_gaff["pvap_bar"],
        c='gray',
        s=120,
        alpha=0.7,
        label="GAFF",
        marker='s',
    )
    ax.scatter(
        1000 / np.array(list(R125.expt_Pvap.keys())),
        R125.expt_Pvap.values(),
        color="black",
        marker="x",
        linewidths=3,
        s=300,
        label="Experiment",
        zorder=-1,
    )

    ax.set_xlim(2.9, 4.3)
    ax.xaxis.set_major_locator(MultipleLocator(0.3))
    ax.xaxis.set_minor_locator(AutoMinorLocator(3))

    ax.set_ylim(1, 100)
    #ax.yaxis.set_major_locator(MultipleLocator(10))
    #ax.yaxis.set_minor_locator(AutoMinorLocator(5))

    ax.tick_params("both",
                   direction="in",
                   which="both",
                   length=4,
                   labelsize=26,
                   pad=10)
    ax.tick_params("both", which="major", length=8)
    ax.xaxis.set_ticks_position("both")
    ax.yaxis.set_ticks_position("both")
    ax.set_yscale("log")

    ax.set_xlabel(r"1000 / T (K$^{-1}$)", fontsize=32, labelpad=20)
    ax.set_ylabel(r"$\mathregular{P_{vap}}$ (bar)", fontsize=32, labelpad=20)
    for axis in ['top', 'bottom', 'left', 'right']:
        ax.spines[axis].set_linewidth(2.0)

    ax.legend(loc="lower left",
              bbox_to_anchor=(0.1, 1.05),
              ncol=3,
              fontsize=20,
              handletextpad=0.1,
              markerscale=0.8)
    ax.text(0.6, 0.8, "HFC-125", fontsize=34, transform=ax.transAxes)
    fig.subplots_adjust(bottom=0.3, top=0.85, left=0.25, right=0.95)
    fig.savefig("ffo_pdfs/pvap-r125.pdf")

    # Plot Enthalpy of Vaporization
    fig, ax = plt.subplots(figsize=(8, 6))
    for temp in temps:
        ax.scatter(
            np.tile(temp, len(df)),
            df.filter(regex=(f"Hvap_{float(temp):.0f}K")),
            c=clrs,
            s=160,
            alpha=0.2,
        )
    ax.scatter(
        df_gaff["T_K"],
        df_gaff["hvap_kJmol"] / R125.molecular_weight * 1000.0,
        c='gray',
        s=120,
        alpha=0.7,
        label="GAFF",
        marker='s',
    )
    ax.scatter(
        R125.expt_Hvap.keys(),
        R125.expt_Hvap.values(),
        color="black",
        marker="x",
        linewidths=3,
        s=300,
        label="Experiment",
        zorder=-1,
    )

    ax.set_xlim(220, 330)
    ax.xaxis.set_major_locator(MultipleLocator(30))
    ax.xaxis.set_minor_locator(AutoMinorLocator(3))

    ax.set_ylim(-10, 410)
    ax.yaxis.set_major_locator(MultipleLocator(100))
    ax.yaxis.set_minor_locator(AutoMinorLocator(5))

    ax.tick_params("both",
                   direction="in",
                   which="both",
                   length=4,
                   labelsize=26,
                   pad=10)
    ax.tick_params("both", which="major", length=8)
    ax.xaxis.set_ticks_position("both")
    ax.yaxis.set_ticks_position("both")

    ax.set_xlabel("T (K)", fontsize=32, labelpad=20)
    ax.set_ylabel(r"$\mathregular{\Delta H_{vap}}$ (kJ/kg)",
                  fontsize=32,
                  labelpad=20)
    for axis in ['top', 'bottom', 'left', 'right']:
        ax.spines[axis].set_linewidth(2.0)

    ax.legend(loc="lower left",
              bbox_to_anchor=(0.1, 1.0),
              ncol=3,
              fontsize=20,
              handletextpad=0.1,
              markerscale=0.8)
    ax.text(0.6, 0.8, "HFC-125", fontsize=34, transform=ax.transAxes)
    fig.subplots_adjust(bottom=0.3, top=0.85, left=0.25, right=0.95)
    fig.savefig("ffo_pdfs/hvap-r125.pdf")
Exemplo n.º 11
0
    def plot_fit(self, fit):
        fmbinlog, axmbinlog = plt.subplots(figsize=(12, 7))
        chain = fit.extract()
        # Plot the points from above as a comparison
        x_model = np.linspace(6.5, 11, 100)
        for counter, c in enumerate(self.sampled_rates.columns):
            label = None
            if counter == 0:
                label = 'Observations'
            axmbinlog.scatter(self.sampled_rates.index,
                              self.sampled_rates[c],
                              color='g',
                              marker='o',
                              alpha=0.05,
                              s=10,
                              label=label)
            axmbinlog.xaxis.set_minor_locator(MultipleLocator(0.25))
            axmbinlog.yaxis.set_minor_locator(MultipleLocator(0.125))
            axmbinlog.tick_params(which='both',
                                  right=True,
                                  top=True,
                                  direction='in',
                                  labelsize=16)
            axmbinlog.set_xlabel('Stellar Mass $\log (M_*/M_{\odot})$',
                                 size=20)
            axmbinlog.set_ylabel(
                '$\log (N$ (SN hosts) / $N$ (Field Galaxies) )', size=20)
        for i in self.sampled_rates.index:
            axmbinlog.errorbar(i,
                               self.sampled_rates.loc[i].mean(),
                               xerr=0.184,
                               color='g',
                               marker='D',
                               alpha=0.5,
                               markersize=2,
                               mew=0.5,
                               mec='w')

        level = 95

        axmbinlog.fill_between(x_model,
                               np.percentile(chain['line'],
                                             50 - 0.5 * level,
                                             axis=0),
                               np.percentile(chain['line'],
                                             50 + 0.5 * level,
                                             axis=0),
                               color='c',
                               alpha=0.2)

        level = 68
        axmbinlog.fill_between(x_model,
                               np.percentile(chain['line'],
                                             50 - 0.5 * level,
                                             axis=0),
                               np.percentile(chain['line'],
                                             50 + 0.5 * level,
                                             axis=0),
                               color='c',
                               alpha=0.3)

        axmbinlog.plot(x_model,
                       np.percentile(chain['line'], 50, axis=0),
                       color='b',
                       alpha=1,
                       linestyle='-',
                       linewidth=1,
                       label='$dN/dG = %.2f$' % np.median(chain['slope']))
        leg = axmbinlog.legend()
        for lh in leg.legendHandles:
            lh.set_alpha(1)
        plt.savefig(self.root_dir + 'figs/rate_vs_mass_slopes_stanfit.png')
dijet = dijet[:, 9:]
bbjet = bbjet[:, 9:]
#ttbar=ttbar[:, 5:]
weights = f['X_weights'][:]
training_weights = f['X_weights_train'][:]
testing_weights = f['X_weights_test'][:]
val_weights = f['X_weights_val'][:]
variablelist = variablelist[9:]

#fig, ax= plt.subplots(34, 3, figsize=(40,280))
#fig, ax = plt.subplots()
nbins = 50
varcounter = -1

from matplotlib.ticker import MultipleLocator, FormatStrFormatter
xmajorLocator = MultipleLocator(200)
xmajorFormatter = FormatStrFormatter('%1d')
xminorLocator = MultipleLocator(50)
ymajorLocator = MultipleLocator(2000)
ymajorFormatter = FormatStrFormatter('%1d')
yminorLocator = MultipleLocator(1e1)

for varcounter in range(95):
    print(variablelist[varcounter])
    if variablelist[varcounter] == "jet_pt" or variablelist[
            varcounter] == "jet_m":
        nbins = 100
        plt.hist(bbjet[:, varcounter] / 1e3,
                 nbins,
                 density=0,
                 weights=bb_vs_bb_weights,
Exemplo n.º 13
0
        elif name == 'F44':
            index2 = 6

    scattering_elements[name] = data

    pylab.subplot(4, 4, index + 1)

    letter, number = split_name(name)

    if index == 0:
        pylab.yscale('log')
        pylab.text(30, 0.03, name, fontsize=12)
    elif index2 == 3:
        pylab.ylim(ymin=0)
        pylab.ylim(ymax=1.1)
        pylab.gca().yaxis.set_minor_locator(MultipleLocator(0.1))
        pylab.text(15, 0.7, name + r'$\rm /F_{11}$', fontsize=12)
    else:
        pylab.ylim(ymin=-1)
        pylab.ylim(ymax=1)
        pylab.gca().yaxis.set_minor_locator(MultipleLocator(0.1))

        if index == 1:
            pylab.text(15, -0.7, '-' + name + r'$\rm /F_{11}$', fontsize=12)
        else:
            pylab.text(15, -0.7, name + r'$\rm /F_{11}$', fontsize=12)

    if index == 1:
        pylab.plot(data['deg'],
                   -data['data'],
                   "o",
Exemplo n.º 14
0
        if value < 0 or value > len(days):
            return ""
        origin = datetime.date(year = 1900, month = 1, day = 1)
        delta = datetime.timedelta(days = int(days[int(value)]) - 2)
        date = origin + delta
        return str(date.day) + "/" + str(date.month)

    fig, (ax1, ax2) = plt.subplots(2, figsize=(15, 8), gridspec_kw={'height_ratios': [1, 2]})

    final_reward = np.around(rewards[-1], decimals = 4)

    ax1.plot(rewards)
    ax1.set_title("Cumulative sum of rewards - " + filename + " (final reward: " + str(final_reward) + ")")
    ax1.set(xlabel = "Date", ylabel = "Cumulative reward")
    ax1.set_xbound(lower=0, upper=len(days))
    ax1.xaxis.set_major_locator(MultipleLocator(50))
    ax1.xaxis.set_major_formatter(FuncFormatter(format_date))
    ax1.yaxis.set_major_locator(MaxNLocator(5))
    ax1.grid()

    plot = ax2.imshow(actions, cmap='GnBu')
    ax2.set_title("Actions heatmap - " + filename)
    ax2.set(xlabel = "Time of day", ylabel = "Date")
    ax2.xaxis.set_major_locator(MultipleLocator(300))
    ax2.xaxis.set_major_formatter(FuncFormatter(format_time))
    ax2.yaxis.set_major_locator(MultipleLocator(50))
    ax2.yaxis.set_major_formatter(FuncFormatter(format_date))
    fig.colorbar(plot, ticks=[-1, 0, 1], fraction=0.0109, pad=0.01)

    plt.savefig("visualize-actions/" + filename + ".png", format='png')
Exemplo n.º 15
0
def plot_exp_fatigue_life(figure_path=None, figure_name=None, save_types=[]):
    #==============================================================================
    # title
    #==============================================================================
    title = ''
    #==============================================================================
    # figure format
    # http://matplotlib.org/users/customizing.html?highlight=rcparams
    #==============================================================================
    plot_format()
    #==============================================================================
    # grid set up
    #==============================================================================
    #plt.grid(True, which='major',linestyle='-')
    #plt.grid(True, which='minor',linestyle='-')
    #plt.grid(True, which='major')
    #plt.grid(True, which='minor')
    #==============================================================================
    # print title
    #==============================================================================
    plt.title(title, fontsize=16)
    #==============================================================================
    # x,y limite
    #==============================================================================
    plt.xlim(1E0, 1E5)
    plt.ylim(0.3, 1.0)
    #==============================================================================
    # xy log scale
    #==============================================================================
    plt.xscale('log')
    plt.yscale('log')
    #==============================================================================
    # xy axial equal
    #==============================================================================
    ax = plt.gca()
    #    ax.set_aspect('equal')
    ax.set_aspect('auto')
    #==============================================================================
    # http://stackoverflow.com/questions/21920233/matplotlib-log-scale-tick-label-number-formatting
    #==============================================================================
    ax.yaxis.set_major_locator(MultipleLocator(0.1))
    ax.yaxis.set_minor_locator(MultipleLocator(0.01))
    ax.yaxis.set_major_formatter(ScalarFormatter())
    #==============================================================================
    # plot lines
    #==============================================================================
    plot_data = PlotData()
    plot_data.readFromFile(figure_path, figure_name)
    plot_data.plot()
    #==============================================================================
    # show legend
    #==============================================================================
    plt.legend(loc=1, frameon=True)
    #    plt.legend(loc=0,fontsize='small',frameon=True,numpoints=1,title='Temperature')
    #==============================================================================
    # save figures
    #==============================================================================
    if figure_path <> None and figure_name <> None:
        for save_type in save_types:
            plt.savefig(figure_path + figure_name + save_type,
                        dpi=150,
                        transparent=True)
            print 'save as', figure_path + figure_name + save_type
    plt.show()
    plt.close()
Exemplo n.º 16
0
def split_level(df, group, rois=['rSMA', 'sgACC'], phases=None, split=None):
    if split == 'level':
        splits = ['item', 'set']
        # pal = sns.palettes.color_palette('Set2',n_colors=2)
        pal = ['blue', 'lightblue']

    elif split == 'memory_phase':
        splits = ['encoding', 'retrieval']
        # pal = sns.palettes.color_palette('Set2',n_colors=4)[2:]
        pal = ['firebrick', 'salmon']

    df = df.loc[group]
    out = {}

    for val in ['ci', 'dist']:
        out[val] = {}
    for roi in rois:
        out['ci'][roi] = {}
        out['dist'][roi] = {}
        for phase in phases:
            out['ci'][roi][phase] = {}
            out['dist'][roi][phase] = {}
            for level in splits:
                out['ci'][roi][phase][level] = {}
                out['dist'][roi][phase][level] = {}

                out['ci'][roi][phase][level], out['dist'][roi][phase][
                    level] = pg.compute_bootci(df.loc[(roi, phase, level),
                                                      'rsa'].values,
                                               func='mean',
                                               n_boot=10000,
                                               return_dist=True,
                                               method='cper',
                                               decimals=3,
                                               seed=42)

    ci = pd.DataFrame.from_dict(
        out['ci'],
        orient='index').reset_index().rename(columns={'index': 'roi'})
    ci = ci.melt(id_vars='roi', var_name='encode_phase',
                 value_name='ci').set_index(['roi',
                                             'encode_phase']).sort_index()
    ci = ci.ci.apply(pd.Series).reset_index()
    ci = ci.melt(id_vars=['roi', 'encode_phase'],
                 var_name='level',
                 value_name='ci').set_index(['roi', 'encode_phase', 'level'])

    dist = pd.DataFrame.from_dict(
        out['dist'],
        orient='index').reset_index().rename(columns={'index': 'roi'})
    dist = dist.melt(id_vars='roi', var_name='encode_phase',
                     value_name='dist').set_index(['roi', 'encode_phase'])
    dist = dist.dist.apply(pd.Series).reset_index()
    dist = dist.melt(id_vars=['roi', 'encode_phase'],
                     var_name='level',
                     value_name='dist').set_index(
                         ['roi', 'encode_phase', 'level'])
    dist = dist.dist.apply(pd.Series).stack().reset_index(-1, drop=True)
    dist = dist.reset_index().rename(columns={0: 'dist'})

    ci['point'] = dist.groupby(['roi', 'encode_phase', 'level']).mean()
    ci = ci.reset_index()

    ci.roi = pd.Categorical(ci.roi, rois, ordered=True)
    ci.encode_phase = pd.Categorical(ci.encode_phase, phases, ordered=True)
    ci.level = pd.Categorical(ci.level, splits, ordered=True)
    ci = ci.sort_values(by=['encode_phase', 'level'])
    ci = ci.set_index('roi').sort_index()

    dist.roi = pd.Categorical(dist.roi, rois, ordered=True)
    dist.encode_phase = pd.Categorical(dist.encode_phase, phases, ordered=True)
    dist.level = pd.Categorical(dist.level, splits, ordered=True)
    dist = dist.sort_values(by=['encode_phase', 'level'])
    dist = dist.set_index('roi').sort_index()

    #collect 2 tailed p-values
    # pvals = dist.reset_index().groupby(['roi','encode_phase','level']
    # ).apply(lambda x : (1-np.mean(x>0))/2
    # ).reset_index().set_index('roi').rename(columns={'dist':'p'})
    # for roi in rois: pvals.loc[roi,'corrp'] = pg.multicomp(pvals.loc[roi,'p'].values,method='fdr_bh')[1]
    pvals = pd.DataFrame(columns=['p'],
                         index=pd.MultiIndex.from_product(
                             [rois, phases, splits],
                             names=['roi', 'encode_phase', 'level']))
    for roi in rois:
        for phase in phases:
            for s in splits:
                pvals.loc[(roi, phase, s), 'p'] = pg.ttest(
                    df.loc[(roi, phase, s), 'rsa'].values,
                    0)['p-val'].values[0]
    # for roi in rois: pvals.loc[roi,'corrp'] = pg.multicomp(list(pvals.loc[roi,'p'].values),method='fdr_bh')[1]
    pvals['corrp'] = pg.multicomp(list(pvals.p.values), method='fdr_bh')[1]
    pvals['sig'] = pvals.corrp.apply(pconvert)

    phase_pal = sns.color_palette(
        ['black', 'darkmagenta', 'lightgreen', 'seagreen'], desat=.75)

    ymax = dist.dist.max() + .05
    ymin = dist.dist.min() - .05
    fig, ax = plt.subplots(1, 2, sharey=True, figsize=(8, 3))
    for i, roi in enumerate(rois):
        dat = df.loc[roi].reset_index()
        Ax = ax[i]
        '''
        #dist violins
        sns.violinplot(data=dist.loc[roi],x='encode_phase',y='dist',cut=0,
                        inner=None,ax=Ax,scale='count',hue='level',split=True,palette=pal)#,palette=['white','white'])
        '''
        sns.barplot(data=dat,
                    x='encode_phase',
                    y='rsa',
                    hue=split,
                    palette=pal,
                    ax=Ax,
                    order=phases,
                    seed=42,
                    errcolor='black')
        change_width(Ax, .35)
        '''
        sns.violinplot(data=dat,x='encode_phase',y='rsa',hue=split,
                        split=True,palette=pal,cut=0,ax=Ax,inner=None)
        '''
        '''
        #jointplot
        sns.pointplot(data=dat,x='encode_phase',y='rsa',hue=split,
                     dodge=.3,n_boot=1000,seed=42,markers=['o','D'],ax=Ax,palette=pal,
                     join=False)
        '''

        lower = ci.loc[roi, 'ci'].apply(lambda x: x[0])
        upper = ci.loc[roi, 'ci'].apply(lambda x: x[1])
        Y = ci.loc[roi, 'point']
        X_together = [[x - .1, x + .1] for x in Ax.get_xticks()]
        X = [x for t in X_together for x in t]

        # Ax.vlines(X,lower,upper,linewidth=3,color='black').set_capstyle('butt')
        # Ax.scatter(X,lower,s=240,marker='_',color='black',linewidths=5)
        # Ax.scatter(X,upper,s=240,marker='_',color='black',linewidths=5)
        # Ax.scatter(X,Y,s=480,marker='_',color='black',edgecolors='black') #set level

        # #stripplots
        # sns.stripplot(data=dat,x='encode_phase',y='rsa',hue=split,palette=pal,
        #             ax=Ax,dodge=.3,order=phases,alpha=.3,edgecolor='black',linewidth=1)
        '''
        #chicken scratch
        dat = dat.set_index(['encode_phase',split])
        for p, phase in enumerate(phases):
            left = dat.loc[(phase,splits[0]),'rsa']
            right = dat.loc[(phase,splits[1]),'rsa']
            for xy in range(left.shape[0]):
                xvals = X_together[p]
                xvals[0] -= .01
                xvals[1] += .01
                Ax.plot(X_together[p],[left[xy],right[xy]],color='grey',lw=1,alpha=.5)
        '''

        Ax.hlines(0,
                  Ax.get_xlim()[0],
                  Ax.get_xlim()[1],
                  color='grey',
                  linestyle='--',
                  linewidth=3)
        Ax.set_xticklabels('', rotation=45)
        Ax.set_title(roi + '_' + group + '_' + split)

        Ax.legend_.remove()

        Ax.set_ylim(ymin, ymax)
        Ax.yaxis.set_major_locator(MultipleLocator(.2))
        Ax.yaxis.set_minor_locator(MultipleLocator(.1))

        sns.despine(ax=Ax, trim=True)

        for i, x in enumerate(X):
            Ax.annotate(pvals.loc[roi, 'sig'].values[i],
                        xy=(x - .05, Ax.get_ylim()[1] - .1))

    if len(rois) > 1:
        ax[0].set_ylabel('∆ fisher z(r)')
        ax[1].set_ylabel('')
    else:
        ax.set_ylabel('∆ fisher z(r)')
        ax.set_ylabel('')
    plt.savefig('./plots/%s_%s.eps' % (group, split), format='eps')
Exemplo n.º 17
0
def pollyxt_dwd_display_saturation(tmpFile, saveFolder):
    """
    Description
    -----------
    Display the housekeeping data from laserlogbook file.

    Parameters
    ----------
    tmpFile: str
    the .mat file which stores the housekeeping data.

    saveFolder: str

    Usage
    -----
    pollyxt_dwd_display_saturation(tmpFile)

    History
    -------
    2019-01-10. First edition by Zhenping
    """

    if not os.path.exists(tmpFile):
        print('{filename} does not exists.'.format(filename=tmpFile))
        return

    # read matlab .mat data
    try:
        mat = spio.loadmat(tmpFile, struct_as_record=True)
        figDPI = mat['figDPI'][0][0]
        mTime = mat['time'][0][:]
        height = mat['height'][0][:]
        SAT_FR_355 = mat['SAT_FR_355'][:]
        SAT_FR_532 = mat['SAT_FR_532'][:]
        SAT_FR_1064 = mat['SAT_FR_1064'][:]
        SAT_NR_532 = mat['SAT_NR_532'][:]
        yLim_FR_RCS = mat['yLim_FR_RCS'][:][0]
        yLim_NR_RCS = mat['yLim_NR_RCS'][:][0]
        pollyVersion = mat['campaignInfo']['name'][0][0][0]
        location = mat['campaignInfo']['location'][0][0][0]
        version = mat['processInfo']['programVersion'][0][0][0]
        fontname = mat['processInfo']['fontname'][0][0][0]
        dataFilename = mat['taskInfo']['dataFilename'][0][0][0]
        xtick = mat['xtick'][0][:]
        xticklabel = mat['xtickstr']
        imgFormat = mat['imgFormat'][:][0]
    except Exception as e:
        print(e)
        print('Failed reading %s' % (tmpFile))
        return

    # set the default font
    matplotlib.rcParams['font.sans-serif'] = fontname
    matplotlib.rcParams['font.family'] = "sans-serif"

    # meshgrid
    Time, Height = np.meshgrid(mTime, height)

    # load colormap
    dirname = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sys.path.append(dirname)
    try:
        from python_colormap import signal_status_colormap
    except Exception as e:
        raise ImportError('python_colormap module is necessary.')

    # display status of 355 FR
    fig = plt.figure(figsize=[10, 5])
    ax = fig.add_axes([0.11, 0.15, 0.74, 0.75])
    pcmesh = ax.pcolormesh(Time,
                           Height,
                           SAT_FR_355,
                           vmin=-0.5,
                           vmax=2.5,
                           cmap=signal_status_colormap(),
                           rasterized=True)
    ax.set_xlabel('UTC', fontsize=15)
    ax.set_ylabel('Height (m)', fontsize=15)

    ax.set_ylim(yLim_FR_RCS.tolist())
    ax.yaxis.set_major_locator(MultipleLocator(2500))
    ax.yaxis.set_minor_locator(MultipleLocator(500))
    ax.set_xticks(xtick.tolist())
    ax.set_xticklabels(celltolist(xticklabel))
    ax.tick_params(axis='both',
                   which='major',
                   labelsize=15,
                   right=True,
                   top=True,
                   width=2,
                   length=5)
    ax.tick_params(axis='both',
                   which='minor',
                   width=1.5,
                   length=3.5,
                   right=True,
                   top=True)

    ax.set_title('Signal Status at ' +
                 '{wave}nm Far-Range from {instrument} at {location}'.format(
                     wave=355, instrument=pollyVersion, location=location),
                 fontsize=15)

    cb_ax = fig.add_axes([0.865, 0.15, 0.02, 0.75])
    cbar = fig.colorbar(pcmesh,
                        cax=cb_ax,
                        ticks=[0, 1, 2],
                        orientation='vertical')
    cbar.ax.tick_params(direction='in', pad=5)
    cbar.ax.set_title('', fontsize=9)
    cbar.ax.set_yticklabels(['Good Signal', 'Saturated', 'Low SNR'])
    cbar.ax.tick_params(axis='both',
                        which='major',
                        labelsize=12,
                        right=True,
                        top=True,
                        width=2,
                        length=5)
    cbar.ax.tick_params(axis='both',
                        which='minor',
                        width=1.5,
                        length=3.5,
                        right=True,
                        top=True)

    fig.text(0.05,
             0.04,
             datenum_to_datetime(mTime[0]).strftime("%Y-%m-%d"),
             fontsize=15)
    fig.text(0.8,
             0.04,
             'Version: {version}'.format(version=version),
             fontsize=14)

    fig.savefig(os.path.join(
        saveFolder, '{dataFilename}_SAT_FR_355.{imgFmt}'.format(
            dataFilename=rmext(dataFilename), imgFmt=imgFormat)),
                dpi=figDPI)
    plt.close()

    # display status of 532 FR
    fig = plt.figure(figsize=[10, 5])
    ax = fig.add_axes([0.11, 0.15, 0.74, 0.75])
    pcmesh = ax.pcolormesh(Time,
                           Height,
                           SAT_FR_532,
                           vmin=-0.5,
                           vmax=2.5,
                           cmap=signal_status_colormap(),
                           rasterized=True)
    ax.set_xlabel('UTC', fontsize=15)
    ax.set_ylabel('Height (m)', fontsize=15)

    ax.set_ylim(yLim_FR_RCS.tolist())
    ax.yaxis.set_major_locator(MultipleLocator(2500))
    ax.yaxis.set_minor_locator(MultipleLocator(500))
    ax.set_xticks(xtick.tolist())
    ax.set_xticklabels(celltolist(xticklabel))
    ax.tick_params(axis='both',
                   which='major',
                   labelsize=15,
                   right=True,
                   top=True,
                   width=2,
                   length=5)
    ax.tick_params(axis='both',
                   which='minor',
                   width=1.5,
                   length=3.5,
                   right=True,
                   top=True)

    ax.set_title('Signal Status at ' +
                 '{wave}nm Far-Range from {instrument} at {location}'.format(
                     wave=532, instrument=pollyVersion, location=location),
                 fontsize=15)

    cb_ax = fig.add_axes([0.865, 0.15, 0.02, 0.75])
    cbar = fig.colorbar(pcmesh,
                        cax=cb_ax,
                        ticks=[0, 1, 2],
                        orientation='vertical')
    cbar.ax.tick_params(direction='in', pad=5)
    cbar.ax.set_title('', fontsize=9)
    cbar.ax.set_yticklabels(['Good Signal', 'Saturated', 'Low SNR'])
    cbar.ax.tick_params(axis='both',
                        which='major',
                        labelsize=12,
                        right=True,
                        top=True,
                        width=2,
                        length=5)
    cbar.ax.tick_params(axis='both',
                        which='minor',
                        width=1.5,
                        length=3.5,
                        right=True,
                        top=True)

    fig.text(0.05,
             0.04,
             datenum_to_datetime(mTime[0]).strftime("%Y-%m-%d"),
             fontsize=15)
    fig.text(0.8,
             0.04,
             'Version: {version}'.format(version=version),
             fontsize=14)

    fig.savefig(os.path.join(
        saveFolder, '{dataFilename}_SAT_FR_532.{imgFmt}'.format(
            dataFilename=rmext(dataFilename), imgFmt=imgFormat)),
                dpi=figDPI)
    plt.close()

    # display status of 1064 FR
    fig = plt.figure(figsize=[10, 5])
    ax = fig.add_axes([0.11, 0.15, 0.74, 0.75])
    pcmesh = ax.pcolormesh(Time,
                           Height,
                           SAT_FR_1064,
                           vmin=-0.5,
                           vmax=2.5,
                           cmap=signal_status_colormap(),
                           rasterized=True)
    ax.set_xlabel('UTC', fontsize=15)
    ax.set_ylabel('Height (m)', fontsize=15)

    ax.set_ylim(yLim_FR_RCS.tolist())
    ax.yaxis.set_major_locator(MultipleLocator(2500))
    ax.yaxis.set_minor_locator(MultipleLocator(500))
    ax.set_xticks(xtick.tolist())
    ax.set_xticklabels(celltolist(xticklabel))
    ax.tick_params(axis='both',
                   which='major',
                   labelsize=15,
                   right=True,
                   top=True,
                   width=2,
                   length=5)
    ax.tick_params(axis='both',
                   which='minor',
                   width=1.5,
                   length=3.5,
                   right=True,
                   top=True)

    ax.set_title('Signal Status at ' +
                 '{wave}nm Far-Range from {instrument} at {location}'.format(
                     wave=1064, instrument=pollyVersion, location=location),
                 fontsize=15)

    cb_ax = fig.add_axes([0.865, 0.15, 0.02, 0.75])
    cbar = fig.colorbar(pcmesh,
                        cax=cb_ax,
                        ticks=[0, 1, 2],
                        orientation='vertical')
    cbar.ax.tick_params(direction='in', pad=5)
    cbar.ax.set_title('', fontsize=9)
    cbar.ax.set_yticklabels(['Good Signal', 'Saturated', 'Low SNR'])
    cbar.ax.tick_params(axis='both',
                        which='major',
                        labelsize=12,
                        right=True,
                        top=True,
                        width=2,
                        length=5)
    cbar.ax.tick_params(axis='both',
                        which='minor',
                        width=1.5,
                        length=3.5,
                        right=True,
                        top=True)

    fig.text(0.05,
             0.04,
             datenum_to_datetime(mTime[0]).strftime("%Y-%m-%d"),
             fontsize=15)
    fig.text(0.8,
             0.04,
             'Version: {version}'.format(version=version),
             fontsize=14)

    fig.savefig(os.path.join(
        saveFolder, '{dataFilename}_SAT_FR_1064.{imgFmt}'.format(
            dataFilename=rmext(dataFilename), imgFmt=imgFormat)),
                dpi=figDPI)
    plt.close()

    # display status of 532 NR
    fig = plt.figure(figsize=[10, 5])
    ax = fig.add_axes([0.11, 0.15, 0.74, 0.75])
    pcmesh = ax.pcolormesh(Time,
                           Height,
                           SAT_NR_532,
                           vmin=-0.5,
                           vmax=2.5,
                           cmap=signal_status_colormap(),
                           rasterized=True)
    ax.set_xlabel('UTC', fontsize=15)
    ax.set_ylabel('Height (m)', fontsize=15)

    ax.set_ylim(yLim_NR_RCS.tolist())
    ax.yaxis.set_major_locator(MultipleLocator(2500))
    ax.yaxis.set_minor_locator(MultipleLocator(500))
    ax.set_xticks(xtick.tolist())
    ax.set_xticklabels(celltolist(xticklabel))
    ax.tick_params(axis='both',
                   which='major',
                   labelsize=15,
                   right=True,
                   top=True,
                   width=2,
                   length=5)
    ax.tick_params(axis='both',
                   which='minor',
                   width=1.5,
                   length=3.5,
                   right=True,
                   top=True)

    ax.set_title('Signal Status at ' +
                 '{wave}nm Near-Range from {instrument} at {location}'.format(
                     wave=532, instrument=pollyVersion, location=location),
                 fontsize=15)

    cb_ax = fig.add_axes([0.865, 0.15, 0.02, 0.75])
    cbar = fig.colorbar(pcmesh,
                        cax=cb_ax,
                        ticks=[0, 1, 2],
                        orientation='vertical')
    cbar.ax.tick_params(direction='in', pad=5)
    cbar.ax.set_title('', fontsize=9)
    cbar.ax.set_yticklabels(['Good Signal', 'Saturated', 'Low SNR'])
    cbar.ax.tick_params(axis='both',
                        which='major',
                        labelsize=12,
                        right=True,
                        top=True,
                        width=2,
                        length=5)
    cbar.ax.tick_params(axis='both',
                        which='minor',
                        width=1.5,
                        length=3.5,
                        right=True,
                        top=True)

    fig.text(0.05,
             0.04,
             datenum_to_datetime(mTime[0]).strftime("%Y-%m-%d"),
             fontsize=15)
    fig.text(0.8,
             0.04,
             'Version: {version}'.format(version=version),
             fontsize=14)

    fig.savefig(os.path.join(
        saveFolder, '{dataFilename}_SAT_NR_532.{imgFmt}'.format(
            dataFilename=rmext(dataFilename), imgFmt=imgFormat)),
                dpi=figDPI)
    plt.close()
Exemplo n.º 18
0
def group_comp(df, phases, split):
    if split == 'level':
        splits = ['item', 'set']
        # pal = sns.palettes.color_palette('Set2',n_colors=2)
        pal = ['blue', 'lightblue']

    elif split == 'memory_phase':
        splits = ['encoding', 'retrieval']
        # pal = sns.palettes.color_palette('Set2',n_colors=4)[2:]
        pal = ['firebrick', 'salmon']
    rois = ['rSMA', 'sgACC']
    comp = pd.DataFrame(index=pd.MultiIndex.from_product(
        [rois, phases, splits], names=['roi', 'encode_phase', split]))
    for roi in rois:
        for phase in phases:
            for level in splits:
                c = df.loc[('control', roi, phase, level), 'rsa'].values
                p = df.loc[('ptsd', roi, phase, level), 'rsa'].values
                comp.loc[(roi, phase, level), 'point'] = c.mean() - p.mean()
                tres = pg.ttest(c, p, paired=False, correction=False)
                comp.loc[(roi, phase, level), 'ci_l'] = tres['CI95%'][0][0]
                comp.loc[(roi, phase, level), 'ci_u'] = tres['CI95%'][0][1]
                comp.loc[(roi, phase, level), 'p'] = tres['p-val'][0]
    for roi in rois:
        comp.loc[roi, 'corrp'] = pg.multicomp(list(comp.loc[roi, 'p'].values),
                                              method='fdr_bh')[1]
    comp['sig'] = comp.corrp.apply(pconvert)

    ymax = comp.ci_u.max() + .05
    ymin = comp.ci_l.min() - .05
    fig, ax = plt.subplots(1, 2, sharey=True, figsize=(24, 12))
    for i, roi in enumerate(rois):
        dat = comp.loc[roi].reset_index()
        Ax = ax[i]

        sns.barplot(data=dat,
                    x='encode_phase',
                    y='point',
                    hue=split,
                    palette=pal,
                    ax=Ax,
                    order=phases,
                    seed=42,
                    errcolor='black')
        X_together = [[x - .2, x + .2] for x in Ax.get_xticks()]
        X = [x for t in X_together for x in t]
        Ax.vlines(X,
                  dat.ci_l.values,
                  dat.ci_u.values,
                  linewidth=5,
                  color='black').set_capstyle('round')
        Ax.hlines(0,
                  Ax.get_xlim()[0],
                  Ax.get_xlim()[1],
                  color='grey',
                  linestyle='--',
                  linewidth=3)

        Ax.legend_.remove()

        Ax.set_ylim(ymin, ymax)
        Ax.yaxis.set_major_locator(MultipleLocator(.1))
        Ax.yaxis.set_minor_locator(MultipleLocator(.05))

        sns.despine(ax=Ax, trim=True)

        for i, x in enumerate(X):
            Ax.annotate(comp.loc[roi, 'sig'].values[i],
                        xy=(x - .05, Ax.get_ylim()[1] - .1))

    if len(rois) > 1:
        ax[0].set_ylabel('∆ fisher z(r)')
        ax[1].set_ylabel('')
    else:
        ax.set_ylabel('∆ fisher z(r)')
        ax.set_ylabel('')

    plt.savefig('./plots/group_comp_%s.eps' % (split), format='eps')
Exemplo n.º 19
0
def plot_mcd(dic,
             op='avg',
             x_axis='Energy (eV)',
             title='[PH]',
             xdata='energy',
             ydata='mdeg'):
    plt.clf()
    fig, ax = plt.subplots(figsize=(4, 2))
    # norm=plt.Normalize(-10,10) #optional to remove discrete H bar divisions
    norm = colors.BoundaryNorm(np.linspace(-10, 10, 11), ncolors=256)
    sm = plt.cm.ScalarMappable(cmap='coolwarm_r', norm=norm)
    fig.colorbar(sm, ticks=range(-10, 11, 2),
                 label='H (T)')  #make color bar based on H (T) for plot
    for df in dic.values():
        #Dr. Seaborn or: How I Learned to Stop Worrying and Love sns.lineplot. Such efficiency. Much wow.
        sns.lineplot(data=df,
                     x=xdata,
                     y=ydata,
                     linewidth=0.6,
                     hue='field',
                     hue_norm=(-10, 10),
                     palette=sns.color_palette('coolwarm_r', as_cmap=True),
                     legend=None)
    if x_axis == 'Energy (eV)':
        ax.set_xlabel(x_axis)
    if op == 'raw':
        plt.title("Raw MCD " + title)
    if op == 'avg':
        plt.title("Averaged MCD " + title)

    ax.plot([-10, 10], [0, 0], color='black', linestyle='-',
            linewidth='1')  #add 0T baseline

    # ax.set_ylabel(r'$\Delta$A/A$_{\mathrm{max}}$ (x $10^{-3}$)')
    ax.set_ylabel('MCD (mdeg)')
    ax.set_xlim(2.7, 1.2)
    ax.xaxis.set_major_locator(MultipleLocator(0.2))
    ax.xaxis.set_minor_locator(AutoMinorLocator())  # auto set minor ticks
    ax.set_ylim(-1.5, 1.5)
    ax.yaxis.set_major_locator(MultipleLocator(0.5))
    ax.yaxis.set_minor_locator(AutoMinorLocator())  # auto set minor ticks

    ax2 = ax.twiny(
    )  # creates a new axis with invisible y and independent x on opposite side of first x-axis
    ax2.set_xlabel(r'Wavelength (nm)')
    ax2.set_xscale(
        'function',
        functions=(getWavelength,
                   getEnergy))  # set twin scale (convert degree eV to nm)
    xmin, xmax = ax.get_xlim()  # get left axis limits
    ax2.set_xlim(
        (getWavelength(xmax), getWavelength(xmin)
         ))  # apply function and set transformed values to right axis limits
    ax2.xaxis.set_minor_locator(AutoMinorLocator())  # auto set minor ticks

    ax2.plot(
        [], []
    )  # set an invisible artist to twin axes to prevent falling back to initial values on rescale events

    #Set tick parameters
    ax.xaxis.set_tick_params(
        which='major', size=5, width=0.8, direction='in'
    )  #axes.linewidth by default for matplotlib is 0.8, so that value is used here for aesthetic matching.
    ax.xaxis.set_tick_params(which='minor', size=2, width=0.8, direction='in')
    ax.yaxis.set_tick_params(which='major',
                             size=5,
                             width=0.8,
                             direction='in',
                             right='on')
    ax.yaxis.set_tick_params(which='minor',
                             size=2,
                             width=0.8,
                             direction='in',
                             right='on')

    ax2.xaxis.set_tick_params(which='major', size=5, width=0.8, direction='in')
    ax2.xaxis.set_tick_params(which='minor', size=2, width=0.8, direction='in')

    # plt.style.use('classic') #Doesn't seem to affect plot.
    plt.tight_layout()

    plt.style.use('seaborn-paper')
    plt.savefig(op + '_mcd_' + title,
                dpi=300,
                transparent=False,
                bbox_inches='tight')
    plt.show()
Exemplo n.º 20
0
#------------- plot variation coefficient ---------------#

width = 0.55

fig, axs = plt.subplots(1, 1, gridspec_kw={'hspace': 0, 'wspace': 0}, figsize=(12,5))
fig.suptitle("GPU training time variational coefficient (%)")
fig.subplots_adjust(bottom=0.2)

x = np.arange(len(tc_list))
axs.bar(x, vc_pct, width)
axs.set_xticks(x)
axs.set_xticklabels(tc_list, rotation=45, ha="right")
axs.set_xlabel('test cases')
axs.set_ylabel('variation coefficient (%)')
#axs.set_yticks(minor=True)
axs.get_yaxis().set_minor_locator(MultipleLocator(1))
#axs.legend()

axs.grid(which='both', axis='y', linestyle=':', color='black')
plt.savefig("./time_variation.png")

#------------- plot spread ---------------#

fig, axs = plt.subplots(1, 1, gridspec_kw={'hspace': 0, 'wspace': 0}, figsize=(12,5))
fig.suptitle("GPU training time spread")
fig.subplots_adjust(bottom=0.2)

x = np.arange(len(tc_list))
axs.bar(x, spread, width)
axs.set_xticks(x)
axs.set_xticklabels(tc_list, rotation=45, ha="right")
Exemplo n.º 21
0
                    alpha=0.7)
    ax.fill_between(x,
                    df_pc['SOLAR'].to_list(),
                    df_pc['HYDRO'].to_list(),
                    facecolor='orange',
                    alpha=0.7)
    ax.fill_between(x,
                    df_pc['WIND'].to_list(),
                    df_pc['SOLAR'].to_list(),
                    facecolor='purple',
                    alpha=0.7)

    ax.set_ylabel('Share of cumulative capacity', fontsize=9)
    ax.set_xlabel('Year', fontsize=9)
    ax.tick_params(labelsize=8)
    ax.xaxis.set_major_locator(MultipleLocator(2))
    ax.xaxis.set_minor_locator(MultipleLocator(1))
    # ax.yaxis.set_major_locator(MultipleLocator(0.2))
    # ax.yaxis.set_minor_locator(MultipleLocator(0.05))
    # ax.set_ylim([0, 1])
    fig.set_size_inches(4.5, 2.8)

    legend_elements = [
        Patch(facecolor='brown', label='Coal', alpha=0.7),
        Patch(facecolor='green', label='Gas', alpha=0.7),
        Patch(facecolor='blue', label='Hydro', alpha=0.7),
        Patch(facecolor='orange', label='Solar', alpha=0.7),
        Patch(facecolor='purple', label='Wind', alpha=0.7)
    ]

    ax.legend(handles=legend_elements, fontsize=9, ncol=2, loc='lower left')
Exemplo n.º 22
0
def plotHistogram(data, options):

    colours = options.colour.split(',')
    alphas = options.alpha.split(',')
    columns = options.column.split(',')
    leglabels = None
    if options.leglabels:
        leglabels = options.leglabels.split(',')
    #fig = plt.figure(figsize=(6,3))
    fig = plt.figure()

    ax1 = fig.add_subplot(111)

    #bins = n.linspace(round(float(options.binlower)), round(float(options.binupper)), int((float(options.binupper) - float(options.binlower))/float(options.binwidth))+1)
    bins = n.linspace(
        float(options.binlower), float(options.binupper),
        int((float(options.binupper) - float(options.binlower)) /
            float(options.binwidth)) + 1)
    print(bins)

    ml = MultipleLocator(float(options.majorticks))
    ax1.xaxis.set_major_locator(ml)

    ax1 = fig.add_subplot(111)
    # May have more than one histogram to plot
    i = 0
    for d in data:
        if len(colours) == 1:
            colour = colours[0]
        else:
            colour = colours[i]

        if len(alphas) == 1:
            alpha = alphas[0]
        else:
            alpha = alphas[i]

        print(n.sort(n.array(d)))
        ax1.hist(n.sort(n.array(d)),
                 bins=bins,
                 color=colour,
                 edgecolor='black',
                 linewidth=0.5,
                 alpha=float(alpha))
        i += 1

    ax1.set_ylabel(options.ylabel)
    for tl in ax1.get_yticklabels():
        tl.set_color('k')

    ax1.set_xlabel(options.xlabel)
    #ax1.set_title('Classifier performance.')
    if len(columns) > 1:
        ax1.legend(columns, loc=1, frameon=False)
    elif leglabels is not None:
        ax1.legend(leglabels, loc=1, frameon=False)

    ax1.text(0.8,
             0.95,
             options.plotlabel,
             transform=ax1.transAxes,
             va='top',
             size=MEDIUM_SIZE)
    ax1.text(0.1,
             0.95,
             options.panellabel,
             transform=ax1.transAxes,
             va='top',
             size=MEDIUM_SIZE,
             weight='bold')

    ml = MultipleLocator(float(options.minorticks))
    ax1.xaxis.set_minor_locator(ml)
    ax1.get_xaxis().set_tick_params(which='both', direction='out')
    ax1.set_xlim(float(options.binlower), float(options.binupper))

    ax1.set_ylim(ymin=0)
    if options.ylimit:
        ax1.set_ylim(1, float(options.ylimit))

    if options.log:
        ax1.set_yscale('log')

    if options.threshold is not None:
        ax1.axvline(x=float(options.threshold), color='k', linestyle='--')

    plt.tight_layout()

    if options.outputFile is not None:
        plt.savefig(options.outputFile)
    else:
        plt.show()
Exemplo n.º 23
0
def plot_average_prices(results_dir, output_dir):
    """Plot average prices under different schemes"""

    # Prices from different models
    p_bau = analysis.get_average_prices(results_dir, 'bau_case.pickle', None,
                                        'PRICES', -1)
    p_rep = analysis.get_average_prices(results_dir, 'rep_case.pickle',
                                        'stage_2_rep', 'PRICES', -1)
    p_tax = analysis.get_average_prices(results_dir, 'rep_case.pickle',
                                        'stage_1_carbon_tax', 'PRICES', -1)
    p_price_dev_mppdc = analysis.get_average_prices(
        results_dir, 'mppdc_price_change_deviation_case.pickle',
        'stage_3_price_targeting', 'lamb', 1)
    p_price_dev_heuristic = analysis.get_average_prices(
        results_dir, 'heuristic_price_change_deviation_case.pickle',
        'stage_3_price_targeting', 'PRICES', -1)

    # Create figures
    c = cl.to_numeric(
        cl.flipper()['qual']['5']['Set1']
    )  # ['Accent', 'Dark2', 'Paired', 'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3'])
    fig, ax = plt.subplots()
    ax.plot(p_bau.index.tolist(),
            p_bau['average_price_real'].tolist(),
            color=scale_rgb(c[1]),
            alpha=0.7,
            linewidth=0.9)
    ax.plot(p_tax.index.tolist(),
            p_tax['average_price_real'].tolist(),
            color=scale_rgb(c[0]),
            alpha=0.7,
            linewidth=0.9)
    ax.plot(p_rep.index.tolist(),
            p_rep['average_price_real'].tolist(),
            color=scale_rgb(c[2]),
            alpha=0.7,
            linewidth=0.9)
    ax.plot(p_price_dev_mppdc.index.tolist(),
            p_price_dev_mppdc['average_price_real'].tolist(),
            color=scale_rgb(c[3]),
            alpha=0.7,
            linewidth=0.9)
    ax.plot(p_price_dev_heuristic.index.tolist(),
            p_price_dev_heuristic['average_price_real'].tolist(),
            color=scale_rgb(c[4]),
            alpha=0.6,
            linewidth=0.9)

    fig.set_size_inches(3, 2.3)

    ax.set_ylabel('Average price ($/MWh)', fontsize=9, labelpad=-0.1)
    ax.set_xlabel('Year', fontsize=9)
    ax.tick_params(labelsize=8)
    ax.xaxis.set_major_locator(MultipleLocator(5))
    ax.xaxis.set_minor_locator(MultipleLocator(1))
    ax.yaxis.set_major_locator(MultipleLocator(20))
    ax.yaxis.set_minor_locator(MultipleLocator(5))

    ax.legend(['BAU', 'Tax', 'REP', 'MPPDC', 'Heuristic'],
              fontsize=7,
              ncol=2,
              frameon=False)
    fig.subplots_adjust(left=0.16, bottom=0.18, top=0.98, right=0.98)
    fig.savefig(os.path.join(output_dir, 'average_prices.png'))
    fig.savefig(os.path.join(output_dir, 'average_prices.pdf'))

    plt.show()
Exemplo n.º 24
0
  100.0  16310  -62.5  -73.5     21   0.02    285     36  406.7  406.8  406.7
    '''

    # Parse the data
    sound_data = StringIO(data_txt)
    p, h, T, Td = np.loadtxt(sound_data, usecols=range(0, 4), unpack=True)

    # Create a new figure. The dimensions here give a good aspect ratio
    fig = plt.figure(figsize=(6.5875, 6.2125))
    ax = fig.add_subplot(111, projection='skewx')

    plt.grid(True)

    # Plot the data using normal plotting functions, in this case using
    # log scaling in Y, as dicatated by the typical meteorological plot
    ax.semilogy(T, p, 'r')
    ax.semilogy(Td, p, 'g')

    # An example of a slanted line at constant X
    l = ax.axvline(0, color='b')

    # Disables the log-formatting that comes with semilogy
    ax.yaxis.set_major_formatter(ScalarFormatter())
    ax.set_yticks(np.linspace(100, 1000, 10))
    ax.set_ylim(1050, 100)

    ax.xaxis.set_major_locator(MultipleLocator(10))
    ax.set_xlim(-50, 50)

    plt.show()
Exemplo n.º 25
0
         ms=8,
         mec="#7E2320",
         mew=2)  # set properties

axes.set_xlim(0, None)  # limit for xaxis
axes.set_ylim(None, 0)  # leave the ymax auto, but fix ymin
axes.set_xlabel(r"$k_{\rm B}T$ / $J$", labelpad=8)
axes.set_ylabel(r"$\kappa_{\rm xy}$ / $T$", labelpad=8)

##///Set ticks space and minor ticks space ///#
xtics = 0.3  # space between two ticks
mxtics = xtics / 2.  # space between two minor ticks

majorFormatter = FormatStrFormatter(
    '%g')  # put the format of the number of ticks

axes.xaxis.set_major_locator(MultipleLocator(xtics))
axes.xaxis.set_major_formatter(majorFormatter)
axes.xaxis.set_minor_locator(MultipleLocator(mxtics))
axes.yaxis.set_major_formatter(FormatStrFormatter('%.3f'))

axes.locator_params(axis='y', nbins=6)

plt.show()

folder = "../figures_sim/"
figure_name = "TS-kxy" + "_B_" + str(B) + "_J_" + str(J) + "_D_" + str(
    D) + "_res_" + str(resolution_k) + ".pdf"
fig.savefig(folder + figure_name, bbox_inches="tight")

#//////////////////////////////////////////////////////////////////////////////#
Exemplo n.º 26
0
Arquivo: gcn.py Projeto: ustchhy/dgl
def run(args, graph, labels, train_idx, val_idx, test_idx, evaluator, n_running):
    # define model and optimizer
    model = gen_model(args)
    model = model.to(device)

    optimizer = optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.wd)
    lr_scheduler = optim.lr_scheduler.ReduceLROnPlateau(
        optimizer, mode="min", factor=0.5, patience=100, verbose=True, min_lr=1e-3
    )

    # training loop
    total_time = 0
    best_val_acc, best_test_acc, best_val_loss = 0, 0, float("inf")

    accs, train_accs, val_accs, test_accs = [], [], [], []
    losses, train_losses, val_losses, test_losses = [], [], [], []

    for epoch in range(1, args.n_epochs + 1):
        tic = time.time()

        adjust_learning_rate(optimizer, args.lr, epoch)

        loss, pred = train(model, graph, labels, train_idx, optimizer, args.use_labels)
        acc = compute_acc(pred[train_idx], labels[train_idx], evaluator)

        train_acc, val_acc, test_acc, train_loss, val_loss, test_loss = evaluate(
            model, graph, labels, train_idx, val_idx, test_idx, args.use_labels, evaluator
        )

        lr_scheduler.step(loss)

        toc = time.time()
        total_time += toc - tic

        # if val_acc > best_val_acc:
        if val_loss < best_val_loss:
            best_val_loss = val_loss
            best_val_acc = val_acc
            best_test_acc = test_acc

        if epoch % args.log_every == 0:
            print(f"Epoch: {epoch}/{args.n_epochs}")
            print(
                f"Loss: {loss.item():.4f}, Acc: {acc:.4f}\n"
                f"Train/Val/Test loss: {train_loss:.4f}/{val_loss:.4f}/{test_loss:.4f}\n"
                f"Train/Val/Test/Best val/Best test acc: {train_acc:.4f}/{val_acc:.4f}/{test_acc:.4f}/{best_val_acc:.4f}/{best_test_acc:.4f}"
            )

        for l, e in zip(
            [accs, train_accs, val_accs, test_accs, losses, train_losses, val_losses, test_losses],
            [acc, train_acc, val_acc, test_acc, loss, train_loss, val_loss, test_loss],
        ):
            l.append(e)

    print("*" * 50)
    print(f"Average epoch time: {total_time / args.n_epochs}, Test acc: {best_test_acc}")

    if args.plot_curves:
        fig = plt.figure(figsize=(24, 24))
        ax = fig.gca()
        ax.set_xticks(np.arange(0, args.n_epochs, 100))
        ax.set_yticks(np.linspace(0, 1.0, 101))
        ax.tick_params(labeltop=True, labelright=True)
        for y, label in zip([accs, train_accs, val_accs, test_accs], ["acc", "train acc", "val acc", "test acc"]):
            plt.plot(range(args.n_epochs), y, label=label)
        ax.xaxis.set_major_locator(MultipleLocator(100))
        ax.xaxis.set_minor_locator(AutoMinorLocator(1))
        ax.yaxis.set_major_locator(MultipleLocator(0.01))
        ax.yaxis.set_minor_locator(AutoMinorLocator(2))
        plt.grid(which="major", color="red", linestyle="dotted")
        plt.grid(which="minor", color="orange", linestyle="dotted")
        plt.legend()
        plt.tight_layout()
        plt.savefig(f"gcn_acc_{n_running}.png")

        fig = plt.figure(figsize=(24, 24))
        ax = fig.gca()
        ax.set_xticks(np.arange(0, args.n_epochs, 100))
        ax.tick_params(labeltop=True, labelright=True)
        for y, label in zip(
            [losses, train_losses, val_losses, test_losses], ["loss", "train loss", "val loss", "test loss"]
        ):
            plt.plot(range(args.n_epochs), y, label=label)
        ax.xaxis.set_major_locator(MultipleLocator(100))
        ax.xaxis.set_minor_locator(AutoMinorLocator(1))
        ax.yaxis.set_major_locator(MultipleLocator(0.1))
        ax.yaxis.set_minor_locator(AutoMinorLocator(5))
        plt.grid(which="major", color="red", linestyle="dotted")
        plt.grid(which="minor", color="orange", linestyle="dotted")
        plt.legend()
        plt.tight_layout()
        plt.savefig(f"gcn_loss_{n_running}.png")

    return best_val_acc, best_test_acc
    ax.set_ylabel("Counts")
    ax.set_xticklabels([])
    ax.set_xticks([])
    ax.legend(["2b SR NN Regression", "2b SR Data"])

    ratio = [m / d if d > 0 else 100 for m, d in zip(modelmhh, datamhh)]
    err = [r / np.sqrt(d) if d > 0 else 0 for r, d in zip(ratio, datamhh)]
    ax = plt.subplot(gs[1])
    print(ratio)
    ax.errorbar(XData, ratio, yerr=err, fmt='k.')
    ax.plot([mhhbins[0], mhhbins[-1]], [1, 1], 'k--', linewidth=1)
    ax.set_ylim(0.75, 1.25)
    ax.set_ylim(0.9, 1.1)
    ax.set_xlabel("$m_{hh}$" + " (GeV)")
    ax.set_ylabel("Pred./Data")
    ax.yaxis.set_major_locator(MultipleLocator(0.05))
    ax.yaxis.set_minor_locator(MultipleLocator(0.01))
    ax.xaxis.set_major_locator(MultipleLocator(100))
    ax.xaxis.set_minor_locator(MultipleLocator(25))
    plt.savefig(ModelName + "mhhSR.png")
    plt.show()
else:
    modeldfSR = modeldf.loc[binInSR(modeldf["m_h1"], modeldf["m_h2"])]
    modelmhh = list(integrate_fmp(modeldfSR)["pdf"])
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.step(mhhbins, modelmhh + [modelmhh[-1]], 'r', linewidth=2, where='post')
    ax.set_xlabel("$m_{hh}$" + " (GeV)")
    ax.set_ylabel("Counts")
    ax.legend(["4b SR NN Regression"])
    ax.xaxis.set_major_locator(MultipleLocator(100))
Exemplo n.º 28
0
             label='Initial UHG',
             ls='--',
             linewidth='3',
             zorder=5,
             alpha=0.75)
    #ax1.fill_between(x,UHG_flow,facecolor='gray', alpha=0.25)

    #ax1.minorticks_on()
    ax1.grid(which='major',
             axis='both',
             color='black',
             linestyle='-',
             zorder=3)
    ax1.grid(which='minor', axis='both', color='grey', linestyle='-', zorder=3)

    majorLocator = MultipleLocator(interval)
    ax1.xaxis.set_major_locator(majorLocator)

    ax1.yaxis.set_minor_locator(AutoMinorLocator(2))

    ax1.set_xlabel('Time (hr)')
    ax1.set_ylabel('Flow (cfs)')

    #Make tick labels smaller/rotate for long UHGs
    if num_ordinates >= 15:
        for label in ax1.xaxis.get_ticklabels():
            label.set_fontsize(8)
            plt.xticks(rotation=90)
    if num_ordinates >= 24:
        for label in ax1.xaxis.get_ticklabels():
            label.set_fontsize(6)
Exemplo n.º 29
0
plt.figure()
ax = plt.gca()
for fname in fnames:
    print(fname)
    curve = np.load(fname)
    print((curve[-1, 0] - curve[0, 0]) / 3600)
    last = curve[0]
    c_v = [[0, curve[0, 2], curve[0, 3]]]
    for x in curve[1:]:
        #print(x)
        time_diff = x[0] - last[0]
        Ah = time_diff / 3600 * -x[1]
        c_v.append([c_v[-1][0] + Ah, x[2], x[3]])
        last = x
    print(np.array(c_v[-1]))
    c_v = np.array(c_v)
    plt.plot(c_v[:, 0] * 1E3,
             c_v[:, 2],
             label=fname.split("_")[-1].split(".npy")[0])
    #plt.plot(curve[:,3].astype('float'))
lgd = ax.legend()
plt.grid(True, 'both', 'both')
ml = MultipleLocator(1)
ax.xaxis.set_minor_locator(ml)
ax.axhline(y=2.35, lw=1, color='r')
ax.axhline(y=2.33, lw=1, color='r')
plt.ylabel('Cell Voltage')
plt.xlabel('Capacity Discharged (mAh)')
plt.savefig('plot.pdf', format='pdf')
Exemplo n.º 30
0
#!/usr/bin/python

import sys
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import pandas
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

plt.clf()
fig=plt.figure(figsize=(40, 40))
ax = fig.add_subplot(111)
mat=pandas.read_csv(sys.argv[1],header=0,index_col=0)
# min=0 and max=1 is set to just distinguish absent and present
# remove those parameters to see colors scaled by value
ax.matshow(mat,cmap=cm.gray, interpolation='nearest', vmin=0, vmax=1)
locator=MultipleLocator(1)
locator.MAXTICKS = 10000
ax.xaxis.set_major_locator(locator)
ax.set_xticklabels([""]+mat.columns.tolist(), rotation=90)
ax.yaxis.set_major_locator(MultipleLocator(1))
ax.yaxis.set_major_formatter(FormatStrFormatter('%s'))
ax.set_yticklabels([""]+mat.index.tolist())
ax.tick_params(axis='both', which='both', labelsize=8, direction='out',
                       labelleft='on', labelright='off', labelbottom='off',
                       labeltop='on', left='on', right='off', bottom='off',
                       top='on')
plt.savefig(sys.argv[2], bbox_inches='tight', dpi = 100)

Exemplo n.º 31
0
def makeKlusterImage(klusterid, kl, outputpath):
    """ Create the kluster image. """

    # FIXME: Make configurable.

    pixels = kl.getPixelMap()

    x_min = kl.getXMin()

    x_max = kl.getXMax()

    y_min = kl.getYMin()

    y_max = kl.getYMax()

    w = kl.getWidth()

    h = kl.getHeight()

    ## The maximum count value.
    C_max = kl.getMaxCountValue()

    x_bar = kl.getXUW()

    y_bar = kl.getYUW()

    radius = kl.getRadiusUW()

    m, c, sumR = kl.getLineOfBestFitValues()

    # Create the figure.
    plt.close('all')

    figsize = 5.0

    ## The figure for the cluster image.
    blobfig = plt.figure(1,
                         figsize=(figsize * 1.27, figsize),
                         dpi=150,
                         facecolor='w',
                         edgecolor='w')

    # Set the beyond-frame background colour.
    blobfigax = blobfig.add_subplot(111, axisbg='#222222')

    # Add the frame background (blue).
    blobfigax.add_patch(plt.Rectangle((0, 0), 256, 256, facecolor='#82bcff'))

    # Add a grid.
    plt.grid(1)

    # Select the "hot" colour map for the pixel counts.

    cmap = plt.cm.hot

    colax, _ = colorbar.make_axes(plt.gca())

    col_max = 10 * (np.floor(C_max / 10.) + 1)

    colorbar.ColorbarBase(colax,
                          cmap=cmap,
                          norm=colors.Normalize(vmin=0, vmax=col_max))

    # Add the line of best fit.
    addLineOfBestFit(blobfigax, m, c)

    # Add the radius circle.
    addRadiusCircle(blobfigax, x_bar, y_bar, radius)

    # Loop over the pixels and plot them.
    for X, C in pixels.iteritems():
        x = X % 256
        y = X / 256
        scaled_C = float(C) / float(col_max)
        blobfigax.add_patch(
            plt.Rectangle((x, y), 1, 1, facecolor=cmap(scaled_C)))

    # Set the axis limits based on the cluster radius.
    b = 3  # border

    xlim_min = x_bar - (np.floor(radius) + b)
    xlim_max = x_bar + (np.floor(radius) + b)
    ylim_min = y_bar - (np.floor(radius) + b)
    ylim_max = y_bar + (np.floor(radius) + b)

    blobfigax.set_xlim([xlim_min, xlim_max])
    blobfigax.set_ylim([ylim_min, ylim_max])

    # Set the axis tick mark spacing.
    blobfigax.xaxis.set_major_locator(MultipleLocator(10))
    blobfigax.yaxis.set_major_locator(MultipleLocator(10))

    # Save the figure.
    blobfig.savefig(outputpath + "/%s.png" % (klusterid))