Beispiel #1
0
def test_lindblad():
    mesolver = Lindblad_solver(H, c_ops=[sz.astype(complex)])
    Nt = 800
    dt = 0.5

    import time
    start_time = time.time()
    # L = mesolver.liouvillian()
    t0 = -10 / au2fs
    result = mesolver.evolve(rho0,
                             dt=dt,
                             Nt=Nt,
                             e_ops=[H1],
                             return_result=True,
                             t0=t0)
    #corr = mesolver.correlation_3op_2t(rho0, [sz, sz, sz], dt, Nt, Ntau=Nt)

    # print(result.observables)
    import proplot as plt
    fig, ax = plt.subplots()
    times = np.arange(Nt) * dt + t0
    ax.plot(times, result.observables[:, 0])
    ax.format(ylabel='Coherence')

    print('Execution time = {} s'.format(time.time() - start_time))

    fig, ax = plt.subplots()
    ax.plot(times, pulse.field(times))
    ax.set_ylabel('E(t)')
    return
Beispiel #2
0
def plot_reaction_rate_burning_rate(df_rate):
    fig, ax = pplot.subplots(aspect=(4, 3), axwidth=4)
    c1 = pplot.scale_luminance('cerulean', 0.5)
    c2 = pplot.scale_luminance('red', 0.5)
    df_rate.sort_values(by="time", inplace=True)

    lns1 = ax.plot(df_rate["time"],
                   df_rate["vol_averaged_reaction_rate"],
                   color=c1,
                   label="Reaction rate")

    max_rate = df_rate["vol_averaged_reaction_rate"].max()
    ax.format(xlabel="Time (s)",
              ylabel="Volume-Averaged coke reaction rate (kg/m$^3$/s)",
              ycolor=c1,
              ylim=(-1, max_rate * 1.1))

    ax2 = ax.twinx()
    lns2 = ax2.plot(df_rate["time"],
                    df_rate["burning_fraction"] * 100,
                    color=c2,
                    linestyle="--",
                    label="Conversion")
    ax2.format(xlabel="Time (s)",
               ylabel="Conversion (%)",
               ycolor=c2,
               ylim=(-1, 100))

    lns = lns1 + lns2
    labs = [l.get_label() for l in lns]
    ax.legend(lns, labs, loc="upper right", fancybox=True)

    return ax, ax2, fig
Beispiel #3
0
def test_sesolver():
    s0, sx, sy, sz = pauli()
    H = (-0.05) * sz - 0. * sx

    solver = SESolver(H)
    Nt = 1000
    dt = 4
    psi0 = (basis(2, 0) + basis(2, 1)) / np.sqrt(2)
    start_time = time.time()

    result = solver.evolve(psi0, dt=dt, Nt=Nt, e_ops=[sx])
    print("--- %s seconds ---" % (time.time() - start_time))

    start_time = time.time()

    times = np.arange(Nt) * dt
    r = _ode_solver(H, psi0, dt=dt, Nt=Nt, nout=2, e_ops=[sx])

    print("--- %s seconds ---" % (time.time() - start_time))

    # test correlation functions
    # corr = solver.correlation_3p_1t(psi0=psi0, oplist=[s0, sx, sx],
    #                                 dt=0.05, Nt=Nt)
    #
    # times = np.arange(Nt)
    #
    import matplotlib.pyplot as plt

    fig, ax = plt.subplots()
    ax.plot(times, result.observables[:, 0])
    ax.plot(r.times, r.observables[:, 0], '--')
    # ax.plot(times, corr.real)
    plt.show()
Beispiel #4
0
def Plot_MaxTemperature_OutletO2ConcHistory(df_combined):
    fig, ax = pplot.subplots(aspect=(4, 3), axwidth=4)

    lns1 = ax.plot(df_combined["Time"],
                   df_combined["max"],
                   color=c1,
                   label="Max Point Temperature",
                   linestyle="-")
    lns2 = ax.plot(df_combined["Time"],
                   df_combined["Transverse_Tmax"],
                   color=c1,
                   label="Max Transversely Averaged Temperature",
                   linestyle="--")
    ax.format(xlabel="Time (s)", ylabel="Temperature (K)", ycolor=c1)

    ax2 = ax.twinx()
    lns3 = ax2.plot(df_combined["Time"],
                    df_combined["O2ConcAtOutlet"],
                    color=c2,
                    linestyle="-.",
                    label="O$_2$ Molar Concentration at outlet")
    max_O2 = df_combined["O2ConcAtOutlet"].max()
    ax2.format(ylabel="O$_2$ mole concentration At Outlet (mol/m$^3$)",
               ycolor=c2)

    lns = lns1 + lns2 + lns3
    labs = [l.get_label() for l in lns]
    ax.legend(lns, labs, loc="upper right", ncol=1, fancybox=True)

    # fig.tight_layout()
    return ax, ax2, fig
Beispiel #5
0
def linear_absorption(omegas, transition_energies, dip, output=None, \
                      gamma=1./au2ev, normalize=False):
    '''
    SOS for linear absorption signal S = 2 pi |mu_{fg}|^2 delta(omega - omega_{fg}).
    The delta function is replaced with a Lorentzian function.

    Parameters
    ----------
    omegas : 1d array
        the frequency range for the signal
    transition_energies : TYPE
        DESCRIPTION.
    edip : 1d array
        transtion dipole moment
    output : TYPE, optional
        DESCRIPTION. The default is None.
    gamma : float, optional
        Lifetime broadening. The default is 1./au2ev.
    normalize : TYPE, optional
        Normalize the maximum intensity of the signal as 1. The default is False.

    Returns
    -------
    signal : 1d array
        linear absorption signal at omegas

    '''

    signal = 0.0

    for j, transition_energy in enumerate(transition_energies):

        signal += dip[j]**2 * lorentzian(omegas - transition_energy, gamma)

    if normalize:
        signal /= max(signal)

    if output is not None:

        fig, ax = plt.subplots(figsize=(4, 3))

        ax.plot(omegas * au2ev, signal)

        #scale = 1./np.sum(dip**2)

        for j, transition_energy in enumerate(transition_energies):
            ax.axvline(transition_energy * au2ev, 0., dip[j]**2, color='grey')

        ax.set_xlim(min(omegas) * au2ev, max(omegas) * au2ev)
        ax.set_xlabel('Energy (keV)')
        ax.set_ylabel('Absorption')
        #ax.set_yscale('log')
        # ax.set_ylim(0, 1)

        # fig.subplots_adjust(wspace=0, hspace=0, bottom=0.15, \
        # left=0.17, top=0.96, right=0.96)
        fig.savefig(output, dpi=1200, transparent=True)

    return signal
Beispiel #6
0
def plot_bamf_p(bAmfClr, bAmfCld, output_fig_dir):
    '''plot bAmf at each pressure level'''
    for p_index in range(bAmfClr.shape[0]):
        f, axs = plot.subplots(ncols=2)
        x, y = np.meshgrid(bAmfClr.x, bAmfClr.y)
        m1 = axs[0].pcolormesh(y, x, bAmfClr[p_index, ...], levels=256)
        m2 = axs[1].pcolormesh(y, x, bAmfCld[p_index, ...], levels=256)
        axs[0].colorbar(m1, loc='r', label='bAmfClr')
        axs[1].colorbar(m2, loc='r', label='bAmfCld')

        # save figure
        output_name = os.path.join(output_fig_dir, f'bAmf_layer{p_index}.png')
        logging.info(f'Saving bAmf to {output_name}')
        f.savefig(output_name)
Beispiel #7
0
def relative(name, dir_):
    """
    Plots relative time comparisons.
    """
    cats, nlats, sizes, tables = runtimes(name, dir_)
    inco, = np.where(np.array([cat.lower() for cat in cats]) == 'nco')
    inco = inco[0]
    f, ax = plot.subplots(axwidth=2.5,
                          aspect=(2, 3),
                          legend='b',
                          span=False,
                          share=1)
    hs = []
    ic, xc = 0, 0  # make xarray lines different shades of same color
    ref = np.array([table[inco][3] for table in tables])
    for i in idxs:
        if i == inco:
            continue
        cat = cats[i]
        if 'xarray' in cat.lower():
            color = xcolors[xc]
            xc += 1
        else:
            # color = f'C{ic}'
            color = ocolors[ic]
            ic += 1
        times = [table[i][3]
                 for table in tables]  # 4th cell contains 'real' time
        hs += ax.plot(sizes,
                      np.array(times) / ref,
                      color=color,
                      marker='o',
                      markersize=6,
                      label=cat,
                      lw=1)
    ax.format(xlabel='file size (MB)',
              ylabel='ratio',
              gridminor=True,
              ylim=(0.1, 3),
              yscale='log',
              yformatter='scalar',
              xlim=(min(sizes), max(sizes)),
              xscale='log',
              xformatter='scalar',
              suptitle=f'{name.title()} benchmark relative to NCO')
    f.bpanel.legend(hs, ncols=2, order='F')
    return f
Beispiel #8
0
def plot_all_stations(
        df,
        df_diff,
        ncols=2,
        days_smooth_gps=30,
        ylim=None,
        share=False,
        figsize=(10, 10),
        outname=None,
        drop_na_insar=True,
):
    import proplot as pplt

    nplots = len(df_diff.index)
    # fig, axes = plt.subplots(
    fig, axes = pplt.subplots(
        nrows=int(np.ceil(nplots / ncols)),
        ncols=ncols,
        # refwidth=1,
        # refheight=1,
        figsize=figsize,
        sharex=share,
        sharey=share,
        # figsize=(4 * ncols, nplots)
    )
    # axes = axes.ravel()
    for idx, n in enumerate(df_diff.index):
        # ax = axes.ravel()[idx]
        ax = axes[idx]
        gps_col, insar_col = f"{n}_gps", f"{n}_insar"
        # curdf = df[[]]  # .dropna()
        ax.plot(df.index, df[gps_col], marker="o", ms=1, alpha=0.3)
        _plot_smoothed(ax, df, gps_col, days_smooth_gps, "-")

        insar_df = df[[insar_col
                       ]].dropna() if drop_na_insar else df[[insar_col]]
        ax.plot(insar_df.index, insar_df[insar_col], marker="o", ms=1)
        # print(df[insar_col].dropna())
        # ax.legend()
        # ax.grid()
        ax.set_title(n)
    axes.format(grid=True, ylim=ylim, ylabel="cm")
    if outname:
        fig.savefig(outname)
    return fig, axes
Beispiel #9
0
def plot_fig(values, ticks, title, filename):
    NTA_lats = [-90, 90]
    NTA_lons = [-180, 180]

    gap_x, gap_y = 1, 1

    levels = 11
    map_lon = np.arange(-180, 180, gap_x)
    map_lat = np.arange(-90, 90, gap_y)
    Lon, Lat = np.meshgrid(map_lon, map_lat)

    fig, axs = plot.subplots(nrows=1,
                             ncols=1,
                             aspect=2,
                             axwidth=4,
                             basemap=False,
                             proj='cyl')  #proj_kw={'lon_0': 180})

    m = axs[0, 0].contourf(map_lon,
                           map_lat,
                           values,
                           levels=ticks,
                           extend='both',
                           cmap='Spectral',
                           norm='segmented',
                           colorbar='r',
                           colorbar_kw={'ticks': ticks})

    # axs[0,0].format(title='Cloud Top Temperature (Kelvin)')

    axs.format(suptitle=title,
               landcolor='mushroom',
               facecolor='white',
               land=False,
               reso='med',
               borders=True,
               titleborder=True,
               lonlabels='b',
               latlabels='l',
               coast=True,
               latlines=30,
               lonlines=60)

    fig.savefig(filename, facecolor='white', dpi=300)
Beispiel #10
0
def plot_comp_s5p_chem(s5p, ds, output_fig_dir):
    '''Plot the comparison between S5P TM5 and CHEM product'''

    # load data
    s5p_amfClr = s5p['air_mass_factor_clear']
    s5p_amfCld = s5p['air_mass_factor_cloudy']
    amfClr = ds['scdClr'] / ds['vcdGnd']
    amfCld = ds['scdCld'] / ds['vcdGnd']

    # crop the data to data valid domain which usually is the wrfchem domain
    valid = ~amfClr.isnull()
    amfClr = amfClr.where(valid, drop=True)
    amfCld = amfCld.where(valid, drop=True)
    s5p_amfClr = s5p_amfClr.where(valid, drop=True)
    s5p_amfCld = s5p_amfCld.where(valid, drop=True)

    # plot
    f, axs = plot.subplots(nrows=3, ncols=2)

    vmax = max(s5p_amfClr.max(), amfClr.max()).values
    s5p_amfClr.plot(ax=axs[0], vmin=0, vmax=vmax)
    amfClr.plot(ax=axs[1], vmin=0, vmax=vmax)

    vmax = max(s5p_amfCld.max(), amfCld.max()).values
    s5p_amfCld.plot(ax=axs[2], vmin=0, vmax=vmax)
    amfCld.plot(ax=axs[3], vmin=0, vmax=vmax)

    (s5p_amfClr / amfClr).plot(ax=axs[4], vmin=0)
    (s5p_amfCld / amfCld).plot(ax=axs[5], vmin=0)

    axs[0].format(title='S5P AMFClr')
    axs[1].format(title='CHEM AMFClr')
    axs[2].format(title='S5P AMFCld')
    axs[3].format(title='CHEM AMFCld')
    axs[4].format(title='AMFClr (S5P/CHEM)')
    axs[5].format(title='AMFCld (S5P/CHEM)')

    # save figure
    output_name = os.path.join(output_fig_dir, 'comp_chem_tm5.png')
    logging.info(f'Saving to {output_name}')
    f.savefig(output_name)
Beispiel #11
0
def set_axis(file_list):
    '''set the axis format'''
    f, axs = plot.subplots(proj='eqc',
                           nrows=math.ceil((len(file_list)/4)),
                           ncols=4,
                           span=False,
                           share=3)

    axs.format(abc=True,
               abcloc='l',
               abcstyle='(a)',
               labels=True,
               lonlines=lon_d,
               latlines=lat_d,
               lonlim=(extend[0], extend[1]),
               latlim=(extend[2], extend[3]),
               geogridlinewidth=1,
               geogridcolor='w',
               )

    return axs, f
Beispiel #12
0
def set_axis(radar_list):
    '''set the axis format'''
    f, axs = plot.subplots(proj='eqc',
                           ncols=len(radar_list),
                           nrows=2,
                           span=False,
                           share=3)

    axs.format(
        rowlabels=['CRF', 'Flashrate'],
        abc=True,
        abcloc='l',
        abcstyle='a)',
        labels=True,
        lonlines=lon_d,
        latlines=lat_d,
        lonlim=(extend[0], extend[1]),
        latlim=(extend[2], extend[3]),
        geogridlinewidth=1,
        geogridcolor='w',
    )

    return axs, f
Beispiel #13
0
    def cars(self, shift, omega1, t2=0., plt_signal=False, fname=None):

        edip = self.edip_rms
        E = self.eigvals()

        S = sos.cars(E, edip, shift, omega1, t2=t2)

        if not plt_signal:

            return S

        else:

            fig, ax = plt.subplots()

            ax.contourf(shift*au2wavenumber, omega1*au2ev, S.imag.T, lw=0.6,\
                        cmap='spectral')

            ax.format(xlabel='Raman shift (cm$^{-1}$)',
                      ylabel=r'$\Omega_1$ (eV)')

            fig.savefig(fname + '.pdf')

            return S, fig, ax
Beispiel #14
0
#    column share the same axis limits, scales, ticks, and labels. This is often
#    convenient, but may be annoying for some users. To keep this feature turned off,
#    simply :ref:`change the default settings <ug_rc>` with e.g.
#    ``plot.rc.update(share=False, span=False)``. See :ref:`this section <ug_share>`
#    for details.

# %%
# Generate sample data
import numpy as np
state = np.random.RandomState(51423)
data = 2 * (state.rand(100, 5) - 0.5).cumsum(axis=0)

# %%
# Single subplot
import proplot as plot
fig, ax = plot.subplots()
ax.plot(data, lw=2)
ax.format(suptitle='Single subplot', xlabel='x axis', ylabel='y axis')

# %%
# Simple subplot grid
import proplot as plot
fig, axs = plot.subplots(ncols=2)
axs[0].plot(data, lw=2)
axs[0].format(xticks=20, xtickminor=False)
axs.format(suptitle='Simple subplot grid',
           title='Title',
           xlabel='x axis',
           ylabel='y axis')

# %%
Beispiel #15
0
data = fits.getdata("coadded_and_subtracted_cube.fits")
corrs = fits.getdata("correllelagrams.fits")
indices = range(39, 49)

dataframes = data[indices]
corrsframes = corrs[indices, 24:75, 24:75]

dataflat = np.hstack([fr for fr in dataframes])
corrsflat = np.hstack([fr for fr in corrsframes])

# recreate power stretch
a = 1000
corrspower = (a**corrsflat - 1) / a

fig, axs = plot.subplots(figsize=("510px", "140px"), nrows=2, hspace=0)
ymax = corrspower.shape[0]
ymid = ymax // 2
xmax = corrsflat.shape[1]
xmid = corrsframes.shape[-1] // 2

axs[0].imshow(dataflat,
              cmap="inferno",
              origin="lower",
              extent=(-0.5, 509.5, -0.5, 50.5))
axs[0].format(xlim=(0, xmax), ylim=(0, ymax))

axs[1].imshow(corrspower, cmap="inferno", origin="lower")
axs[1].hlines(ymid, 0, xmax, color="white", ls="--", lw=0.2)
xs = range(xmid, corrsflat.shape[1], corrsframes.shape[-1])
axs[1].vlines(xs, 0, ymax, color="white", ls="--", lw=0.2)
Beispiel #16
0
    ave_T_var_sumstar_nf[j] = st2.spatial_ave_xr(Tvar_sumstar_nf.sel(lon=slice(lonbounds_ave[0],lonbounds_ave[1])), lats=lats.sel(lat=slice(latbounds_ave[0],latbounds_ave[1])))
    
    ave_T_var_lambdaQs[j] = st2.spatial_ave_xr(Tvar_lambdaQs.sel(lon=slice(lonbounds_ave[0],lonbounds_ave[1])), lats=lats.sel(lat=slice(latbounds_ave[0],latbounds_ave[1])))
    ave_T_var_lambdaQr[j] = st2.spatial_ave_xr(Tvar_lambdaQr.sel(lon=slice(lonbounds_ave[0],lonbounds_ave[1])), lats=lats.sel(lat=slice(latbounds_ave[0],latbounds_ave[1])))
    ave_T_var_lambdaQtot[j] = st2.spatial_ave_xr(Tvar_lambdaQtot.sel(lon=slice(lonbounds_ave[0],lonbounds_ave[1])), lats=lats.sel(lat=slice(latbounds_ave[0],latbounds_ave[1])))
    
    # ave_T_var_lambdaQs[j] = st2.spatial_ave_xr(Tvar_Qs - Tvar_Qsstar, lats)
    # ave_T_var_lambdaQr[j] = st2.spatial_ave_xr(Tvar_Qr - Tvar_Qrstar, lats)
    
    print('T_var_sum', ave_T_var_sum[j])
    print('T_var', ave_T_var[j])
    
    
    

fig, axs = plot.subplots(ncols=1, nrows=2, aspect=1.2, tight=True, share=False, hratios=(3,2))
#plot.subplots(ncols=2, nrows=3)
h1=axs[0].plot(Tns/12., ave_T_var_Qs, color='C2', label=r'$Q_s$', linewidth=2, zorder=5)
#plt.plot(Tns/12., ave_T_var_thf, color='C3', label=r'$THF$')
#plt.plot(Tns/12., ave_T_var_Rnet, color='C4', label=r'$R_{net}$')
h2=axs[0].plot(Tns/12., ave_T_var_Qr, color='C0', label=r'$Q_o$', linewidth=2, zorder=5)
#plt.plot(Tns/12., ave_T_var_Qek, color='C1', label=r'$Q_{ek}$')
h3=axs[0].plot(Tns/12., ave_T_var_sum, color='k', label=r'$\sigma^2_T$', linewidth=2, zorder=5)
#h4=axs[0].plot(Tns/12., ave_T_var, color='C5', label=r'$\sigma_T^2$')
axs[0].axhline(0, color='k', linewidth=1)

hs=[h1,h2,h3]
#Global/tropics
#axs[0].set_ylim(-0.1,0.6)
#axs[0].set_ylim(-0.1,0.48)
axs[0].set_ylim(-0.1,0.38)
Beispiel #17
0
# `~proplot.ui.subplots`. This generates a `~proplot.axes.PolarAxes`
# instance. Its `~proplot.axes.PolarAxes.format` command permits
# polar-specific modifications like changing the central radius, the zero
# azimuth location, the radial and azimuthal limits, and the positive
# azimuthal direction. This projection can also be used to make sector plots
# and annular plots.

# %%
import proplot as plot
import numpy as np
N = 200
state = np.random.RandomState(51423)
x = np.linspace(0, 2 * np.pi, N)
y = 100 * (state.rand(N, 5) - 0.3).cumsum(axis=0) / N
plot.rc['axes.titlepad'] = '1em'  # default matplotlib offset is incorrect
fig, axs = plot.subplots([[1, 1, 2, 2], [0, 3, 3, 0]], proj='polar')
axs.format(
    suptitle='Polar axes demo',
    linewidth=1,
    ticklabelsize=9,
    rlines=0.5,
    rlim=(0, 19),
)
for i in range(5):
    xi = x + i * 2 * np.pi / 5
    axs.plot(xi, y[:, i], cycle='FlatUI', zorder=0, lw=3)

# Standard polar plot
axs[0].format(title='Normal plot',
              thetaformatter='pi',
              rlines=5,
Beispiel #18
0
# datasets with complex statistical distributions.
#
# In the below example, we create a new divering colormap and
# reconstruct the colormap from `this SciVisColor example
# <https://sciviscolor.org/media/filer_public/c7/27/c727e638-82eb-445b-bc96-e7b64c13efa2/colormoves.png>`__.
# We also save the results for future use by passing ``save=True`` to
# `~proplot.constructor.Colormap`.

# %%
import proplot as pplt
import numpy as np
state = np.random.RandomState(51423)
data = state.rand(30, 30).cumsum(axis=1)

# Generate figure
fig, axs = pplt.subplots([[0, 1, 1, 0], [2, 2, 3, 3]], refwidth=2.4, span=False)
axs.format(
    xlabel='xlabel', ylabel='ylabel',
    suptitle='Merging colormaps'
)

# Diverging colormap example
title1 = 'Diverging from sequential maps'
cmap1 = pplt.Colormap('Blues4_r', 'Reds3', name='Diverging', save=True)

# SciVisColor examples
title2 = 'SciVisColor example'
cmap2 = pplt.Colormap(
    'Greens1_r', 'Oranges1', 'Blues1_r', 'Blues6',
    ratios=(1, 3, 5, 10), name='SciVisColorUneven', save=True
)
Beispiel #19
0
def test_journal_subplots(journal):
    """Tests that subplots can be generated with journal specifications."""
    f, axs = plot.subplots(journal=journal)
Beispiel #20
0
def plot_stats(data,
               x_key,
               x_label=None,
               y_keys=None,
               y_labels=None,
               start_index=0,
               save_filename=None):
    """
    Generate time-series plots of stats specified by keys
    Args:
        data: [dict] containing data to be plotted. len of all values should be equal
            data must include x_key as a valid key
        x_key: [str] key for the x-axis (time varying component)
        x_label: [str] corresponding label for the x_key, if not provided then the key is used
        y_keys: [list of str] optional list of keys to plot, each should exist in data.keys()
            If nothing is given, data.keys() will be used
        y_labels: [list of str] optional list of labels, should be the same length as keys input
            If nothing is given, y_keys will be used
        start_index: [int] time offset for plotting data - default=0 will plot all data
        save_filename: [str] containing the complete output filename.
    Returns:
        fig: matplotlib figure handle
    """
    assert x_key in list(data.keys()), ('x_key=%s must be in data.keys()' %
                                        x_key)
    if x_label is None:
        x_label = x_key
    if y_keys is None:
        y_keys = list(data.keys())
        if 'epoch' in y_keys:
            y_keys.remove('epoch')
        if 'batch_step' in y_keys:
            y_keys.remove('batch_step')
    else:
        assert all([y_key in list(data.keys()) for y_key in y_keys])
    if y_labels is None:
        y_labels = [' '.join(y_key.split('_')) for y_key in y_keys]
    else:
        assert len(y_labels) == len(y_keys), (
            'The number of y_labels must match the number of y_keys')
    num_y_keys = len(y_keys)
    num_plots_y = int(np.ceil(np.sqrt(num_y_keys)))
    num_plots_x = int(np.ceil(np.sqrt(num_y_keys)))
    fig, axes = plot.subplots(nrows=num_plots_y,
                              ncols=num_plots_x,
                              sharex=False,
                              sharey=False)
    key_idx = 0
    for plot_id in np.ndindex((num_plots_y, num_plots_x)):
        if key_idx < num_y_keys:
            x_dat = data[x_key][start_index:]
            y_dat = data[y_keys[key_idx]][start_index:]
            if len(x_dat) == len(y_dat):
                ax = axes[plot_id]
                ax.plot(x_dat, y_dat)
                ax.format(yticks=[
                    np.minimum(0.0, np.min(y_dat)),
                    np.maximum(0.0, np.max(y_dat))
                ],
                          ylabel=y_labels[key_idx])
                key_idx += 1
            else:
                ax = clear_axis(axes[plot_id])
                print(
                    'utils/plot_functions.py: WARNING: x and y for key %s must have same first dimensions but are %g and %g'
                    % (y_keys[key_idx], len(x_dat), len(y_dat)))
        else:
            ax = clear_axis(axes[plot_id])
    axes.format(xlabel=x_label, suptitle='Stats per Batch')
    if save_filename is not None:
        fig.savefig(save_filename, transparent=True)
        plot.close(fig)
        return None
    plot.show()
    return fig
gcsmap = fs.get_mapper(pr_zarr)
dset = xr.open_zarr(gcsmap)

# %%
dset

# %% [markdown]
# ## Plot the first timestep

# %%
dset['time'][0]

# %%
fig, ax = plot.subplots(axwidth=4.5,
                        tight=True,
                        proj='robin',
                        proj_kw={'lon_0': 90},
                        figsize=(15, 10))
# format options
ax.format(
    land=False,
    coast=True,
    innerborders=True,
    borders=True,
    labels=True,
    geogridlinewidth=0,
)
map1 = ax.pcolormesh(dset['lon'],
                     dset['lat'],
                     dset['pr'][0, :, :] * 1.e3,
                     cmap='IceFire',
Beispiel #22
0
def photon_echo_t3(mol, omega1, omega2, t3, g_idx=[0], e_idx=None, f_idx=None,\
                   fname='2DES', plt_signal=False, separate=False):
    """
    2D photon echo signal scanning omega1 and omega2 at detection time t3.

    The current implementation only applies for a single ground state.

    For a manifold of g states, the ground state bleaching neglected here has to be considered.

    Parameters
    ----------
    evals : ndarray
        eigenvalues of system.
    edip : ndarray
        electric dipole matrix.
    omega1 : TYPE
        DESCRIPTION.
    omega3 : TYPE
        DESCRIPTION.
    tau2 : TYPE
        DESCRIPTION.
    g_idx : TYPE
        DESCRIPTION.
    e_idx : TYPE
        DESCRIPTION.
    gamma : TYPE
        DESCRIPTION.
    separate: bool
        separate the ladder diagrams

    Returns
    -------
    TYPE
        DESCRIPTION.

    """

    E = mol.eigvals()
    edip = mol.edip_rms

    gamma = mol.gamma
    dephasing = mol.dephasing

    if gamma is None:
        raise ValueError('Please set the decay constants gamma first.')

    N = mol.nstates

    if e_idx is None: e_idx = range(1, N)
    if f_idx is None: f_idx = range(1, N)

    # gsb = _GSB(evals, edip, omega1, omega3, t2, g_idx, e_idx, gamma)
    se = _SE(E,
             edip,
             -omega1,
             omega2,
             t3,
             g_idx,
             e_idx,
             gamma,
             dephasing=dephasing)
    esa = _ESA(E, edip, -omega1, omega2, t3, g_idx, e_idx, f_idx, \
               gamma, dephasing=dephasing)

    S = se + esa

    if plt_signal == True:

        # make plots
        fig, ax = plt.subplots(refaspect=2)

        im = ax.contourf(
            omega1 * au2ev,
            omega2 * au2ev,
            S.real / abs(S).max(),  #interpolation='bilinear',
            cmap=cm.RdBu,
            lw=0.6,
            origin='lower')  #-abs(SPE).max())

        ax.set_xlabel(r'$-\Omega_1$ (eV)')
        ax.set_ylabel(r'$\Omega_2$ (eV)')

    if separate:
        np.savez(fname, omega1, omega2, se, esa)
        return se, esa
    else:
        np.savez(fname, omega1, omega2, S)
        return S
Beispiel #23
0
def benchmark(name, dir_, ncols=3, ymin=0.1, ymax=50, server='uriah'):
    """
    Plots benchmark result summaries.
    """
    cats, nlats, sizes, tables, fname = runtimes(name, dir_, server=server)
    plot.rc.cycle = 'colorblind10'
    server = {
        'uriah': 'macbook',
        'cheyenne4': 'supercomputer',
        'monde': 'server'
    }.get(server, server)
    f, axs = plot.subplots(axwidth=2.5,
                           ncols=2,
                           aspect=(2, 3),
                           legend='b',
                           span=False,
                           share=1)
    nxarray = len([cat for cat in cats if 'xarray' in cat.lower()])
    xcolors = plot.colors('greys', nxarray, left=0.3)
    ocolors = [
        color for i, color in enumerate(plot.colors('colorblind10'))
        if i not in (5, 7)
    ]
    idxs = np.argsort(cats)  # use alphabetical order
    for ax, scale in zip(axs, ('linear', 'log')):
        hs = []
        ic, xc = 0, 0  # make xarray lines different shades of same color
        for i in idxs:
            cat = cats[i]
            if 'xarray' in cat.lower():
                color = xcolors[xc]
                xc += 1
            else:
                # color = f'C{ic}'
                color = ocolors[ic]
                ic += 1
            times = [table[i][3]
                     for table in tables]  # 4th cell contains 'real' time
            hs += ax.plot(sizes,
                          times,
                          color=color,
                          marker='o',
                          markersize=6,
                          label=cat,
                          lw=1)
            # hs += [ax.scatter(sizes, times, color=[color], label=cat)]
        ax.format(
            xlabel='file size (MB)',
            ylabel='time (seconds)',
            gridminor=True,
            # ax.format(xlabel='latitude count', ylabel='time (seconds)',
            ylim=(0, ymax) if scale == 'linear' else (ymin, ymax),
            yscale=scale,
            yformatter='scalar',
            xlim=(min(sizes), max(sizes)),
            xscale=scale,
            xformatter='scalar',
            title=f'{scale.title()} scale',
            suptitle=f'{name.title()} benchmark on {server}')
    f.bpanel.legend(hs, ncols=ncols, order='F')
    f.save(fname)
    return f
Beispiel #24
0
def npbytes_to_str(var):
    return (bytes(var).decode("utf-8"))


# read data
ds = xr.open_dataset('../output_files/wrfchemi_00z_d01')
# take 06 UTC and 24 MOZCART species as an example
t = 6
# get info of time
Times = ds['Times']
time_str = datetime.strptime("".join(npbytes_to_str(Times[t].values)),
                             "%Y-%m-%d_%H:%M:%S").strftime("%Y-%m-%d_%H:%M:%S")
# get keys except "Times"
species = ds.drop_vars('Times')

# plot
f, axs = plot.subplots(tight=True, share=0,
                       nrows=6, ncols=4,
                       )

axs.format(suptitle=time_str+' nearest')
for index, key in enumerate(species):
    m = axs[index].pcolormesh(ds[key][t, 0, ...], levels=256, cmap='Fire')
    axs[index].format(title=ds[key].attrs['description'])
    axs[index].colorbar(m, loc='r',
                        label=ds[key].attrs['units'],
                        tickminor=False)

f.savefig('../emission_example.png')
Beispiel #25
0
    # dip[3, 3] = 1.
    # dip[0, 3] = dip[3,0] = [0.5, 1, 0]

    mol = Mol(H, dip)
    mol.set_decay(gamma)

    return mol


if __name__ == '__main__':

    from lime.units import au2fs
    from lime.style import subplots

    fig, ax = plt.subplots(figsize=(4.2, 3.2))
    E = np.array([0., 0.5, 1.1, 1.3]) / au2ev
    gamma = [0, 0.002, 0.002, 0.002]
    H = np.diag(E)

    from lime.mol import Mol
    from lime.optics import Biphoton

    from matplotlib import cm

    dip = np.zeros((len(E), len(E)))
    dip[1, 2] = dip[2, 1] = 1.
    dip[1, 3] = dip[3, 1] = 1.

    dip[0, 1] = dip[1, 0] = 1.
    dip[0, 3] = dip[3, 0] = 1
Beispiel #26
0
# %%
import proplot as pplt
import numpy as np
import pandas as pd

# Cycle that loops through 'dashes' Line2D property
cycle = pplt.Cycle(lw=3, dashes=[(1, 0.5), (1, 1.5), (3, 0.5), (3, 1.5)])

# Sample data
state = np.random.RandomState(51423)
data = (state.rand(20, 4) - 0.5).cumsum(axis=0)
data = pd.DataFrame(data, columns=pd.Index(['a', 'b', 'c', 'd'], name='label'))

# Plot data
fig, ax = pplt.subplots(refwidth=2.5, suptitle='Plot without color cycle')
obj = ax.plot(data,
              cycle=cycle,
              legend='ll',
              legend_kw={
                  'ncols': 2,
                  'handlelength': 2.5
              })

# %% [raw] raw_mimetype="text/restructuredtext"
# .. _ug_cycles_dl:
#
# Downloading color cycles
# ------------------------
#
# There are several interactive online tools for generating perceptually
Beispiel #27
0
def absorption(mol,
               omegas,
               plt_signal=False,
               fname=None,
               normalize=False,
               scale=1.,
               yscale=None):
    '''
    SOS for linear absorption signal S = 2 pi |mu_{fg}|^2 delta(omega - omega_{fg}).
    The delta function is replaced with a Lorentzian function.

    Parameters
    ----------
    omegas : 1d array
        detection frequency window for the signal
    H : 2D array
        Hamiltonian
    edip : 2d array
        electric dipole moment
    output : TYPE, optional
        DESCRIPTION. The default is None.
    gamma : float, optional
        Lifetime broadening. The default is 1./au2ev.
    normalize : TYPE, optional
        Normalize the maximum intensity of the signal as 1. The default is False.

    Returns
    -------
    signal : 1d array
        linear absorption signal at omegas

    '''

    edip = mol.edip_rms

    gamma = mol.gamma
    eigenergies = mol.eigvals()

    # set the ground state energy to 0
    eigenergies = eigenergies - eigenergies[0]

    # assume the initial state is from the ground state 0
    signal = 0.0
    for j in range(1, mol.nstates):
        e = eigenergies[j]
        signal += abs(edip[j, 0])**2 * lorentzian(omegas - e, gamma[j])

    if normalize:
        signal /= max(signal)

    if plt_signal:

        fig, ax = plt.subplots(figsize=(4, 3))

        ax.plot(omegas * au2ev, signal)

        for j, e in enumerate(eigenergies):
            ax.axvline(e * au2ev, 0., abs(edip[0, j])**2 * scale, color='grey')

        ax.set_xlim(min(omegas) * au2ev, max(omegas) * au2ev)
        ax.set_xlabel('Energy (eV)')
        ax.set_ylabel('Absorption')
        if yscale:
            ax.set_yscale(yscale)

        # ax.set_ylim(0, 1)

        # fig.subplots_adjust(wspace=0, hspace=0, bottom=0.15, \
        # left=0.17, top=0.96, right=0.96)

        if fname is not None:
            fig.savefig(fname, dpi=1200, transparent=True)

        return signal, fig, ax
    else:
        return signal
Beispiel #28
0
# it every time ProPlot is imported, simply pass ``save=True`` to
# `~proplot.constructor.Cycle`. If you want to change the global property
# cycler, pass a *name* to the :rcraw:`cycle` setting or pass the result of
# `~proplot.constructor.Cycle` to the :rcraw:`axes.prop_cycle` setting (see
# the :ref:`configuration guide <ug_config>`).

# %%
import numpy as np
lw = 5
state = np.random.RandomState(51423)
data = (state.rand(12, 6) - 0.45).cumsum(axis=0)
kwargs = {'legend': 'b', 'labels': list('abcdef')}

# Modify the default color cycle
plot.rc.cycle = '538'
fig, axs = plot.subplots(ncols=3, axwidth=1.9)
axs.format(suptitle='Changing the color cycle')
ax = axs[0]
ax.plot(data, lw=lw, **kwargs)
ax.format(title='Global color cycle')

# Pass the cycle to a plotting command
ax = axs[1]
ax.plot(data, cycle='qual1', lw=lw, **kwargs)
ax.format(title='Local color cycle')

# As above but draw each line individually
# Note that the color cycle is not reset with each plot call
ax = axs[2]
labels = kwargs['labels']
for i in range(data.shape[1]):
Beispiel #29
0
def photon_echo(mol, pump, probe, t2=0., g_idx=[0], e_idx=None, f_idx=None, fname='signal', \
                plt_signal=False, pol=None):
    """
    Photon echo signal for a multi-level system using SOS expression.

    Approximations:
        1. decay are included phenomelogically
        2. no population relaxation

    Parameters
    ----------
    mol : TYPE
        DESCRIPTION.
    pump : TYPE
        Omega1, conjugate variable of t1
    probe : TYPE
        Omega3, conjugate variable of t3
    t2 : TYPE
        population time.
    g_idx : TYPE
        DESCRIPTION.
    e_idx : TYPE
        DESCRIPTION.
    f_idx : TYPE
        DESCRIPTION.
    gamma : float
        decay rates for excited states.

    Raises
    ------
    ValueError
        DESCRIPTION.

    Returns
    -------
    S : TYPE
        DESCRIPTION.

    """

    E = mol.eigvals()
    dip = mol.edip_rms

    gamma = mol.gamma

    if gamma is None:
        raise ValueError('Please set the decay constants gamma first.')

    N = mol.nstates

    if e_idx is None: e_idx = range(N)
    if f_idx is None: f_idx = range(N)

    # compute the signal
    S = _photon_echo(E, dip, omega1=-pump, omega3=probe, t2=t2, g_idx=g_idx, e_idx=e_idx, f_idx=f_idx,\
              gamma=gamma)

    np.savez(fname, pump, probe, S)

    if plt_signal == True:

        # make plots
        fig, ax = plt.subplots()

        omega_min = min(pump) * au2ev
        omega_max = max(pump) * au2ev

        im = ax.contour(
            S.real.T / abs(S).max(),  #interpolation='bilinear',
            cmap=cm.RdBu,
            origin='lower',
            extent=[omega_min, omega_max, omega_min, omega_max],
            vmax=1,
            vmin=-1)  #-abs(SPE).max())

        ax.plot(pump * au2ev, probe * au2ev, '--', lw=1, color='grey')
        # ax.axhline(y=1.1, color='w', linestyle='--', linewidth=0.5, alpha=0.5)
        # ax.axhline(y=0.9, color='w', linestyle='--', linewidth=0.5, alpha=0.5)
        #
        # ax.axvline(x=1.1, color='w', linestyle='--', linewidth=0.5, alpha=0.5)
        # ax.axvline(x=0.9, color='w', linestyle='--', linewidth=0.5, alpha=0.5)
        #im = ax.contour(SPE,
        #               origin='lower', extent=[0.8, omega_max, omega_min, omega_max],
        #               vmax=1, vmin=0) #-abs(SPE).max())

        ax.set_xlabel(r'$-\Omega_1$ (eV)')
        ax.set_ylabel(r'$\Omega_3$ (eV)')
        #ax.set_title(r'$T_2 = $' + str(t2))

        # plt.colorbar(im)

        # fig.subplots_adjust(hspace=0.0,wspace=0.0,bottom=0.14,left=0.0,top=0.95,right=0.98)

    return S
Beispiel #30
0
# cycle is used to style the input data. ProPlot iterates through property
# cycle properties when (1) making multiple calls to a plotting command, or (2)
# plotting successive columns of 2-dimensional input data. For more information
# on property cycles, see the :ref:`color cycles section <ug_cycles>` and `this
# matplotlib tutorial
# <https://matplotlib.org/tutorials/intermediate/color_cycle.html#sphx-glr-tutorials-intermediate-color-cycle-py>`__.

# %%
import proplot as plot
import numpy as np

state = np.random.RandomState(51423)
data1 = state.rand(6, 4)
data2 = state.rand(6, 4) * 1.5
with plot.rc.context({'lines.linewidth': 3}):
    fig, axs = plot.subplots(ncols=2)
    axs.format(xlabel='xlabel',
               ylabel='ylabel',
               suptitle='Local property cycles demo')

    # Property cycles specific to datasets
    axs[0].plot(data1, cycle='Reds', cycle_kw={'left': 0.3})
    axs[0].plot(data2, cycle='Blues', cycle_kw={'left': 0.3})
    axs[1].plot(data1 * data2,
                cycle='black',
                cycle_kw={'linestyle': ('-', '--', '-.', ':')})

# %% [raw] raw_mimetype="text/restructuredtext"
# .. _ug_1dstd:
#
# Standardized arguments