Пример #1
0
def meijaard_figure_four(time, rollRate, steerRate, speed):
    width = 4.0 # inches
    golden_ratio = (np.sqrt(5.0) - 1.0) / 2.0
    height = width * golden_ratio
    fig = figure()
    fig.set_size_inches([width, height])
    params = {'backend': 'ps',
              'axes.labelsize': 10,
              'text.fontsize': 10,
              'legend.fontsize': 10,
              'xtick.labelsize': 8,
              'ytick.labelsize': 8,
              'text.usetex': True}
    rcParams.update(params)

    fig.subplots_adjust(right=0.85, left=0.15, bottom=0.15)
    rateAxis = fig.add_subplot(111)
    speedAxis = rateAxis.twinx()

    p1, = rateAxis.plot(time, rollRate, "k--",label="Roll Rate")
    p2, = rateAxis.plot(time, steerRate, "k:", label="Steer Rate")
    p3, = speedAxis.plot(time, speed, "k-", label="Speed")

    rateAxis.set_ylim(-0.5, 1.0)
    rateAxis.set_yticks([-0.5, 0.0, 0.5, 1.0])
    rateAxis.set_xticks([0., 1., 2., 3., 4., 5.])
    rateAxis.set_xlabel('Time [sec]')
    rateAxis.set_ylabel('Angular Rate [rad/sec]')
    lines = [p1, p2, p3]
    rateAxis.legend(lines, [l.get_label() for l in lines])
    speedAxis.set_ylim(4.55, 4.7)
    speedAxis.set_yticks([4.55, 4.60, 4.65, 4.70])
    speedAxis.set_ylabel('Speed [m/s]')

    return fig
Пример #2
0
def meijaard_figure_four(time, rollRate, steerRate, speed):
    width = 4.0 # inches
    golden_ratio = (np.sqrt(5.0) - 1.0) / 2.0
    height = width * golden_ratio
    fig = figure()
    fig.set_size_inches([width, height])
    params = {'backend': 'ps',
              'axes.labelsize': 10,
              'text.fontsize': 10,
              'legend.fontsize': 10,
              'xtick.labelsize': 8,
              'ytick.labelsize': 8,
              'text.usetex': True}
    rcParams.update(params)

    fig.subplots_adjust(right=0.85, left=0.15, bottom=0.15)
    rateAxis = fig.add_subplot(111)
    speedAxis = rateAxis.twinx()

    p1, = rateAxis.plot(time, rollRate, "k--",label="Roll Rate")
    p2, = rateAxis.plot(time, steerRate, "k:", label="Steer Rate")
    p3, = speedAxis.plot(time, speed, "k-", label="Speed")

    rateAxis.set_ylim(-0.5, 1.0)
    rateAxis.set_yticks([-0.5, 0.0, 0.5, 1.0])
    rateAxis.set_xticks([0., 1., 2., 3., 4., 5.])
    rateAxis.set_xlabel('Time [sec]')
    rateAxis.set_ylabel('Angular Rate [rad/sec]')
    lines = [p1, p2, p3]
    rateAxis.legend(lines, [l.get_label() for l in lines])
    speedAxis.set_ylim(4.55, 4.7)
    speedAxis.set_yticks([4.55, 4.60, 4.65, 4.70])
    speedAxis.set_ylabel('Speed [m/s]')

    return fig
Пример #3
0
def plot_infection(trial_exposures, blocking=True, multiple=False, leg=None, title=None, file_name=None, size=None, font_size=None, leg_loc=None):
    size = fig_size if size is None else size
    font_size = plot_font_size if font_size is None else font_size
    steps = len(trial_exposures) if not multiple else len(trial_exposures[0])
    fig = figure(title, figsize=size)
    rcParams.update({'font.size': font_size})
    ax = fig.gca()

    if multiple:
        for data in trial_exposures:
            ax.plot(data, linewidth=plot_line_width)
    else:
        ax.plot(trial_exposures, linewidth=plot_line_width)

    ax.set_ylim(.2, .8)
    ax.set_xlim(0, steps)
    xlabel('Time Steps, n')
    ylabel('Network Infection')

    if title is not None: ax.set_title(title)
    if leg is not None and leg_loc is None: legend(leg)
    elif leg_loc is not None: legend(leg, bbox_to_anchor=leg_loc, loc='upper left')

    if file_name is not None:
        try: savefig(file_name, bbox_inches='tight', pad_inches=0)
        except FileExistsError: pass

    if blocking:
        show()
Пример #4
0
    def plot_timestep_convergence(self):
        from matplotlib.pyplot import figure,subplot,xlabel,ylabel,plot,errorbar,title,text,xticks,rcParams,savefig,xlim

        params = {'legend.fontsize':14,'figure.facecolor':'white','figure.subplot.hspace':0.,
          'axes.labelsize':16,'xtick.labelsize':14,'ytick.labelsize':14}
        rcParams.update(params) 


        timesteps = self.timesteps
        energies  = convert(self.energies.copy(),'Ha','eV')
        errors    = convert(self.errors.copy(),'Ha','eV')
        Esmall = energies[0]

        figure()
        tsrange = [0,1.1*timesteps[-1]]
        plot(tsrange,[0,0],'k-')
        errorbar(timesteps,energies-Esmall,errors,fmt='k.')
        text(array(tsrange).mean(),0,'{0:6.4f} eV'.format(Esmall))
        xticks(timesteps)
        xlim(tsrange)
        xlabel('Timestep (Ha)')
        ylabel('Total Energy (eV)')
        title('DMC Timestep Convergence')

        savefig('TimestepConvergence.png',format='png',bbox_inches ='tight',pad_inches=1)
Пример #5
0
def main():
    assert len(argv) == 3
    with open(argv[1], "r") as file:
        line = file.readline()
    if "." in line:
        x = loadtxt(argv[1], dtype="float32", delimiter="\n")
        kwargs = {"discrete": False}
    else:
        x = loadtxt(argv[1], dtype="int32", delimiter="\n")
        kwargs = {"discrete": True}
    rcParams.update({"font.family": "monospace"})
    (_, ax) = subplots(figsize=(9, 6))
    histplot(x, kde=False, color="darkgray", ec="w", ax=ax, **kwargs)
    ax.set_ylabel(None)
    kwargs = {
        "lw": 3,
        "ls": "--",
        "alpha": 0.625,
    }
    m = mean(x)
    ax.axvline(m, label=f"mean   => {m:.2f}", c="blue", **kwargs)
    m = median(x)
    ax.axvline(m, label=f"median => {m:.2f}", c="red", **kwargs)
    ax.legend()
    tight_layout()
    savefig(argv[2])
    close()
Пример #6
0
    def make_skewt_axes(self,pmax=1050.,pmin=100.):
	
	self.fig = figure(figsize=(7,8))
	self.fig.clf()
	
	rcParams.update({\
		'font.size':10,\
		})

	self.skewxaxis=self.fig.add_axes([.085,.1,.83,.8], projection='skewx')
	self.skewxaxis.set_yscale('log')

	xticklocs=arange(-80,45,10)
	T0 = xticklocs

	P=linspace(pmax,pmin,37)

	w = array([0.0001,0.0004,0.001, 0.002, 0.004, 0.007, 0.01, 0.016, 0.024, 0.032])
	self.skewxaxis.add_mixratio_isopleths(w,P[P>=550],color='purple',ls='--',alpha=1.,lw=0.5)
	self.skewxaxis.add_dry_adiabats(linspace(250,440,20)-273.15,P,color='red',ls='--',alpha=1.,lw=0.5)
	self.skewxaxis.add_moist_adiabats(linspace(8,32,7),P[P>=200],color='g',ls='--',alpha=1.,lw=0.5)
	self.skewxaxis.other_housekeeping()

	self.wbax=self.fig.add_axes([0.815,0.1,0.1,0.8],sharey=self.skewxaxis,frameon=False)
	self.wbax.xaxis.set_ticks([],[])
	self.wbax.yaxis.grid(True,ls='-',color='y',lw=0.5)
	for tick in self.wbax.yaxis.get_major_ticks():
	    # tick.label1On = False
	    pass
	self.wbax.get_yaxis().set_tick_params(size=0,color='y')
	self.wbax.set_xlim(-1.5,1.5)
	self.wbax.get_yaxis().set_visible(False)

	# Set up standard atmosphere height scale on 
	# LHS of plot. It's jus
	majorLocatorKM   = MultipleLocator(2)
	majorLocatorKFT  = MultipleLocator(5)
	minorLocator     = MultipleLocator(1)

	self.kmhax=self.fig.add_axes([0.915,0.1,1e-6,0.8],frameon=True)
	self.kmhax.xaxis.set_ticks([],[])
	self.kmhax.spines['left'].set_color('k')
	self.kmhax.spines['right'].set_visible(False)
	self.kmhax.tick_params(axis='y', colors='k',labelsize=10)
	self.kmhax.set_ylim(0,16.18)
	self.kmhax.set_title("km/kft",fontsize=12)
	self.kmhax.get_yaxis().set_tick_params(which="both",direction='out')
	self.kmhax.yaxis.set_major_locator(majorLocatorKM)
	self.kmhax.yaxis.set_minor_locator(minorLocator)

	self.fthax=self.kmhax.twinx()
	self.fthax.xaxis.set_ticks([],[])
	self.fthax.tick_params(axis='y', colors='k',labelsize=10)
	self.fthax.set_ylim(0,53.084)
	self.fthax.get_yaxis().set_tick_params(which="both",direction='out')
	self.fthax.yaxis.set_major_locator(majorLocatorKFT)
	self.fthax.yaxis.set_minor_locator(minorLocator)
Пример #7
0
def ploter(plot1, cv1, plot2, cv2, plot3, cv3, args):
    rcParams['figure.figsize'] = args['size']  # 16, 8
    floor = 1
    factor = 0.9
    gap = 0.4
    intensity = 0.9
    if len(cv1):
        points = len(plot1)
        limit_cv = float(max(cv1))
        for n, c in zip(xrange(points - 1), cv1):
#            if c != 0:
#                intensity = factor * (floor + ((c * (1 - floor)) / limit_cv))
#            else:
#                intensity = gap
            plot([plot1[n][0], plot1[n + 1][0]],
                 [plot1[n][1], plot1[n + 1][1]], color=(0, intensity, intensity))
    if len(cv2):
        points = len(plot2)
        limit_cv = float(max(cv2))
        for n, c in zip(xrange(points - 1), cv2):
#            if c != 0:
#                intensity = factor * (floor + ((c * (1 - floor)) / limit_cv))
#            else:
#                intensity = gap
            plot([plot2[n][0], plot2[n + 1][0]],
                 [plot2[n][1], plot2[n + 1][1]], color=(intensity, 0, intensity))
    if len(cv3):
        points = len(plot3)
        limit_cv = float(max(cv3))
        for n, c in zip(xrange(points - 1), cv3):
#            if c != 0:
#                intensity = factor * (floor + ((c * (1 - floor)) / limit_cv))
#            else:
#                intensity = gap
            plot([plot3[n][0], plot3[n + 1][0]],
                 [plot3[n][1], plot3[n + 1][1]], color=(intensity, intensity, 0))
    # plot(x1, y1, '#009999', x2, y2, '#990099', x3, y3, '#999900', linewidth=
    # 1.3)
    title(args['title'])
    xlimit = args['xlim']
    ylimit = args['ylim']
    if (xlimit[0] != 0 or xlimit[1] != 0) and (type(xlimit[0]) == type(xlimit[1]) == float):
        xlim(xlimit)
    else:
        xlimit = (1, max([len(plot1), len(plot2), len(plot3)]))
        xlim(xlimit)
    if (ylimit[0] != 0 or ylimit[1] != 0) and (type(ylimit[0]) == type(ylimit[1]) == float):
        ylim(ylimit)
# else:
# ny = [y for y in y1 + y2 + y3 if y is not None]
# ylimit = (min(ny) - 1, max(ny) + 1)
# ylim(ylimit)
    rcParams.update({'font.size': args['font_size']})
    savefig(args['outfile'], bbox_inches=0)
    show()
    clf()
Пример #8
0
def draw_png(filename, saveDir):
    dict = readXDC(filename)
    name = filename.split('/')[-1].split('.', 1)[0]
    if not os.path.exists(saveDir):
        os.makedirs(saveDir)

    keys = list(dict.keys())  # keys are integer, which is block index

    width = 560 + gap * (len(vu11p) - 1)
    height = 5414.4 if len(keys) > 80 else 1000
    fontsize = 80 if len(keys) > 80 else 40
    rcParams.update({'font.size': fontsize})

    # draw transparent polygons on a new image
    fig, ax = plt.subplots(figsize=(256,100))
    fig.set_size_inches(width / 100, height / 100)
    ax.set_xlim(0, width + 20)
    ax.set_ylim(0, height + 20)
    rect = patches.Rectangle((10, 10), width, height, linewidth=1, facecolor='#f6f6f6')
    ax.add_patch(rect)
    drawBackGround(ax, width, height, gap)
    for j in range(len(keys)):
        key = keys[j]
        entries = dict.get(key)
        sites = np.zeros(shape=(len(entries) * 4, 2))
        for pair in entries:
            site = pair[0]
            x = 0
            y = 0
            if site.startswith('DSP'):
                x, y = drawDSP(ax, site, gap, dsp_block)
            elif site.startswith('RAMB'):
                x, y = drawBRAM(ax, site, gap, bram_block)
            elif site.startswith('URAM'):
                x, y = drawURAM(ax, site, gap, uram_block)

            for index in range(4):
                sites[entries.index(pair) * 4 + index, 0] = x[index]
                sites[entries.index(pair) * 4 + index, 1] = y[index]
        drawTiles(ax, sites, '#000000')
    # add axis
    legend_elements = [
        Patch(facecolor=dsp_block, label='DSP48'),
        Patch(facecolor=bram_block, label='BRAM'),
        Patch(facecolor=uram_block, label='URAM')
    ]

    # ax.legend(handles=legend_elements, prop={'size':13})

    # plt.savefig(saveDir + name + '.png', dpi=50)
    # plt.close()
    plt.savefig(saveDir + name + '.pdf')
    plt.close()
    print(saveDir + name + '.pdf')
    return saveDir + name + '.pdf'
Пример #9
0
def meijaard_figure_four(time, rollRate, steerRate, speed):
    """Returns a figure that matches Figure #4 in [Meijaard2007]_.

    References
    ----------

    .. [Meijaard2007]_ J. P. Meijaard, Jim M. Papadopoulos, Andy Ruina, and A.
       L. Schwab. Linearized dynamics equations for the balance and steer of a
       bicycle: A benchmark and review. Proceedings of the Royal Society A:
       Mathematical, Physical and Engineering Sciences, 463(2084):1955–1982,
       August 2007.

    """
    width = 4.0  # inches
    golden_ratio = (np.sqrt(5.0) - 1.0) / 2.0
    height = width * golden_ratio
    fig = figure()
    fig.set_size_inches([width, height])
    params = {
        'backend': 'ps',
        'axes.labelsize': 10,
        'text.fontsize': 10,
        'legend.fontsize': 10,
        'xtick.labelsize': 8,
        'ytick.labelsize': 8,
        'text.usetex': True
    }
    rcParams.update(params)

    fig.subplots_adjust(right=0.85, left=0.15, bottom=0.15)
    rateAxis = fig.add_subplot(111)
    speedAxis = rateAxis.twinx()

    p1, = rateAxis.plot(time, rollRate, "k--", label="Roll Rate")
    p2, = rateAxis.plot(time, steerRate, "k:", label="Steer Rate")
    p3, = speedAxis.plot(time, speed, "k-", label="Speed")

    rateAxis.set_ylim(-0.5, 1.0)
    rateAxis.set_yticks([-0.5, 0.0, 0.5, 1.0])
    rateAxis.set_xticks([0., 1., 2., 3., 4., 5.])
    rateAxis.set_xlabel('Time [sec]')
    rateAxis.set_ylabel('Angular Rate [rad/sec]')
    lines = [p1, p2, p3]
    rateAxis.legend(lines, [l.get_label() for l in lines])
    speedAxis.set_ylim(4.55, 4.7)
    speedAxis.set_yticks([4.55, 4.60, 4.65, 4.70])
    speedAxis.set_ylabel('Speed [m/s]')

    return fig
Пример #10
0
def everything(datfile,
               volSample,
               pSal,
               totalCarbonate,
               totalPhosphate,
               totalSilicate,
               concAcid,
               WhichKs=10,
               WhoseKSO4=1,
               WhoseKF=1,
               WhoseTB=2,
               totalAmmonia=0,
               totalH2Sulfide=0):
    """Plot everything for a single titration from a VINDTA-style .dat file."""
    (massAcid, emf, massSample, f1Guess, LGuess, alkGuess, emf0Guess, granEmf0,
     alk_emf0, alkSim, alk0Sim, RMS, Npts,
     rgb) = prep(datfile,
                 volSample,
                 pSal,
                 totalCarbonate,
                 totalPhosphate,
                 totalSilicate,
                 concAcid,
                 WhichKs=WhichKs,
                 WhoseKSO4=WhoseKSO4,
                 WhoseKF=WhoseKF,
                 WhoseTB=WhoseTB,
                 totalAmmonia=totalAmmonia,
                 totalH2Sulfide=totalH2Sulfide)
    fig = figure(figsize=[17, 10])
    rcParams.update({'font.size': 10})
    gs = fig.add_gridspec(4, 2)
    subplots_adjust(wspace=0.3, hspace=0.8)
    ax1 = fig.add_subplot(gs[0, 0])
    emfTitration(ax1, massAcid, emf, massSample, concAcid, alk_emf0, alkGuess,
                 rgb, '(a)')
    ax2 = fig.add_subplot(gs[1, 0])
    f1Gran(ax2, massAcid, massSample, concAcid, f1Guess, alkGuess, rgb, '(b)')
    ax3 = fig.add_subplot(gs[2, 0])
    emf0Estimates(ax3, massAcid, massSample, concAcid, granEmf0, emf0Guess,
                  alkGuess, LGuess, rgb, '(c)')
    ax4 = fig.add_subplot(gs[3, 0])
    alkTitration(ax4, massAcid, alkSim, rgb, '(d)')
    ax5 = fig.add_subplot(gs[0, 1])
    alkEstimates(ax5, massAcid, alk0Sim, rgb, alk_emf0, RMS, Npts, '(e)')
    ax6 = fig.add_subplot(gs[1:4, 1])
    components(ax6, massAcid, alk0Sim, alkSim, '(f)')
    return fig
Пример #11
0
def meijaard_figure_four(time, rollRate, steerRate, speed):
    """Returns a figure that matches Figure #4 in [Meijaard2007]_.

    References
    ----------

    .. [Meijaard2007]_ J. P. Meijaard, Jim M. Papadopoulos, Andy Ruina, and A.
       L. Schwab. Linearized dynamics equations for the balance and steer of a
       bicycle: A benchmark and review. Proceedings of the Royal Society A:
       Mathematical, Physical and Engineering Sciences, 463(2084):1955–1982,
       August 2007.

    """
    width = 4.0  # inches
    golden_ratio = (np.sqrt(5.0) - 1.0) / 2.0
    height = width * golden_ratio
    fig = figure()
    fig.set_size_inches([width, height])
    params = {'backend': 'ps',
              'axes.labelsize': 10,
              'text.fontsize': 10,
              'legend.fontsize': 10,
              'xtick.labelsize': 8,
              'ytick.labelsize': 8,
              'text.usetex': True}
    rcParams.update(params)

    fig.subplots_adjust(right=0.85, left=0.15, bottom=0.15)
    rateAxis = fig.add_subplot(111)
    speedAxis = rateAxis.twinx()

    p1, = rateAxis.plot(time, rollRate, "k--", label="Roll Rate")
    p2, = rateAxis.plot(time, steerRate, "k:", label="Steer Rate")
    p3, = speedAxis.plot(time, speed, "k-", label="Speed")

    rateAxis.set_ylim(-0.5, 1.0)
    rateAxis.set_yticks([-0.5, 0.0, 0.5, 1.0])
    rateAxis.set_xticks([0., 1., 2., 3., 4., 5.])
    rateAxis.set_xlabel('Time [sec]')
    rateAxis.set_ylabel('Angular Rate [rad/sec]')
    lines = [p1, p2, p3]
    rateAxis.legend(lines, [l.get_label() for l in lines])
    speedAxis.set_ylim(4.55, 4.7)
    speedAxis.set_yticks([4.55, 4.60, 4.65, 4.70])
    speedAxis.set_ylabel('Speed [m/s]')

    return fig
Пример #12
0
def plot(data, samples, sims):
    rcParams.update({"font.family": "monospace"})
    fig = figure(figsize=(14, 13.5), dpi=75)
    gs = GridSpec(2, 3, figure=fig, height_ratios=[1, 4])
    ax0 = fig.add_subplot(gs[0, :])
    ax1 = fig.add_subplot(gs[1, 0])
    ax2 = fig.add_subplot(gs[1, 1])
    ax3 = fig.add_subplot(gs[1, 2])
    histplot(
        samples.goals_pred,
        kde=True,
        discrete=True,
        color="darkgray",
        ec="w",
        ax=ax0,
    )
    ax0.set_ylabel("sim goals")
    ax0.axvline(data.goal.sum(), ls="--", color="r", lw=2, label="obs goals")
    ax0.legend()
    kwargs = {
        "cmap": "bone",
    }
    ax1.set_title("obs shot clusters, density")
    kdeplot(x=data.y, y=data.x, fill=True, ax=ax1, **kwargs)
    scatterplot(
        x=data.y,
        y=data.x,
        hue=data.cluster,
        palette="Dark2",
        ax=ax1,
    )
    ax2.set_title("pred shot probability")
    ax2.tricontourf(sims["y"], sims["x"], sims["shot_prob"], **kwargs)
    scatterplot(x=data.y, y=data.x, ax=ax2)
    ax3.set_title("pred goal probability")
    ax3.tricontourf(sims["y"], sims["x"], sims["goal_prob"], **kwargs)
    ax3.set_yticks([])
    scatterplot(x=data.y, y=data.x, hue=data.goal.astype("int32"), ax=ax3)
    for ax in [ax1, ax2, ax3]:
        ax.set_aspect("equal")
        ax.set_xlim([-45.0, 45.0])
        ax.set_ylim([200.0, 0.0])
        ax.set_xlabel("")
        ax.set_ylabel("")
    tight_layout()
    savefig(FILENAME["results"])
    close()
Пример #13
0
def plot_network(network,
                 blocking=True,
                 netx_plot=False,
                 size=fig_size,
                 weights=None,
                 file_name=None,
                 plot_edges=False,
                 alph=.05):
    fig = figure(figsize=size)
    rcParams.update({
        'font.size': plot_font_size,
        'mathtext.default': 'regular'
    })
    ax = fig.gca()
    ax.axis('off')  # Disable axis

    graph = network if netx_plot else network.network_plot
    plot_layout = kamada_kawai_layout(graph)
    cmap = cm.get_cmap('coolwarm')

    sizes, edge_colors, node_colors = 80, 'k', 'w'
    if weights is not None:
        sizes = [50 if weight == 0 else 80 for weight in weights]
        node_colors = weights

        min_val, max_val = min(weights), max(weights)

    if plot_edges: draw_networkx_edges(graph, plot_layout, alpha=alph)
    draw_networkx_nodes(graph,
                        plot_layout,
                        node_size=sizes,
                        linewidths=.5,
                        edgecolors='k',
                        node_color=node_colors,
                        cmap=cmap)
    draw()

    if weights is not None:
        plt = cm.ScalarMappable(cmap=cmap, norm=Normalize(vmin=0, vmax=1))
        plt._A = []
        colorbar(plt)

    if file_name is not None:
        savefig(file_name, bbox_inches='tight', pad_inches=0)
    show(block=blocking)  # Open matplotlib window
Пример #14
0
    def plot_timestep_convergence(self):
        from matplotlib.pyplot import (
            figure,
            subplot,
            xlabel,
            ylabel,
            plot,
            errorbar,
            title,
            text,
            xticks,
            rcParams,
            savefig,
            xlim,
        )

        params = {
            "legend.fontsize": 14,
            "figure.facecolor": "white",
            "figure.subplot.hspace": 0.0,
            "axes.labelsize": 16,
            "xtick.labelsize": 14,
            "ytick.labelsize": 14,
        }
        rcParams.update(params)

        timesteps = self.timesteps
        energies = convert(self.energies.copy(), "Ha", "eV")
        errors = convert(self.errors.copy(), "Ha", "eV")
        Esmall = energies[0]

        figure()
        tsrange = [0, 1.1 * timesteps[-1]]
        plot(tsrange, [0, 0], "k-")
        errorbar(timesteps, energies - Esmall, errors, fmt="k.")
        text(array(tsrange).mean(), 0, "{0:6.4f} eV".format(Esmall))
        xticks(timesteps)
        xlim(tsrange)
        xlabel("Timestep (Ha)")
        ylabel("Total Energy (eV)")
        title("DMC Timestep Convergence")

        savefig("TimestepConvergence.png", format="png", bbox_inches="tight", pad_inches=1)
Пример #15
0
 def plot(self,i, praefix=''):
     # plot i-th component
     h = self.h
     t = self.tout
     x = self.xout[:,i]
     #ordnet den jeweiligen Stellen im Vektor die richtige Bezeichnung zu, die vom Plot aufgerufen werden kann
     label = ['Anzahl der Gesunden', 'Anzahl der Kranken', 'Anzahl der Resistenten']
     p0 = plot(t, x, linewidth = 2, label = label[i])
     #das Folgende ist auskommentiert, da wir keine exakte Lösung haben
     #try:
         #self.exactsol()
         #p1=plot(t,self.xexact, 'r',label='exakte Loesung')
     #except:
         #print("no exact solution given")
     title(self.example+' mit '+self.method+', h='+str(h)+', beta = '+str(self.beta)+', gamma = '+str(self.gamma))
     rcParams.update({'font.size': 12})
     legend(loc='center right', shadow=True)
     xlabel('t')
     ylabel('x(t)')
     #speichert die Plotts, sobald alle 3 Graphen enthalten sind
     if i == 2:
         savefig('sol_'+str(praefix)+'_'+self.example+'_'+self.method+'_s'+str(self.snum)+'_i'+str(i)+str(self.beta)+str(self.gamma)+'.png')
Пример #16
0
    def plot_bandstructure(self,
                           filename=None,
                           filepath=None,
                           max_min_e=None,
                           show=False,
                           save=True,
                           show_vbm_cbm=True):
        if 'bands' in self:
            from structure import get_kpath
            if filename == None:
                filename = 'band_structure.pdf'
            if filepath == None:
                filepath = os.path.join(self.abspath, filename)
            else:
                filepath = os.path.join(filepath, filename)
            #end if
            try:
                import matplotlib
                gui_envs = ['GTKAgg', 'TKAgg', 'agg', 'Qt4Agg', 'WXAgg']
                for gui in gui_envs:
                    try:
                        matplotlib.use(gui, warn=False, force=True)
                        from matplotlib import pyplot
                        success = True
                        break
                    except:
                        continue
                    #end try
                #end for
                from matplotlib.pyplot import figure, plot, xlabel, ylabel, title, show, ylim, legend, xlim, rcParams, rc, savefig, gca, xticks, axvline, scatter
                params = {
                    'legend.fontsize': 14,
                    'figure.facecolor': 'white',
                    'figure.subplot.hspace': 0.,
                    'axes.labelsize': 16,
                    'xtick.labelsize': 14,
                    'ytick.labelsize': 14
                }
                rcParams.update(params)
            except (ImportError, RuntimeError):
                success = False
            if not success:
                figure, plot, xlabel, ylabel, title, show, ylim, legend, xlim, rcParams, savefig, bar, xticks, subplot, grid, setp, errorbar, loglog, semilogx, semilogy, text = unavailable(
                    'matplotlib.pyplot', 'figure', 'plot', 'xlabel', 'ylabel',
                    'title', 'show', 'ylim', 'legend', 'xlim', 'rcParams',
                    'savefig', 'bar', 'xticks', 'subplot', 'grid', 'setp',
                    'errorbar', 'loglog', 'semilogx', 'semilogy', 'text')
            #end if
            fig = figure()
            ax = gca()
            kpath = get_kpath(structure=self.input_structure,
                              check_standard=False)
            x = kpath['explicit_path_linearcoords']
            labels = kpath['explicit_kpoints_labels']
            nbands = self.input.system.nbnd
            for nb in range(nbands):
                y = []
                for bi in self.bands.up:
                    y.append(bi['eigs'][nb])
                #end for
                y = array(y) - self.bands.vbm.energy
                plot(x, y, 'k')
                if len(self.bands.down) > 0:
                    y = []
                    for bi in self.bands.down:
                        y.append(bi['eigs'][nb])
                    #end for
                    y = array(y) - self.bands.vbm.energy
                    plot(x, y, 'r')
                #end if
            #end for
            for ln, li in enumerate(labels):
                if li is not '':
                    axvline(x[ln], ymin=-100, ymax=100, linewidth=3, color='k')
                    if li == 'GAMMA':
                        labels[ln] = r'$\Gamma$'
                    elif li is not '':
                        labels[ln] = '${0}$'.format(li)
                    #end if
                    if labels[ln - 1] is not '' and ln > 0:
                        labels[ln] = labels[ln - 1] + '|' + labels[ln]
                        labels[ln - 1] = ''
                    #end if
                #end if
            #end for

            xlim([min(x), max(x)])
            if max_min_e is None:
                ylim(-5, +5)
            else:
                ylim(max_min_e[0], max_min_e[1])
            #end if
            ylabel('Energy (eV)')
            xticks(x, labels)
            ax.tick_params(axis='x', which='both', length=0)
            ax.tick_params(axis='x', which='both', pad=10)
        #end if
        if show_vbm_cbm:
            vbm = self.bands.vbm
            cbm = self.bands.cbm
            for kn, ki in enumerate(self.bands.up):
                if (vbm.kpoint_rel == ki['kpoint_rel']).all():
                    scatter(x[kn], 0, c='green', s=100)
                #end if
                if (cbm.kpoint_rel == ki['kpoint_rel']).all():
                    scatter(x[kn], cbm.energy - vbm.energy, c='r', s=100)
                #end if
            #end for
        #end if
        if save:
            savefig(filename, format='pdf', bbox_inches='tight')
        #end if
        if show:
            show()
Пример #17
0
    def make_skewt_axes(self,pmax=1050.,pmin=100.,tmin=-40.,tmax=30.):
        """Set up the skew-t axis the way I like to see it"""
        
        self.fig = figure(figsize=(8,8))
        self.fig.clf()

        
        rcParams.update({\
            'font.size':10,\
            })

        self.skewxaxis=self.fig.add_axes([.065,.1,.71,.8], projection='skewx')
        self.skewxaxis.set_yscale('log')
        self.skewxaxis.pmax=pmax
        self.skewxaxis.pmin=pmin
        self.skewxaxis.tmax=tmax
        self.skewxaxis.tmin=tmin

        xticklocs=arange(-80,45,10)
        T0 = xticklocs

        # P=linspace(pmax,pmin,101)
        P=logspace(log10(pmax),log10(pmin),101)

        w = array([0.00001,0.0001,0.0004,0.001, 0.002, 0.004, 0.007, 0.01, 0.016, 0.024, 0.032])
        self.skewxaxis.add_mixratio_isopleths(w,P[P>=700],color='g',ls='--',alpha=1.,lw=0.5)
        self.skewxaxis.add_dry_adiabats(linspace(210,550,18)-degCtoK,P,color='g',ls='--',alpha=1.,lw=0.5)
        self.skewxaxis.add_moist_adiabats(linspace(0,44,12),pmax,color='g',ls='--',alpha=1.,lw=0.5)
	#self.skewxaxis.add_moist_adiabats(linspace(0,38,12),pmax,color='g',ls='--',alpha=1.,lw=0.5)
        self.skewxaxis.set_title("%s %s"%(self['StationNumber'],self['SoundingDate']))

        self.skewxaxis.other_housekeeping()

        self.wbax=self.fig.add_axes([0.685,0.1,0.1,0.8],sharey=self.skewxaxis,frameon=False)
        self.wbax.xaxis.set_ticks([],[])
        self.wbax.yaxis.grid(True,ls='-',color='y',lw=0.5)
        for tick in self.wbax.yaxis.get_major_ticks():
            # tick.label1On = False
            pass
        self.wbax.get_yaxis().set_tick_params(size=0,color='y')
        self.wbax.set_xlim(-1.5,1.5)
        self.wbax.get_yaxis().set_visible(False)
        self.wbax.set_title('kn',fontsize=10,color='k',ha='right')

        # Set up standard atmosphere height scale on 
        # LHS of plot. 
        majorLocatorKM   = MultipleLocator(2)
        majorLocatorKFT  = MultipleLocator(5)
        minorLocator     = MultipleLocator(1)

        # determine base height from base pressure (nominally 1050 hPa)
        # via hydrostatic equilibrium for standard atmosphere

        # model atmospheric conditions with constant lapse rate and
        # NIST (1013.25hPa and 20C)
        zmin=barometric_equation_inv(0,293.15,101325.,pmax*100.)
        zmax=barometric_equation_inv(0,293.15,101325.,pmin*100.)
        zminf=zmin*3.2808
        zmaxf=zmax*3.2808

        self.kmhax=self.fig.add_axes([0.775,0.1,1e-6,0.8],frameon=True)
        self.kmhax.xaxis.set_ticks([],[])
        self.kmhax.spines['left'].set_color('k')
        self.kmhax.spines['right'].set_visible(False)
        self.kmhax.tick_params(axis='y', colors='k',labelsize=8)
        self.kmhax.set_ylim(zmin*1e-3,zmax*1e-3)
        self.kmhax.set_title("km/kft",fontsize=10)
        self.kmhax.get_yaxis().set_tick_params(which="both",direction='out')
        self.kmhax.yaxis.set_major_locator(majorLocatorKM)
        self.kmhax.yaxis.set_minor_locator(minorLocator)

        self.fthax=self.kmhax.twinx()
        self.fthax.xaxis.set_ticks([],[])
        self.fthax.tick_params(axis='y', colors='k',labelsize=8)
        self.fthax.set_ylim(zminf*1e-3,zmaxf*1e-3)
        self.fthax.get_yaxis().set_tick_params(which="both",direction='out')
        self.fthax.yaxis.set_major_locator(majorLocatorKFT)
        self.fthax.yaxis.set_minor_locator(minorLocator)
Пример #18
0
from periodic_table import pt
from unit_converter import convert
from generic import obj
from developer import DevBase, unavailable
try:
    from matplotlib.pyplot import figure, plot, xlabel, ylabel, title, show, ylim, legend, xlim, rcParams, savefig, bar, xticks, subplot, grid, setp, errorbar, loglog, semilogx, semilogy

    params = {
        'legend.fontsize': 14,
        'figure.facecolor': 'white',
        'figure.subplot.hspace': 0.,
        'axes.labelsize': 16,
        'xtick.labelsize': 14,
        'ytick.labelsize': 14
    }
    rcParams.update(params)
except (ImportError, RuntimeError):
    figure, plot, xlabel, ylabel, title, show, ylim, legend, xlim, rcParams, savefig, bar, xticks, subplot, grid, setp, errorbar, loglog, semilogx, semilogy = unavailable(
        'matplotlib.pyplot', 'figure', 'plot', 'xlabel', 'ylabel', 'title',
        'show', 'ylim', 'legend', 'xlim', 'rcParams', 'savefig', 'bar',
        'xticks', 'subplot', 'grid', 'setp', 'errorbar', 'loglog', 'semilogx',
        'semilogy')
#end try


class Pseudopotential(DevBase):
    colors = dict(s='k', p='r', d='b', f='m')
    lcolors = ['k', 'r', 'b', 'm']
    ldict = {0: 's', 1: 'p', 2: 'd', 3: 'f'}

    format = 'generic'
Пример #19
0
    def make_skewt_axes(self, pmax=1100., pmin=50.):

        self.fig = figure(figsize=(9, 8))
        self.fig.clf()

        rcParams.update({\
        'font.size':10,})

        P = linspace(pmax, pmin, 37)
        pres_levels = np.arange(1000, 0, -100)

        self.skewxaxis = self.fig.add_axes([.085, .1, .73, .8],
                                           projection='skewx')
        self.skewxaxis.set_yscale('log')

        xticklocs = arange(-80, 45, 10)
        T0 = xticklocs

        w = array([
            0.0001, 0.0004, 0.001, 0.002, 0.004, 0.007, 0.01, 0.016, 0.024,
            0.032
        ])
        self.skewxaxis.add_mixratio_isopleths(w,
                                              P[P >= 550],
                                              color='purple',
                                              ls='--',
                                              alpha=1.,
                                              lw=0.5)
        self.skewxaxis.add_dry_adiabats(linspace(250, 440, 20) - 273.15,
                                        P,
                                        color='red',
                                        ls='--',
                                        alpha=1.,
                                        lw=0.5)
        self.skewxaxis.add_moist_adiabats(linspace(8, 32, 7),
                                          P[P >= 200],
                                          color='g',
                                          ls='--',
                                          alpha=1.,
                                          lw=0.5)
        self.skewxaxis.other_housekeeping()

        self.wbax = self.fig.add_axes([0.75, 0.1, 0.1, 0.8],
                                      sharey=self.skewxaxis,
                                      frameon=False)  # wind barb axis
        self.wbax.xaxis.set_ticks([], [])
        self.wbax.yaxis.grid(True, ls='-', color='y', lw=0.5)
        for tick in self.wbax.yaxis.get_major_ticks():
            # tick.label1On = False
            pass
        self.wbax.get_yaxis().set_tick_params(size=0, color='y')
        self.wbax.set_xlim(-1.5, 1.5)
        self.wbax.get_yaxis().set_visible(False)

        # Set up standard atmosphere height scale on
        # LHS of plot. It's jus
        majorLocatorKM = MultipleLocator(2)
        majorLocatorKFT = MultipleLocator(5)
        minorLocator = MultipleLocator(1)

        self.htax = self.fig.add_axes([0.1, 0.1, 1e-6, 0.8],
                                      sharey=self.skewxaxis,
                                      frameon=False)
        self.htax.xaxis.set_ticks([], [])
        self.htax.spines['left'].set_color('k')
        self.htax.spines['right'].set_visible(False)
        self.htax.get_yaxis().set_tick_params(size=0, color='y')
        self.htax.get_yaxis().set_visible(False)
        pres_heights = np.array([
            self.data['hght'][np.argmin(np.abs(_ - self.data['pres']))]
            for _ in pres_levels
        ])
        for ph in range(pres_levels.shape[0]):
            self.htax.text(0,
                           pres_levels[ph],
                           '%d m' % pres_heights[ph],
                           fontsize=8)
        #print pres_heights

        self.fig.text(0.83, 0.9, 'Sounding Params')
        #$\underline{Sounding Params}$')
        #h0 = interp(0, self.data['temp'], self.data['hght'])
        h0 = self.data['hght'][np.argmin(abs(self.data['temp'] - 0))]
        h20 = self.data['hght'][np.argmin(abs(self.data['temp'] + 20))]
        h40 = self.data['hght'][np.argmin(abs(self.data['temp'] + 40))]
        lcl_height = 216 * (self.data['temp'][0] - self.data['dwpt'][0])
        mr = MixRatio(SatVap(self.data['dwpt']), self.data['pres'] * 100)
        pdiff = -1.0 * np.diff(self.data['pres'])
        #print mr.shape, pdiff.shape
        # precipitable water
        pw = np.sum(
            np.array([
                mr[_] * 100.0 * pdiff[_] / 9.8 for _ in range(pdiff.shape[0])
            ]))
        # crude estimate of wet bulb temp
        tw = self.data['temp'][0] - (self.data['temp'][0] -
                                     self.data['dwpt'][0]) / 3.
        # now some shear calculations
        wspd6km = self.data['sknt'][np.argmin(abs(self.data['hght'] - 6000))]
        wdir6km = self.data['drct'][np.argmin(abs(self.data['hght'] - 6000))]

        udiff = wspd6km * np.cos(
            np.radians(270 - wdir6km)) - self.data['sknt'][3] * np.cos(
                np.radians(270 - self.data['drct'][3]))
        vdiff = wspd6km * np.sin(
            np.radians(270 - wdir6km)) - self.data['sknt'][3] * np.sin(
                np.radians(270 - self.data['drct'][3]))
        #print udiff, vdiff
        shear6km = np.sqrt(udiff**2 + vdiff**2)

        #trop_index = tropopause_index(self.data['temp'])
        #if trop_index == -999: tropopause_pressure = -999.
        #else: tropopause_pressure = self.data['pres'][trop_index]
        # New way to do tropopause pressure

        # first calculate the parameters that go in
        smooth_temp = running_mean(self.data['temp'], 3, ntimes=30)

        dp = np.gradient(self.data['pres'])

        #lapse = 1000.0*np.diff(smooth)/np.diff(S.data['hght'])

        deriv = np.gradient(smooth_temp, dp)
        deriv_smooth = running_mean(deriv, 3, ntimes=30)

        theta = running_mean(Theta(273.15 + self.data['temp'],
                                   self.data['pres'] * 100.0),
                             3,
                             ntimes=50)

        dtheta = -1.0 * running_mean(np.gradient(theta, dp), 3, ntimes=10)

        rh = running_mean(RH(self.data['temp'], self.data['dwpt']),
                          3,
                          ntimes=30)
        drh = -1.0 * np.gradient(rh, dp)
        weights = {
            'theta': 1.0,
            'dtdp': 1.0,
            'T': 1.0,
            'dthetadp': 1.0,
            'drhdp': 0.6,
            'pres': 1.0
        }
        input_data = {
            'theta': theta,
            'dtdp': deriv_smooth,
            'T': smooth_temp,
            'dthetadp': dtheta,
            'drhdp': drh,
            'pres': self.data['pres']
        }
        tropopause_pressure = fuzzy_tropopause(input_data, weights)

        self.fig.text(0.83, 0.88, '0%s: %d m' % (degC, h0))
        self.fig.text(0.83, 0.86, '-20%s: %d m' % (degC, h20))
        self.fig.text(0.83, 0.84, '-40%s: %d m' % (degC, h40))
        self.fig.text(0.83, 0.82, 'LCL: %d m' % lcl_height)
        self.fig.text(0.83, 0.80, 'PW: %.1f mm' % pw)
        self.fig.text(0.83, 0.78, '6 km shear: %d kts' % shear6km)
        self.fig.text(0.83, 0.76, 'Trop: %d hPa' % (tropopause_pressure))

        self.fig.text(0.83, 0.70, 'Surface')
        self.fig.text(0.83, 0.68, 'P: %.1f hPa' % self.data['pres'][0])
        self.fig.text(0.83, 0.66, 'Ht: %d m' % (self.data['hght'][0]))

        self.fig.text(0.83, 0.64, 'T: %.1f %s' % (self.data['temp'][0], degC))
        self.fig.text(0.83, 0.62,
                      'T$_D$: %.1f %s' % (self.data['dwpt'][0], degC))
        self.fig.text(0.83, 0.60, 'T$_W$: %.1f %s' % (tw, degC))

        # now do the hodograph?
        self.hodoax = self.fig.add_axes([0.08, 0.69, 0.20, 0.20],
                                        frameon=True,
                                        polar=True)
        self.hodoax.xaxis.set_ticks([], [])
        self.hodoax.yaxis.set_ticks([], [])
        speed_mask = np.ma.masked_where(self.data['sknt'] > 999,
                                        self.data['sknt'])
        angle = 270 - self.data['drct']
        rad_angle = np.radians(angle)
        pres_mask = np.bitwise_and(
            self.data['pres'] > 200.,
            self.data['drct'] < 361.)  # only look at valid winds below 200 mb

        if self.fmt == 'EDT' or self.fmt == 'EC':
            self.hodoax.scatter(rad_angle[pres_mask], self.data['sknt'][pres_mask], c = self.data['hght'][pres_mask], \
            edgecolors = 'none', s = 5, cmap = plt.cm.jet_r)
        elif self.fmt == 'UWYO':
            self.hodoax.plot(rad_angle,
                             self.data['sknt'],
                             c='red',
                             linewidth=3)

        #self.hodoax.plot(rad_angle, speed_mask, c = 'red', linewidth = 3)
        #self.hodoax.set_rmax(100)

        self.hodoax.set_yticks(np.arange(0, 150, 30))
        self.hodoax.tick_params(labelsize=5)
        self.hodoax.set_xticks(np.arange(0, 2 * np.pi, np.pi / 2))
        self.hodoax.set_xticklabels([])
        self.hodoax.grid(True)
        try:
            self.hodoax.set_rlabel_position(180)
        except AttributeError:
            pass
Пример #20
0
    df_tot['Sample_ID'] = files
    df_tot.set_index('Sample_ID', inplace=True)
    df_tot = df_tot[dfs[longest].columns]
    df_tot.to_csv(save_path + "Merged_%s-%s_%s_TO_%s.csv" %
                  (sol.model, sol.model_type_str, files[0], files[-1]))
    print("Batch file successfully saved in:\n", save_path)


def print_diagn(M, q, r, s):
    return raftery_lewis(M, q, r, s, verbose=0)


def plot_par():
    rc = {
        u'figure.dpi': 72.0,
        u'figure.edgecolor': 'white',
        u'figure.facecolor': 'white',
        u'savefig.bbox': u'tight',
        u'savefig.directory': u'~',
        u'savefig.dpi': 200.0,
        u'savefig.edgecolor': u'white',
        u'savefig.facecolor': u'white',
        u'axes.formatter.use_mathtext': True,
        u'xtick.direction': 'in',
        u'ytick.direction': 'in',
    }
    return rc


rcParams.update(plot_par())
Пример #21
0
# %autoreload 2
#%reload_ext autoreload

import numpy
import matplotlib
from matplotlib import pylab, mlab, pyplot
np = numpy
plt = pyplot

from IPython.display import display
from IPython.core.pylabtools import figsize, getfigs

from pylab import *
from numpy import *
from matplotlib.pyplot import rcParams
rcParams.update({"font.size": 15})

#%%%% cd working directory
import os
os.chdir("/Users/cham/projects/sb2")
print(os.getcwd())

#%%%% code
"""
https://phoenix.astro.physik.uni-goettingen.de/
"""

from astropy.io import fits
flux_hi = fits.getdata(
    "/Users/cham/Documents/slides/stellar_parameters/demo_ccf/lte05800-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits"
)
Пример #22
0
def plot_scatter_data(data,
                      multiple=False,
                      file_name=None,
                      leg=None,
                      blocking=True,
                      x_label=None,
                      y_label=None,
                      x_log=False,
                      size=None,
                      font_size=None,
                      connect=False,
                      y_format=False,
                      dot_size=80,
                      leg_loc=None,
                      y_bnd=None):
    size = data_fig_size if size is None else size
    font_size = plot_font_size if font_size is None else font_size
    fig = figure(figsize=size)
    rcParams.update({'font.size': font_size, 'mathtext.default': 'regular'})
    ax = fig.gca()

    min_x, max_x, min_y, max_y = 1, 0, 1, 0

    if multiple:
        for run in data:
            tmp_min_x, tmp_max_x = min(run[0, :]), max(run[0, :])
            tmp_min_y, tmp_max_y = min(run[1, :]), max(run[1, :])
            min_x = tmp_min_x if min_x > tmp_min_x else min_x
            max_x = tmp_max_x if max_x < tmp_max_x else max_x
            min_y = tmp_min_y if min_y > tmp_min_y else min_y
            max_y = tmp_max_y if max_y < tmp_max_y else max_y

            ax.scatter(run[0, :], run[1, :], s=dot_size)
            if connect: ax.plot(run[0, :], run[1, :])
    else:
        ax.scatter(data[0, :], data[1, :], s=dot_size)
        if connect: ax.plot(data[0, :], data[1, :])
        min_x, max_x = min(data[0, :]), max(data[0, :])
        min_y, max_y = min(data[1, :]), max(data[1, :])

    ax.set_xlim(min_x, max_x)
    y_delta = (max_y - min_y) * .05
    if y_bnd is None:
        ax.set_ylim(min_y - y_delta, max_y + y_delta)
    else:
        ax.set_ylim(y_bnd[0], y_bnd[1])

    if y_format: ticklabel_format(style='sci', axis='y', scilimits=(-5, 1))
    if x_label is not None: ax.set_xlabel(x_label)
    if y_label is not None: ax.set_ylabel(y_label)

    if x_log: ax.set_xscale('log')
    if leg is not None and leg_loc is None: legend(leg)
    elif leg_loc is not None:
        legend(leg, bbox_to_anchor=leg_loc, loc='upper left')

    if file_name is not None:
        try:
            savefig(file_name, bbox_inches='tight', pad_inches=0)
        except FileExistsError:
            pass

    if blocking: show()
Пример #23
0
@author: naus010

The file in which I can combine experiments, saved from OH_GTB.
I should run OH_GTB_read_data_helper, then OH_GBT, then this file

vPP: This is the setup that produces powerpoint images. Mostly larger text.
"""

import os
import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import rcParams

rcParams.update({'font.size': 16})
rcParams.update({'lines.markersize': 9})
rcParams.update({'lines.linewidth': 1.5})

def read_full(exp_name, dataset):
    '''Reads the 'full' array (opt C and E and OH)'''
    filename = exp_name +'_'+ dataset + '_full'
    filepointer = os.path.join('Data output','arrays',filename)
    full_array = np.loadtxt(filepointer)
    return unpack_full(full_array)
    
def read_x(exp_name, dataset):
    '''Reads the xopt array'''
    filename = exp_name +'_'+ dataset + '_xopt'
    filepointer = os.path.join('Data output','arrays',filename)
    xopt = np.loadtxt(filepointer)
Пример #24
0
    dfs = [pd.read_csv(working_path+"/Results/%s/INV_%s-%s_%s.csv" %(f,sol.model,sol.model_type_str,f)) for f in files]
    listed_dfs = [list(d) for d in dfs]
    df_tot = pd.concat(dfs, axis=0)
    longest = max(enumerate(listed_dfs), key = lambda tup: len(tup[1]))[0]
    df_tot['Sample_ID'] = files
    df_tot.set_index('Sample_ID', inplace=True)
    df_tot = df_tot[dfs[longest].columns]
    df_tot.to_csv(save_path+"Merged_%s-%s_%s_TO_%s.csv" %(sol.model,sol.model_type_str,files[0],files[-1]))
    print("Batch file successfully saved in:\n", save_path)


def print_diagn(M, q, r, s):
    return raftery_lewis(M, q, r, s, verbose=0)

def plot_par():
    rc = {
          u'figure.edgecolor': 'white',
          u'figure.facecolor': 'white',
          u'savefig.bbox': u'tight',
          u'savefig.directory': u'~',
          
          u'savefig.edgecolor': u'white',
          u'savefig.facecolor': u'white',
          u'axes.formatter.use_mathtext': True,
          u'xtick.direction'  : 'in',
          u'ytick.direction'  : 'in',
          
          }
    return rc
rcParams.update(plot_par())
    def make_skewt_axes(self, pmax=1050., pmin=100., tmin=-40., tmax=30.,
                        fig=None):
        """Set up the skew-t axis the way I like to see it"""

        if fig is None:
            self.fig = figure(figsize=(8, 8))
            # self.fig.clf()
        else:
            self.fig = fig

        rcParams.update({'font.size': 10, })

        self.skewxaxis = self.fig.add_axes([.065, .1, .71, .8],
                                           projection='skewx')
        self.skewxaxis.set_yscale('log')
        self.skewxaxis.pmax = pmax
        self.skewxaxis.pmin = pmin
        self.skewxaxis.tmax = tmax
        self.skewxaxis.tmin = tmin

        xticklocs = arange(-80, 45, 10)
        T0 = xticklocs

        # P=linspace(pmax,pmin,101)
        P = logspace(log10(pmax), log10(pmin), 101)

        w = array([0.00001, 0.0001, 0.0004, 0.001, 0.002, 0.004,
                   0.007, 0.01, 0.016, 0.024, 0.032])
        self.skewxaxis.add_mixratio_isopleths(
            w, P[P >= 700], color='g', ls='--', alpha=1., lw=0.5)
        self.skewxaxis.add_dry_adiabats(
            linspace(210, 550, 18)-degCtoK, P, color='g', ls='--', alpha=1.,
            lw=0.5)
        self.skewxaxis.add_moist_adiabats(
            linspace(0, 44, 12), pmax, color='g', ls='--', alpha=1., lw=0.5)

        self.skewxaxis.set_title("%s %s" % (self['StationNumber'],
                                            self['SoundingDate']))

        self.skewxaxis.other_housekeeping()

        self.wbax = self.fig.add_axes([0.685, 0.1, 0.1, 0.8],
                                      sharey=self.skewxaxis, frameon=False)
        self.wbax.xaxis.set_ticks([], [])
        self.wbax.yaxis.grid(True, ls='-', color='y', lw=0.5)
        for tick in self.wbax.yaxis.get_major_ticks():
            # tick.label1On = False
            pass
        self.wbax.get_yaxis().set_tick_params(size=0, color='y')
        self.wbax.set_xlim(-1.5, 1.5)
        self.wbax.get_yaxis().set_visible(False)
        self.wbax.set_title('kn', fontsize=10, color='k', ha='right')

        # Set up standard atmosphere height scale on
        # LHS of plot.
        majorLocatorKM = MultipleLocator(2)
        majorLocatorKFT = MultipleLocator(5)
        minorLocator = MultipleLocator(1)

        # determine base height from base pressure (nominally 1050 hPa)
        # via hydrostatic equilibrium for standard atmosphere

        # model atmospheric conditions with constant lapse rate and
        # NIST (1013.25hPa and 20C)
        zmin = barometric_equation_inv(0, 293.15, 101325., pmax*100.)
        zmax = barometric_equation_inv(0, 293.15, 101325., pmin*100.)
        zminf = zmin * 3.2808
        zmaxf = zmax * 3.2808

        self.kmhax = self.fig.add_axes([0.775, 0.1, 1e-6, 0.8], frameon=True)
        self.kmhax.xaxis.set_ticks([], [])
        self.kmhax.spines['left'].set_color('k')
        self.kmhax.spines['right'].set_visible(False)
        self.kmhax.tick_params(axis='y', colors='k', labelsize=8)
        self.kmhax.set_ylim(zmin*1e-3, zmax*1e-3)
        self.kmhax.set_title("km/kft", fontsize=10)
        self.kmhax.get_yaxis().set_tick_params(which="both", direction='out')
        self.kmhax.yaxis.set_major_locator(majorLocatorKM)
        self.kmhax.yaxis.set_minor_locator(minorLocator)

        self.fthax = self.kmhax.twinx()
        self.fthax.xaxis.set_ticks([], [])
        self.fthax.tick_params(axis='y', colors='k', labelsize=8)
        self.fthax.set_ylim(zminf*1e-3, zmaxf*1e-3)
        self.fthax.get_yaxis().set_tick_params(which="both", direction='out')
        self.fthax.yaxis.set_major_locator(majorLocatorKFT)
        self.fthax.yaxis.set_minor_locator(minorLocator)
Пример #26
0
def show_plot(Tair, Tfree, at, Q, days, fileName):

    fig = figure(fileName)

    energy = fig.add_subplot(211, axisbg='black')
    temperature = fig.add_subplot(212, axisbg='black')
    energy.set_axisbelow(True)
    temperature.set_axisbelow(True)

    #minor grids
    energy.xaxis.grid(True, 'minor', color='w', linestyle='-', linewidth=.2)
    energy.yaxis.grid(True, 'minor', color='w', linestyle='-', linewidth=.2)
    #ticks
    energy.xaxis.set_ticks(np.arange(0, 24 * noOfDays + 1, 24))
    energy.minorticks_on()
    energy.set_xticklabels(days)
    #major grids
    energy.xaxis.grid(True, 'major', linewidth=.5, linestyle='-', color='w')
    energy.yaxis.grid(True, 'major', linewidth=.5, linestyle='-', color='w')
    #labels
    energy.set_ylabel("Required Power (W)")

    #minor grids
    temperature.xaxis.grid(True,
                           'minor',
                           color='w',
                           linestyle='-',
                           linewidth=.2)
    temperature.yaxis.grid(True,
                           'minor',
                           color='w',
                           linestyle='-',
                           linewidth=.2)
    #ticks
    temperature.xaxis.set_ticks(np.arange(0, 24 * noOfDays + 1, 24))
    temperature.minorticks_on()
    temperature.set_xticklabels(days)
    #major grids
    temperature.xaxis.grid(True,
                           'major',
                           linewidth=.5,
                           linestyle='-',
                           color='w')
    temperature.yaxis.grid(True,
                           'major',
                           linewidth=.5,
                           linestyle='-',
                           color='w')
    #labels
    temperature.set_ylabel("Temperature ($^{o}C$)")
    temperature.set_xlabel("day")

    #for mathematical fonts
    params = {'mathtext.default': 'regular'}
    rcParams.update(params)
    energy.plot(hour, Q, linewidth='1.5', label='Energy requirements')

    temperature.plot(hour, Tair - 273.15, linewidth='1.5', label='$T_{wAC}$')
    temperature.plot(hour,
                     Tfree - 273.15,
                     linewidth='1.5',
                     label='$T_{free}$',
                     linestyle='--')
    temperature.plot(hour, at - 273.15, linewidth='1.5', label='$T_{outside}$')
    temperature.legend(bbox_to_anchor=(1, 1),
                       loc=2,
                       borderaxespad=0.,
                       fontsize='medium',
                       fancybox=True,
                       shadow=True)
    show()
Пример #27
0
    # snarfed from https://stackoverflow.com/questions/22263807/how-is-order-of-items-in-matplotlib-legend-determined
    handles, labels = ax.get_legend_handles_labels()
    labels, handles = zip(*sorted(zip(labels, handles), key=lambda t: t[0]))
    ax.legend(handles, labels)


def plot_Likelihoods(Likelihoods, ax=None):
    ax.set_title('Progress')
    ax.plot(Likelihoods)
    ax.set_xticks(range(1, len(Likelihoods)))
    ax.set_ylabel('log Likelihood')
    ax.set_xlabel('Iteration')


if __name__ == '__main__':
    rcParams.update({"text.usetex": True})

    parser = ArgumentParser('CAVI for single Gaussian')
    parser.add_argument('--N', type=int, default=5000, help='Dataset size')
    parser.add_argument('--mean',
                        type=float,
                        default=0.5,
                        help='Mean for dataset')
    parser.add_argument('--sigma',
                        type=float,
                        default=0.5,
                        help='Standard deviation')
    parser.add_argument('--seed',
                        type=int,
                        default=None,
                        help='Seed for random number generator')
Пример #28
0
from numpy import linspace, array, log
from matplotlib.pyplot import figure, show, rcParams, savefig
from utilities import fig_size

x = linspace(0, 1, 101)
y = array([
    -a * log(a) + -(1 - a) * log(1 - a) if a != 0 and a != 1 else 0 for a in x
])

fig = figure(figsize=fig_size)
rcParams.update({'font.size': 16, 'mathtext.default': 'regular'})
ax = fig.gca()

ax.plot(x, y, linewidth=3)
ax.set_xlim(0, 1)
ax.set_ylim(0, .8)
ax.set_xlabel('$\\bar{B}_i$')
ax.set_ylabel('$I_0$ = $\\frac{ \\bar{R}_i }{ \\bar{R}_i + \\bar{B}_i }$')

path = '../../results/binary_entropy.png'
savefig(path)
show()
Пример #29
0
# csv files with data need to be in:
# workdir/data/id.csv
# where id is the identifiacion of the metro zone to be analyzed.
# The first column is daily deaths and the second daily confirmed cases
# The rest of the information is contained in a doctionary:

# General information for the metro zone or region to be analyzed:
# The actual instance of the covid_mcmc object is store in the last item of the list, once it has been instantiated by AnalyzeZM
#     id          Name   num_relax_days  Population   init date           intervention and relax dates
ZMs = $Zone
# The (optional) hospital occupancy data are stored in:
#  workdir/data/hosp/


rcParams.update({'font.size': 14})



if __name__=='__main__':

    q = $plottingQuantiles  # [10, 25, 50, 75, 90]

    workdir = "$workdir"
    os.makedirs(workdir, exist_ok=True)
    os.makedirs(workdir+"output", exist_ok=True)
    os.makedirs(workdir+"figs", exist_ok=True)
    os.makedirs(workdir+"data", exist_ok=True)
    #os.makedirs(workdir+"data/hospitales_datos", exist_ok=True)
    os.makedirs(workdir+"csv", exist_ok=True)
    #os.makedirs(workdir+"logs", exist_ok=True)
Пример #30
0
import os
from subprocess import Popen
from numpy import linspace,array,zeros,append,mgrid,empty,exp
from xmlreader import readxml
from superstring import string2val,split_delims
from periodic_table import pt
from unit_converter import convert
from generic import obj
from developer import DevBase,unavailable
try:
    from matplotlib.pyplot import figure,plot,xlabel,ylabel,title,show,ylim,legend,xlim,rcParams,savefig,bar,xticks,subplot,grid,setp,errorbar,loglog,semilogx,semilogy

    params = {'legend.fontsize':14,'figure.facecolor':'white','figure.subplot.hspace':0.,
          'axes.labelsize':16,'xtick.labelsize':14,'ytick.labelsize':14}
    rcParams.update(params)
except (ImportError,RuntimeError):
   figure,plot,xlabel,ylabel,title,show,ylim,legend,xlim,rcParams,savefig,bar,xticks,subplot,grid,setp,errorbar,loglog,semilogx,semilogy = unavailable('matplotlib.pyplot','figure','plot','xlabel','ylabel','title','show','ylim','legend','xlim','rcParams','savefig','bar','xticks','subplot','grid','setp','errorbar','loglog','semilogx','semilogy')
#end try



class Pseudopotential(DevBase):
    colors = dict(s='k',p='r',d='b',f='m')
    lcolors= ['k','r','b','m']
    ldict = {0:'s',1:'p',2:'d',3:'f'}

    format = 'generic'

    conv_table = {('upf','fsatom'):('--upf_pot','--xml')}
    extensions = dict(upf='upf',fsatom='xml',gamess='gamess',casino='data')
Пример #31
0
def thermalLoad(fileName):
    global alpha, N, air_temp, dew_point, epsi, cloudCover, relHum, noOfDays, N, hour
    global sol_airn, sol_aire, sol_airs, sol_airw
    for sett in session.query(Settings).filter(Settings.name == fileName):

        length = sett.length
        width = sett.width
        height = sett.height

        #material properties
        thickness = sett.thickness
        h_c = sett.conv_coeff
        rho = sett.density
        c = sett.spec_heat
        k = sett.therm_cond

        Ti = sett.initTemp
        Tcomf = sett.comfTemp

        alpha = sett.swAbs
        epsi = sett.lwEWall
        sigma = 5.67 * (10)**(-8)
        power = sett.altitude
        noOfDays = int(sett.numDays)
    N = noOfDays * 500
    hour = np.linspace(0, noOfDays * 24, N)
    sol_airn = np.empty(N)
    sol_aire = np.empty(N)
    sol_airs = np.empty(N)
    sol_airw = np.empty(N)

    air_temp, dew_point, relHum, cloudCover, days = fit(fileName)
    R = thickness / k
    Cc = rho * c * thickness / 2
    #call function of air and vapor pressure

    excel = "Data/Radiation/ShortwaveRadiation-" + fileName + ".xlsx"

    try:
        rad = pd.read_excel(excel)
    except FileNotFoundError as error:
        sp = sunpath.calculateSunPath(fileName)
        r = radiation.calculateRadiation(fileName)
        rad = pd.read_excel(excel)
    I_sn = rad['Northern']
    I_se = rad['Eastern']
    I_ss = rad['Southern']
    I_sw = rad['Western']

    sol_airn = np.empty(N)
    sol_aire = np.empty(N)
    sol_airs = np.empty(N)
    sol_airw = np.empty(N)

    at = np.empty(N)
    sky = []
    for i in range(N):
        sol_airn[i] = T_sa(i, I_sn)
        sol_aire[i] = T_sa(i, I_se)
        sol_airs[i] = T_sa(i, I_ss)
        sol_airw[i] = T_sa(i, I_sw)
        at[i] = air_temp(hour[i])

    # plot(sol_airn)
    # plot(sol_aire)
    # plot(sol_airw)
    # plot(sol_airs)
    # show()
    # #heat

    # T1n = np.empty(N)
    # T2n = np.empty(N)
    # T1e = np.empty(N)
    # T2e = np.empty(N)
    # T1s = np.empty(N)
    # T2s = np.empty(N)
    # T1w = np.empty(N)
    # T2w = np.empty(N)

    # T1n[0] = 273.15 + Ti
    # T2n[0] = 273.15 + Ti+.001
    # T1e[0] = 273.15 + Ti
    # T2e[0] = 273.15 + Ti+.001
    # T1s[0] = 273.15 + Ti
    # T2s[0] = 273.15 + Ti+.001
    # T1w[0] = 273.15 + Ti
    # T2w[0] = 273.15 + Ti+.001

    # T1nf = np.empty(N)
    # T2nf = np.empty(N)
    # T1ef = np.empty(N)
    # T2ef = np.empty(N)
    # T1sf = np.empty(N)
    # T2sf = np.empty(N)
    # T1wf = np.empty(N)
    # T2wf = np.empty(N)

    # T1nf[0] = 273.15 + Ti
    # T2nf[0] = 273.15 + Ti+.001
    # T1ef[0] = 273.15 + Ti
    # T2ef[0] = 273.15 + Ti+.001
    # T1sf[0] = 273.15 + Ti
    # T2sf[0] = 273.15 + Ti+.001
    # T1wf[0] = 273.15 + Ti
    # T2wf[0] = 273.15 + Ti+.001

    # Tair = np.empty(N)
    # Tair[0] = 273.15 + Ti
    # Tfree = np.empty(N)
    # Tfree[0] = 273.15 + Ti

    # s = (noOfDays*24*3600-0)/N

    # an = width*height
    # ae = length*height
    # aS = width*height
    # aw = length*width

    # A_f = (length-2*thickness)*(width-2*thickness)
    # V = A_f*(height)
    # dens = 1.225 #density of air
    # c_a = 0.718*1000 #specific heat of air
    # C_air = V*dens*c_a

    # Q = np.zeros(N)

    # a = thickness*height

    # Tc = np.empty(N)
    # Tc[0] = Tair[0]

    Tcomfmin = Tcomf - 3
    Tcomfmax = Tcomf + 1

    dc = []
    c = []

    pow = np.linspace(0, 2000, 2001)
    for k in pow:
        T1n = np.empty(N)
        T2n = np.empty(N)
        T1e = np.empty(N)
        T2e = np.empty(N)
        T1s = np.empty(N)
        T2s = np.empty(N)
        T1w = np.empty(N)
        T2w = np.empty(N)

        T1n[0] = 273.15 + Ti
        T2n[0] = 273.15 + Ti + .001
        T1e[0] = 273.15 + Ti
        T2e[0] = 273.15 + Ti + .001
        T1s[0] = 273.15 + Ti
        T2s[0] = 273.15 + Ti + .001
        T1w[0] = 273.15 + Ti
        T2w[0] = 273.15 + Ti + .001

        T1nf = np.empty(N)
        T2nf = np.empty(N)
        T1ef = np.empty(N)
        T2ef = np.empty(N)
        T1sf = np.empty(N)
        T2sf = np.empty(N)
        T1wf = np.empty(N)
        T2wf = np.empty(N)

        T1nf[0] = 273.15 + Ti
        T2nf[0] = 273.15 + Ti + .001
        T1ef[0] = 273.15 + Ti
        T2ef[0] = 273.15 + Ti + .001
        T1sf[0] = 273.15 + Ti
        T2sf[0] = 273.15 + Ti + .001
        T1wf[0] = 273.15 + Ti
        T2wf[0] = 273.15 + Ti + .001

        Tair = np.empty(N)
        Tair[0] = 273.15 + Ti
        Tfree = np.empty(N)
        Tfree[0] = 273.15 + Ti

        s = (noOfDays * 24 * 3600 - 0) / N

        an = width * height
        ae = length * height
        aS = width * height
        aw = length * width

        A_f = (length - 2 * thickness) * (width - 2 * thickness)
        V = A_f * (height)
        dens = 1.225  #density of air
        c_a = 0.718 * 1000  #specific heat of air
        C_air = V * dens * c_a

        Q = np.zeros(N)

        a = thickness * height

        Tc = np.empty(N)
        Tc[0] = Tair[0]

        for i in range(N - 1):

            T1n[i + 1] = T1n[i] + s * (h_rc *
                                       ((sol_airn[i] + 273.15) - T1n[i]) / Cc +
                                       (T2n[i] - T1n[i]) / (R * Cc))
            T1nf[i +
                 1] = T1nf[i] + s * (h_rc *
                                     ((sol_airn[i] + 273.15) - T1nf[i]) / Cc +
                                     (T2nf[i] - T1nf[i]) / (R * Cc))

            T2n[i + 1] = T2n[i] + s * (h_c * (Tfree[i] - T2n[i]) / Cc -
                                       (T2n[i] - T1n[i]) / (R * Cc))
            T2nf[i + 1] = T2nf[i] + s * (h_c * (Tair[i] - T2nf[i]) / Cc -
                                         (T2nf[i] - T1nf[i]) / (R * Cc))

            T1e[i + 1] = T1e[i] + s * (h_rc *
                                       ((sol_aire[i] + 273.15) - T1e[i]) / Cc +
                                       (T2e[i] - T1e[i]) / (R * Cc))
            T1ef[i +
                 1] = T1ef[i] + s * (h_rc *
                                     ((sol_aire[i] + 273.15) - T1ef[i]) / Cc +
                                     (T2ef[i] - T1ef[i]) / (R * Cc))

            T2e[i + 1] = T2e[i] + s * (h_c * (Tfree[i] - T2e[i]) / Cc -
                                       (T2e[i] - T1e[i]) / (R * Cc))
            T2ef[i + 1] = T2ef[i] + s * (h_c * (Tair[i] - T2ef[i]) / Cc -
                                         (T2ef[i] - T1ef[i]) / (R * Cc))

            T1s[i + 1] = T1s[i] + s * (h_rc *
                                       ((sol_airs[i] + 273.15) - T1s[i]) / Cc +
                                       (T2s[i] - T1s[i]) / (R * Cc))
            T1sf[i +
                 1] = T1sf[i] + s * (h_rc *
                                     ((sol_airs[i] + 273.15) - T1sf[i]) / Cc +
                                     (T2sf[i] - T1sf[i]) / (R * Cc))

            T2s[i + 1] = T2s[i] + s * (h_c * (Tfree[i] - T2s[i]) / Cc -
                                       (T2s[i] - T1s[i]) / (R * Cc))
            T2sf[i + 1] = T2sf[i] + s * (h_c * (Tair[i] - T2sf[i]) / Cc -
                                         (T2sf[i] - T1sf[i]) / (R * Cc))

            T1w[i + 1] = T1w[i] + s * (h_rc *
                                       ((sol_airw[i] + 273.15) - T1w[i]) / Cc +
                                       (T2w[i] - T1w[i]) / (R * Cc))
            T1wf[i +
                 1] = T1wf[i] + s * (h_rc *
                                     ((sol_airw[i] + 273.15) - T1wf[i]) / Cc +
                                     (T2wf[i] - T1wf[i]) / (R * Cc))

            T2w[i + 1] = T2w[i] + s * (h_c * (Tfree[i] - T2w[i]) / Cc -
                                       (T2w[i] - T1w[i]) / (R * Cc))
            T2wf[i + 1] = T2wf[i] + s * (h_c * (Tair[i] - T2wf[i]) / Cc -
                                         (T2wf[i] - T1wf[i]) / (R * Cc))

            Q[i] = k  #h_c*((an-a)*(T2nf[i]-273.15-Tcomf)+(ae-a)*(T2ef[i]-273.15-Tcomf)+(aS-a)*(T2sf[i]-273.15-Tcomf)+(aw-a)*(T2wf[i]-273.15-Tcomf))

            if Q[i] < 0:
                Q[i] = 0

            Tfree[i + 1] = Tfree[i] + s * (h_c *
                                           ((an - a) * (T2n[i] - Tfree[i]) +
                                            (ae - a) * (T2e[i] - Tfree[i]) +
                                            (aS - a) * (T2s[i] - Tfree[i]) +
                                            (aw - a) *
                                            (T2w[i] - Tfree[i]))) / (C_air)
            Tair[i + 1] = Tair[i] + s * (h_c * (
                (an - a) * (T2nf[i] - Tair[i]) + (ae - a) *
                (T2ef[i] - Tair[i]) + (aS - a) * (T2sf[i] - Tair[i]) +
                (aw - a) * (T2wf[i] - Tair[i]))) / (C_air) - s * Q[i] / (C_air)

        Q[N - 1] = Q[N - 2]

        #
        secs = np.linspace(0, noOfDays * 24 * 3600, N)
        energy = simps(y=Q, x=secs, even='avg')

        #show_plot(Tair,Tfree,at,Q, days,fileName)
        Tairp = np.empty(N)
        np.copyto(Tairp, Tair)

        discomfort = measureD(Tair, secs, Tcomfmin, Tcomfmax)
        comfort = measureC(Tairp, secs, Tcomfmin, Tcomfmax)

        print(fileName)
        print('Required energy {} (days):{} kJ'.format(
            noOfDays, round((energy / 1000), 2)))
        print('Average power required: {} W'.format(round(Q.mean(), 2)))
        print('Average temperature in free mode: {} C'.format(Tfree.mean() -
                                                              273.15))
        print('Discomfort (D): {}'.format(
            round(discomfort / (comfort + discomfort), 3)))
        print('Comfort (C): {}'.format(
            round(comfort / (comfort + discomfort), 3)))
        dc.append(round(discomfort / (comfort + discomfort), 3))
        c.append(round(comfort / (comfort + discomfort), 3))
    days = dayNames(days)
    fig = figure('Thermal Comfort vs Power')
    energy = fig.add_subplot(111, axisbg='black')
    energy.set_axisbelow(True)
    energy.xaxis.set_ticks(np.arange(0, 2000, 100))
    params = {'mathtext.default': 'regular'}
    rcParams.update(params)
    energy.xaxis.grid(True, 'major', linewidth=.5, linestyle='-', color='w')
    energy.yaxis.grid(True, 'major', linewidth=.5, linestyle='-', color='w')
    energy.set_xlabel("Power ($W$)")
    energy.set_ylabel("Thermal Comfort")
    energy.plot(pow, dc, label='Discomfort ($Q$)', linewidth='1.5')
    energy.plot(pow, c, label='Comfort ($P$)', linewidth='1.5')
    energy.legend(loc='best', fontsize='medium', fancybox=True, shadow=True)
    show()

    c = np.array(c)
    index_comf_power = np.where(c == 1)
    min_opt_power = index_comf_power[0][0]
    max_opt_power = index_comf_power[0][len(index_comf_power[0]) - 1]

    pow = [min_opt_power, max_opt_power]
    count = 0
    for k in pow:
        T1n = np.empty(N)
        T2n = np.empty(N)
        T1e = np.empty(N)
        T2e = np.empty(N)
        T1s = np.empty(N)
        T2s = np.empty(N)
        T1w = np.empty(N)
        T2w = np.empty(N)

        T1n[0] = 273.15 + Ti
        T2n[0] = 273.15 + Ti + .001
        T1e[0] = 273.15 + Ti
        T2e[0] = 273.15 + Ti + .001
        T1s[0] = 273.15 + Ti
        T2s[0] = 273.15 + Ti + .001
        T1w[0] = 273.15 + Ti
        T2w[0] = 273.15 + Ti + .001

        T1nf = np.empty(N)
        T2nf = np.empty(N)
        T1ef = np.empty(N)
        T2ef = np.empty(N)
        T1sf = np.empty(N)
        T2sf = np.empty(N)
        T1wf = np.empty(N)
        T2wf = np.empty(N)

        T1nf[0] = 273.15 + Ti
        T2nf[0] = 273.15 + Ti + .001
        T1ef[0] = 273.15 + Ti
        T2ef[0] = 273.15 + Ti + .001
        T1sf[0] = 273.15 + Ti
        T2sf[0] = 273.15 + Ti + .001
        T1wf[0] = 273.15 + Ti
        T2wf[0] = 273.15 + Ti + .001

        Tair = np.empty(N)
        Tair[0] = 273.15 + Ti
        Tfree = np.empty(N)
        Tfree[0] = 273.15 + Ti

        s = (noOfDays * 24 * 3600 - 0) / N

        an = width * height
        ae = length * height
        aS = width * height
        aw = length * width

        A_f = (length - 2 * thickness) * (width - 2 * thickness)
        V = A_f * (height)
        dens = 1.225  #density of air
        c_a = 0.718 * 1000  #specific heat of air
        C_air = V * dens * c_a

        Q = np.zeros(N)

        a = thickness * height

        Tc = np.empty(N)
        Tc[0] = Tair[0]

        for i in range(N - 1):

            T1n[i + 1] = T1n[i] + s * (h_rc *
                                       ((sol_airn[i] + 273.15) - T1n[i]) / Cc +
                                       (T2n[i] - T1n[i]) / (R * Cc))
            T1nf[i +
                 1] = T1nf[i] + s * (h_rc *
                                     ((sol_airn[i] + 273.15) - T1nf[i]) / Cc +
                                     (T2nf[i] - T1nf[i]) / (R * Cc))

            T2n[i + 1] = T2n[i] + s * (h_c * (Tfree[i] - T2n[i]) / Cc -
                                       (T2n[i] - T1n[i]) / (R * Cc))
            T2nf[i + 1] = T2nf[i] + s * (h_c * (Tair[i] - T2nf[i]) / Cc -
                                         (T2nf[i] - T1nf[i]) / (R * Cc))

            T1e[i + 1] = T1e[i] + s * (h_rc *
                                       ((sol_aire[i] + 273.15) - T1e[i]) / Cc +
                                       (T2e[i] - T1e[i]) / (R * Cc))
            T1ef[i +
                 1] = T1ef[i] + s * (h_rc *
                                     ((sol_aire[i] + 273.15) - T1ef[i]) / Cc +
                                     (T2ef[i] - T1ef[i]) / (R * Cc))

            T2e[i + 1] = T2e[i] + s * (h_c * (Tfree[i] - T2e[i]) / Cc -
                                       (T2e[i] - T1e[i]) / (R * Cc))
            T2ef[i + 1] = T2ef[i] + s * (h_c * (Tair[i] - T2ef[i]) / Cc -
                                         (T2ef[i] - T1ef[i]) / (R * Cc))

            T1s[i + 1] = T1s[i] + s * (h_rc *
                                       ((sol_airs[i] + 273.15) - T1s[i]) / Cc +
                                       (T2s[i] - T1s[i]) / (R * Cc))
            T1sf[i +
                 1] = T1sf[i] + s * (h_rc *
                                     ((sol_airs[i] + 273.15) - T1sf[i]) / Cc +
                                     (T2sf[i] - T1sf[i]) / (R * Cc))

            T2s[i + 1] = T2s[i] + s * (h_c * (Tfree[i] - T2s[i]) / Cc -
                                       (T2s[i] - T1s[i]) / (R * Cc))
            T2sf[i + 1] = T2sf[i] + s * (h_c * (Tair[i] - T2sf[i]) / Cc -
                                         (T2sf[i] - T1sf[i]) / (R * Cc))

            T1w[i + 1] = T1w[i] + s * (h_rc *
                                       ((sol_airw[i] + 273.15) - T1w[i]) / Cc +
                                       (T2w[i] - T1w[i]) / (R * Cc))
            T1wf[i +
                 1] = T1wf[i] + s * (h_rc *
                                     ((sol_airw[i] + 273.15) - T1wf[i]) / Cc +
                                     (T2wf[i] - T1wf[i]) / (R * Cc))

            T2w[i + 1] = T2w[i] + s * (h_c * (Tfree[i] - T2w[i]) / Cc -
                                       (T2w[i] - T1w[i]) / (R * Cc))
            T2wf[i + 1] = T2wf[i] + s * (h_c * (Tair[i] - T2wf[i]) / Cc -
                                         (T2wf[i] - T1wf[i]) / (R * Cc))

            Q[i] = k  #h_c*((an-a)*(T2nf[i]-273.15-Tcomf)+(ae-a)*(T2ef[i]-273.15-Tcomf)+(aS-a)*(T2sf[i]-273.15-Tcomf)+(aw-a)*(T2wf[i]-273.15-Tcomf))

            if Q[i] < 0:
                Q[i] = 0

            Tfree[i + 1] = Tfree[i] + s * (h_c *
                                           ((an - a) * (T2n[i] - Tfree[i]) +
                                            (ae - a) * (T2e[i] - Tfree[i]) +
                                            (aS - a) * (T2s[i] - Tfree[i]) +
                                            (aw - a) *
                                            (T2w[i] - Tfree[i]))) / (C_air)
            Tair[i + 1] = Tair[i] + s * (h_c * (
                (an - a) * (T2nf[i] - Tair[i]) + (ae - a) *
                (T2ef[i] - Tair[i]) + (aS - a) * (T2sf[i] - Tair[i]) +
                (aw - a) * (T2wf[i] - Tair[i]))) / (C_air) - s * Q[i] / (C_air)

        Q[N - 1] = Q[N - 2]

        #
        secs = np.linspace(0, noOfDays * 24 * 3600, N)
        energy = simps(y=Q, x=secs, even='avg')
        if count == 0:
            title = '(minimum comfortable power: {} W)'.format(k)
        else:
            title = '(maximum comfortable power: {} W)'.format(k)
        show_plot(Tair, Tfree, at, Q, days, fileName + ' ' + title)
        show()
        count += 1

        secs = np.linspace(0, noOfDays * 24 * 3600, N)
        energy = simps(y=Q, x=secs, even='avg')

        #show_plot(Tair,Tfree,at,Q, days,fileName)
        Tairp = np.empty(N)
        np.copyto(Tairp, Tair)

        discomfort = measureD(Tair, secs, Tcomfmin, Tcomfmax)
        comfort = measureC(Tairp, secs, Tcomfmin, Tcomfmax)

        print('Required energy {} (days):{} kJ'.format(
            noOfDays, round((energy / 1000), 2)))
        print('Average power required: {} W'.format(round(Q.mean(), 2)))
        print('Average temperature in free mode: {} C'.format(Tfree.mean() -
                                                              273.15))
        print('Discomfort (D): {}'.format(
            round(discomfort / (comfort + discomfort), 3)))
        print('Comfort (C): {}'.format(
            round(comfort / (comfort + discomfort), 3)))
Пример #32
0
from pylearn2.utils import serial
import sys
from matplotlib import pyplot
from pylearn2.config import yaml_parse
import theano.tensor as T
from theano import function
import numpy as np
from matplotlib.pyplot import figure, axes
from matplotlib.pyplot import rcParams

figure(figsize=(4.5, 2.0))
axes([0.1, 0.2, 0.88, 0.6])
#figure(figsize=(4.5, 3.))
rcParams.update({'xtick.labelsize' : 8, 'ytick.labelsize' : 8})
rcParams['ps.useafm'] = True
rcParams['pdf.use14corefonts'] = True
rcParams['text.usetex'] = True

ignore, model_path = sys.argv

model = serial.load(model_path)

dataset_yaml_src = model.dataset_yaml_src

dataset = yaml_parse.load(dataset_yaml_src)

input_space = model.get_input_space()

X = input_space.make_theano_batch()
if X.ndim > 2:
    assert False # doesn't support topo yet