Beispiel #1
0
def grid(fields,
         title='body spectra',
         logZ=False,
         show=True,
         nstd=1,
         vlim=(None, None),
         cmap='inferno'):
    """
    General purpose plotter for multi-dimensional input tensors from 2D up to 6D. The tensor will be converted to 4D
    and plot as a grid of 2D images

    :param fields:
    :param title:
    :param logZ:
    :param show:
    :return:
    """
    if cmap == 'sunlight':
        cmap = sunlight
    fields = np.array(fields)  # just in case its a list
    assert fields.ndim > 2
    if np.iscomplexobj(fields.flat[0]):
        fields = np.abs(fields)**2  # convert to intensity if complex
    while len(fields.shape) > 4:
        try:
            boring_ind = fields.shape.index(1)
            fields = np.mean(fields, axis=boring_ind)
        except ValueError:
            fields = fields[0]  # if none are zero slice out first dimension
    while len(fields.shape) < 4:
        fields = fields[:, np.newaxis]

    slices = np.int_(np.ceil(np.array(fields.shape)[:2] / 5))
    fields = fields[::slices[0], ::slices[1]]
    print(
        f'fields being sliced by {slices} making new fields size {fields.shape}'
    )
    nwave, nobj, x, y = fields.shape

    try:
        std = np.std(fields)
        mean = np.mean(fields)
    except ValueError:
        std = np.std(fields[0])
        mean = np.mean(fields[0])

    if vlim == (None, None):
        vmin, vmax = mean - nstd * std, mean + nstd * std
    else:
        vmin, vmax = vlim

    fig = plt.figure(figsize=(16, 9))
    fig.suptitle(title)
    norm = None if not logZ else (LogNorm() if vmin > 0 else SymLogNorm(1e-7))

    imgrid = ImageGrid(
        fig,
        111,  # as in plt.subplot(111)
        nrows_ncols=(nobj, nwave),
        axes_pad=0.15,
        share_all=True,
        cbar_location="right",
        cbar_mode="single",
        cbar_size="7%",
        cbar_pad=0.15,
    )
    for i, ax in enumerate(imgrid):
        x, y = i % nwave, i // nwave
        im = ax.imshow(fields[x, y],
                       norm=norm,
                       vmin=vmin,
                       vmax=vmax,
                       cmap=cmap)

    ax.cax.colorbar(im)
    ax.cax.toggle_label(True)

    plt.tight_layout()
    plt.subplots_adjust(right=0.9)

    if show:
        plt.show(block=True)
Beispiel #2
0
def view_timeseries(img_tseries,
                    cdi,
                    title=None,
                    logZ=False,
                    vlim=(None, None),
                    dx=None,
                    subplt_cols=3,
                    box={
                        'use': False,
                        'threshold': 1e-7
                    }):
    """
    view white light images in the timeseries

    :param img_tseries: intensity timeseries [n_tsteps, nx,ny]
    :param cdi: struct that contains the CDI params (from CDI.py)
    :param title: string, must be set or will error!
    :param logZ: turn logscale plotting for Z-axis on or off
    :param use_axis: turn on/off using axis ticks, colorbar, etc
    :param vlim: tuple of colorbar axis limits (min,max)
    :param subplt_cols: number of subplots per row
    :param dx: sampling of the image in m. Hardcoded to convert to um
    :param box: if True, draw box around CDI region
    :return:
    """
    # Recreate CDI phase stream for plot titles
    if cdi.use_cdi:
        phases = cdi.phase_series

    # Create figure & adjust subplot number, layout, size, whitespace
    n_tsteps = len(img_tseries)
    n_rows = int(np.ceil(n_tsteps / float(subplt_cols)))

    fig, subplot = plt.subplots(n_rows, subplt_cols, figsize=(12, 10))
    fig.subplots_adjust(
        bottom=0.1,
        top=0.85,
        left=0.01,
        hspace=.4,
        wspace=0.02,
        right=0.9,
    )  #  wspace=0.2, right=0.95, left=0.05,

    # Title
    if title is None:
        warnings.warn("Plots without titles: Don't Do It!")
        title = input("Please Enter Title: ")
        pass
    fig.suptitle(title, fontweight='bold', fontsize=16)

    for ax, t in zip(subplot.flatten(),
                     range(n_rows * subplt_cols)):  # range(n_tsteps)
        if t > n_tsteps - 1:
            ax.axis('off')  # hides axis
            pass
        else:
            # Axis (Subplot) title
            if cdi.use_cdi and not np.isnan(phases[t]):
                ax.set_title(f"probe  "
                             r'$\theta$' + f"={phases[t] / np.pi:.2f}" +
                             r'$\pi$')
            else:
                ax.set_title(f"t={t * sp.sample_time}")

            if logZ:
                if vlim[0] is not None and vlim[0] <= 0:
                    im = ax.imshow(img_tseries[t],
                                   interpolation='none',
                                   origin='lower',
                                   vmin=vlim[0],
                                   vmax=vlim[1],
                                   norm=SymLogNorm(linthresh=1e-5),
                                   cmap="YlGnBu_r")
                    clabel = "Log Normalized Intensity"
                else:
                    im = ax.imshow(img_tseries[t],
                                   interpolation='none',
                                   origin='lower',
                                   vmin=vlim[0],
                                   vmax=vlim[1],
                                   norm=LogNorm(),
                                   cmap="YlGnBu_r")
                    clabel = "Log Normalized Intensity"
            else:
                im = ax.imshow(img_tseries[t],
                               interpolation='none',
                               origin='lower',
                               vmin=vlim[0],
                               vmax=vlim[1],
                               cmap="YlGnBu_r")
                clabel = "Normalized Intensity"

            # XY axis Labels
            tic_spacing, tic_labels, xylabel = scale_lD(dx, tp.fn_fp)
            ax.set_xticks(tic_spacing)
            ax.set_xticklabels(tic_labels)
            ax.set_yticks(tic_spacing)
            ax.set_yticklabels(tic_labels)
            ax.set_xlabel(xylabel)

            if box['use']:
                from medis.CDI import get_fp_mask
                fp_mask, edges, _, _, _, _ = get_fp_mask(
                    cdi, thresh=box['threshold'])
                cl = LineCollection(edges, colors='r')
                ax.add_collection(cl)

        warnings.simplefilter("ignore", category=UserWarning)
        cbar_ax = fig.add_axes([
            0.86, 0.1, 0.04, 0.8
        ])  # Add axes for colorbar @ position [left,bottom,width,height]
        cb = fig.colorbar(im, cax=cbar_ax, orientation='vertical')  #
        cb.set_label(clabel, fontsize=14)
        cb.ax.tick_params(labelsize=10)
Beispiel #3
0
print('Visualizing J(theta0, theta1) ...')

# 依照定义间隔生成均匀分布的数值
theta0_vals = np.linspace(start=-10, stop=10, num=100)
theta1_vals = np.linspace(start=-1, stop=4, num=100)

xs, ys = np.meshgrid(theta0_vals, theta1_vals)
J_vals = np.zeros(xs.shape)

# Fill out J_vals
for i in range(0, theta0_vals.size):
    for j in range(0, theta1_vals.size):
        t = np.array([theta0_vals[i], theta1_vals[j]])
        J_vals[i][j] = compute_cost(X, y, t)

J_vals = np.transpose(J_vals)

fig1 = plt.figure(2)
ax = fig1.gca(projection='3d')
ax.plot_surface(xs, ys, J_vals)
plt.xlabel(r'$\theta_0$')
plt.ylabel(r'$\theta_1$')

plt.figure(3)
# logspace 创建等比数列
lvls = np.logspace(start=-2, stop=3, num=20)
plt.contour(xs, ys, J_vals, levels=lvls, norm=LogNorm())
plt.plot(theta[0], theta[1], c='r', marker="x")

input('ex1 Finished. Press ENTER to exit')
Beispiel #4
0
def showStitchedModels_Redundant(mods,
                                 ax=None,
                                 cmin=None,
                                 cmax=None,
                                 **kwargs):
    """Show several 1d block models as (stitched) section."""
    x = kwargs.pop('x', np.arange(len(mods)))
    topo = kwargs.pop('topo', x * 0)

    nlay = int(np.floor((len(mods[0]) - 1) / 2.)) + 1
    if cmin is None or cmax is None:
        cmin = 1e9
        cmax = 1e-9
        for model in mods:
            res = np.asarray(model)[nlay - 1:nlay * 2 - 1]
            cmin = min(cmin, min(res))
            cmax = max(cmax, max(res))

    if kwargs.pop('sameSize', True):  # all having the same width
        dx = np.ones_like(x) * np.median(np.diff(x))
    else:
        dx = np.diff(x) * 1.05
        dx = np.hstack((dx, dx[-1]))

    x1 = x - dx / 2
    if ax is None:
        fig, ax = plt.subplots()
    else:
        ax = ax
        fig = ax.figure

#    ax.plot(x, x * 0., 'k.')
    zm = kwargs.pop('zm', None)
    maxz = 0.
    if zm is not None:
        maxz = zm
    recs = []
    RES = []
    for i, mod in enumerate(mods):
        mod1 = np.asarray(mod)
        res = mod1[nlay - 1:]
        RES.extend(res)

        thk = mod1[:nlay - 1]
        thk = np.hstack((thk, thk[-1]))
        z = np.hstack((0., np.cumsum(thk)))
        if zm is not None:
            thk[-1] = zm - z[-2]
            z[-1] = zm
        else:
            maxz = max(maxz, z[-1])

        for j, _ in enumerate(thk):
            recs.append(Rectangle((x1[i], topo[i] - z[j]), dx[i], -thk[j]))

    pp = PatchCollection(recs, edgecolors=kwargs.pop('edgecolors', 'none'))
    pp.set_edgecolor(kwargs.pop('edgecolors', 'none'))
    pp.set_linewidths(0.0)
    ax.add_collection(pp)
    if 'cmap' in kwargs:
        pp.set_cmap(kwargs['cmap'])

    print(cmin, cmax)
    norm = LogNorm(cmin, cmax)
    pp.set_norm(norm)
    pp.set_array(np.array(RES))
    #    pp.set_clim(cmin, cmax)
    ax.set_ylim((-maxz, max(topo)))
    ax.set_xlim((x1[0], x1[-1] + dx[-1]))

    cbar = None
    if kwargs.pop('colorBar', True):
        cbar = plt.colorbar(pp,
                            ax=ax,
                            norm=norm,
                            orientation='horizontal',
                            aspect=60)  # , ticks=[1, 3, 10, 30, 100, 300])
        if 'ticks' in kwargs:
            cbar.set_ticks(kwargs['ticks'])


#        cbar.autoscale_None()
    if ax is None:  # newly created fig+ax
        return fig, ax
    else:  # already given, better give back color bar
        return cbar
Beispiel #5
0
plt.savefig('figures/hist_constraint_returns.eps')
plt.show()

################################################################################
################################################################################
#plot volatility from different learning rates

with open(path + 'fs_simplified_compare_learning', 'rb') as f:
    results_g1, results_g2, results_g3 = pickle.load(f)

#plot heat maps
plt.hist2d(np.zeros(10000) + 0.1,
           np.array(results_g1['vol']),
           range=[[0.05, 0.35], [0, 0.055]],
           bins=[9, 100],
           norm=LogNorm())
plt.hist2d(np.zeros(10000) + 0.2,
           np.array(results_g2['vol']),
           range=[[0.05, 0.35], [0, 0.055]],
           bins=[9, 100],
           norm=LogNorm())
plt.hist2d(np.zeros(10000) + 0.3,
           np.array(results_g3['vol']),
           range=[[0.05, 0.35], [0, 0.055]],
           bins=[9, 100],
           norm=LogNorm())

#plot percentiles
pct = 70
pct1 = [
    np.percentile(results_g1['vol'], pct),
Beispiel #6
0
z = 0  # z position [kpc] of slice to plot
N = 401  # samples per direction
samples = linspace(-20, 20, N, endpoint=True)

B = zeros((N, N))
X, Y = meshgrid(samples, samples)

for i, x in enumerate(samples):
    for j, y in enumerate(samples):
        pos = Vector3d(x, y, z) * kpc
        B[i, j] = bField.getField(pos).getR() / gauss  # B in [G]

figure()
maB = ma.masked_array(B, B == 0)
pc = imshow(maB,
            norm=LogNorm(),
            extent=(-20, 20, -20, 20),
            vmin=1e-9,
            vmax=1e-4)
gca().set_aspect(1)
cbar = colorbar(pc, shrink=0.8)
cbar.set_label(r'$\vert \vec{B} \vert$ [G]')
plot(-8.5, 0, 'wo')
xlabel('x [kpc]')
ylabel('y [kpc]')
xlim(-20, 20)
ylim(-20, 20)
savefig('PT11_%s.png' % field, bbox_inches='tight')

show()
Beispiel #7
0
control=control_bc[n,0,:,:]
nobb=nobb_bc[n,0,:,:]
noaf=noaf_bc[n,0,:,:]

print(control.shape)
print(nobb.shape)
print(noaf.shape)

fig,(ax1, ax2, ax3)= plt.subplots(1,3,figsize=(12,3))
X,Y=np.meshgrid(lon,lat)
m1=rp.get_basemap(lllon=-70, urlon=0., lllat=-15., urlat=30.,ax=ax1)
m2=rp.get_basemap(lllon=-70, urlon=0., lllat=-15., urlat=30.,ax=ax2)
m3=rp.get_basemap(lllon=-70, urlon=0., lllat=-15., urlat=30.,ax=ax3)

Max=np.nanmax(control)
im=ax1.pcolormesh(X,Y, control,  cmap=cmap, vmax=Max, norm=LogNorm())#, vmin=vmin,norm=norm)
im=ax2.pcolormesh(X,Y, noaf,  cmap=cmap, vmax=Max, norm=LogNorm())#, vmin=-4000., vmax=4000)#vmin,norm=norm)
im=ax3.pcolormesh(X,Y, nobb,  cmap=cmap, vmax=Max, norm=LogNorm())#vmin=-100., vmax=100.)#, vmin=vmin,norm=norm)

ax1.set_title('Control GC_BC')
ax2.set_title('No African BB')
ax3.set_title('No BB')

cbar_ax = fig.add_axes([0.1, 0.1, 0.65, 0.07])
fig.colorbar(im, cax=cbar_ax, orientation='horizontal')

plt.suptitle('SpeciesConc_CO  %s' %date)

plt.savefig('/users/mjr583/GC/interhemispheric_mixing/plots/SpeciesConc_map_%s_%s.png' %(out, date)) 
plt.close()
"""
Launch the stream and the original spectrogram
"""
stream, pa = mic_read.open_mic()
data = get_sample(stream, pa)
arr2D, freqs, bins = get_specgram(data, rate)
"""
Setup the plot paramters
"""
extent = (bins[0], bins[-1] * SAMPLES_PER_FRAME, freqs[-1], freqs[0])
im = plt.imshow(arr2D,
                aspect='auto',
                extent=extent,
                interpolation="none",
                cmap='jet',
                norm=LogNorm(vmin=.01, vmax=1))
plt.xlabel('Time (s)')
plt.ylabel('Frequency (Hz)')
plt.title('Real Time Spectogram')
plt.gca().invert_yaxis()
##plt.colorbar() #enable if you want to display a color bar

############### Animate ###############
anim = animation.FuncAnimation(fig,
                               update_fig,
                               blit=False,
                               interval=mic_read.CHUNK_SIZE / 1000)
try:
    plt.show()
except:
    print("Plot Closed")
Beispiel #9
0
            else:
                Npix[j] = n_1(fluxlimit_1d[j]) +n_2(f_b)



        N = np.abs(Npix)
        N_source = pixel_angle_deg*N # Number of sources per sqiare arcsecond
        N_norm = N_source / np.max(N_source) # Normalize

        # Construct weight map to gerenate random image:
        weight_map = np.reshape(N_norm,(-1,len(image_data[0])))

        plt.style.use('default')
        plt.figure(figsize = [8, 8])
        plt.imshow(weight_map,cmap = 'gray', interpolation = 'none', origin = 'lower', norm = LogNorm())
        plt.title('Field '+field[target][0]+ ': Normalized sources per pixel')
        plt.savefig(path2+'/expmap.png')
        plt.close()
        print("Exposure map " + str(i+1) + " created..." )



        # Begin making random image:
        weight_tot = np.sum(N_norm)
        weight_outer = np.cumsum(N_norm) # 'Outer edge' of pixel weight
        weight_inner = weight_outer - N_norm # 'Inner edge' of pixel weight


        n_sources = int(np.sum(N_source))
Beispiel #10
0
def saddleplot(
    binedges,
    counts,
    saddledata,
    cmap="coolwarm",
    scale="log",
    vmin=0.5,
    vmax=2,
    color=None,
    title=None,
    xlabel=None,
    ylabel=None,
    clabel=None,
    fig=None,
    fig_kws=None,
    heatmap_kws=None,
    margin_kws=None,
    cbar_kws=None,
    subplot_spec=None,
):
    """
    Generate a saddle plot.

    Parameters
    ----------
    binedges : 1D array-like
        For `n` bins, there should be `n + 1` bin edges
    counts : 1D array-like
        Signal track histogram produced by `digitize_track`. It will include
        2 flanking elements for outlier values, thus the length should be
        `n + 2`.
    saddledata : 2D array-like
        Saddle matrix produced by `make_saddle`. It will include 2 flanking
        rows/columns for outlier signal values, thus the shape should be
        `(n+2, n+2)`.
    cmap : str or matplotlib colormap
        Colormap to use for plotting the saddle heatmap
    scale : str
        Color scaling to use for plotting the saddle heatmap: log or linear
    vmin, vmax : float
        Value limits for coloring the saddle heatmap
    color : matplotlib color value
        Face color for margin bar plots
    fig : matplotlib Figure, optional
        Specified figure to plot on. A new figure is created if none is
        provided.
    fig_kws : dict, optional
        Passed on to `plt.Figure()`
    heatmap_kws : dict, optional
        Passed on to `ax.imshow()`
    margin_kws : dict, optional
        Passed on to `ax.bar()` and `ax.barh()`
    cbar_kws : dict, optional
        Passed on to `plt.colorbar()`
    subplot_spec : GridSpec object
        Specify a subregion of a figure to using a GridSpec.

    Returns
    -------
    Dictionary of axes objects.

    """
    from matplotlib.gridspec import GridSpec, GridSpecFromSubplotSpec
    from matplotlib.colors import Normalize, LogNorm
    from matplotlib import ticker
    import matplotlib.pyplot as plt

    class MinOneMaxFormatter(ticker.LogFormatter):
        def set_locs(self, locs=None):
            self._sublabels = set([vmin % 10 * 10, vmax % 10, 1])

        def __call__(self, x, pos=None):
            if x not in [vmin, 1, vmax]:
                return ""
            else:
                return "{x:g}".format(x=x)

    n_edges = len(binedges)
    n_bins = n_edges - 1
    lo, hi = binedges[0], binedges[-1]

    # Histogram and saddledata are flanked by outlier bins
    n = saddledata.shape[0]
    X, Y = np.meshgrid(binedges, binedges)
    C = saddledata
    hist = counts
    if (n - n_bins) == 2:
        C = C[1:-1, 1:-1]
        hist = hist[1:-1]

    # Layout
    if subplot_spec is not None:
        GridSpec = partial(GridSpecFromSubplotSpec, subplot_spec=subplot_spec)
    grid = {}
    gs = GridSpec(
        nrows=3,
        ncols=3,
        width_ratios=[0.2, 1, 0.1],
        height_ratios=[0.2, 1, 0.1],
        wspace=0.05,
        hspace=0.05,
    )

    # Figure
    if fig is None:
        fig_kws_default = dict(figsize=(5, 5))
        fig_kws = merge(fig_kws_default,
                        fig_kws if fig_kws is not None else {})
        fig = plt.figure(**fig_kws)

    # Heatmap
    if scale == "log":
        norm = LogNorm(vmin=vmin, vmax=vmax)
    elif scale == "linear":
        norm = Normalize(vmin=vmin, vmax=vmax)
    else:
        raise ValueError("Only linear and log color scaling is supported")

    grid["ax_heatmap"] = ax = plt.subplot(gs[4])
    heatmap_kws_default = dict(cmap="coolwarm", rasterized=True)
    heatmap_kws = merge(heatmap_kws_default,
                        heatmap_kws if heatmap_kws is not None else {})
    img = ax.pcolormesh(X, Y, C, norm=norm, **heatmap_kws)
    plt.gca().yaxis.set_visible(False)

    # Margins
    margin_kws_default = dict(edgecolor="k", facecolor=color, linewidth=1)
    margin_kws = merge(margin_kws_default,
                       margin_kws if margin_kws is not None else {})
    # left margin hist
    grid["ax_margin_y"] = plt.subplot(gs[3], sharey=grid["ax_heatmap"])
    plt.barh(binedges[:-1],
             height=np.diff(binedges),
             width=hist,
             align="edge",
             **margin_kws)
    plt.xlim(plt.xlim()[1], plt.xlim()[0])  # fliplr
    plt.ylim(hi, lo)
    plt.gca().spines["top"].set_visible(False)
    plt.gca().spines["bottom"].set_visible(False)
    plt.gca().spines["left"].set_visible(False)
    plt.gca().xaxis.set_visible(False)
    # top margin hist
    grid["ax_margin_x"] = plt.subplot(gs[1], sharex=grid["ax_heatmap"])
    plt.bar(binedges[:-1],
            width=np.diff(binedges),
            height=hist,
            align="edge",
            **margin_kws)
    plt.xlim(lo, hi)
    # plt.ylim(plt.ylim())  # correct
    plt.gca().spines["top"].set_visible(False)
    plt.gca().spines["right"].set_visible(False)
    plt.gca().spines["left"].set_visible(False)
    plt.gca().xaxis.set_visible(False)
    plt.gca().yaxis.set_visible(False)

    # Colorbar
    grid["ax_cbar"] = plt.subplot(gs[5])
    cbar_kws_default = dict(fraction=0.8, label=clabel or "")
    cbar_kws = merge(cbar_kws_default,
                     cbar_kws if cbar_kws is not None else {})
    if scale == "linear" and vmin is not None and vmax is not None:
        grid["cbar"] = cb = plt.colorbar(img, **cbar_kws)
        # cb.set_ticks(np.arange(vmin, vmax + 0.001, 0.5))
        # # do linspace between vmin and vmax of 5 segments and trunc to 1 decimal:
        decimal = 10
        nsegments = 5
        cd_ticks = np.trunc(
            np.linspace(vmin, vmax, nsegments) * decimal) / decimal
        cb.set_ticks(cd_ticks)
    else:
        grid["cbar"] = cb = plt.colorbar(img,
                                         format=MinOneMaxFormatter(),
                                         **cbar_kws)
        cb.ax.yaxis.set_minor_formatter(MinOneMaxFormatter())

    # extra settings
    grid["ax_heatmap"].set_xlim(lo, hi)
    grid["ax_heatmap"].set_ylim(hi, lo)
    plt.grid(False)
    plt.axis("off")
    if title is not None:
        grid["ax_margin_x"].set_title(title)
    if xlabel is not None:
        grid["ax_heatmap"].set_xlabel(xlabel)
    if ylabel is not None:
        grid["ax_margin_y"].set_ylabel(ylabel)

    return grid
Beispiel #11
0
def fieldplot(fig, ax, x, m, WL, comment='', WL_units=' ', crossplane='XZ',
              field_to_plot='Pabs', npts=101, factor=2.1, flow_total=11,
              is_flow_extend=True, pl=-1, outline_width=1, subplot_label=' '):
    Ec, Hc, P, coordX, coordZ = GetField(crossplane, npts, factor, x, m, pl)
    Er = np.absolute(Ec)
    Hr = np.absolute(Hc)
    try:
        from matplotlib import cm
        from matplotlib.colors import LogNorm
        if field_to_plot == 'Pabs':
            Eabs_data = np.resize(P, (npts, npts)).T
            label = r'$\operatorname{Re}(E \times H)$'
        elif field_to_plot == 'Eabs':
            Eabs = np.sqrt(Er[:, 0]**2 + Er[:, 1]**2 + Er[:, 2]**2)
            Eabs_data = np.resize(Eabs, (npts, npts)).T
            label = r'$|E|$'
        elif field_to_plot == 'Habs':
            Habs = np.sqrt(Hr[:, 0]**2 + Hr[:, 1]**2 + Hr[:, 2]**2)
            Eabs_data = np.resize(Habs, (npts, npts)).T
            label = r'$|H|$'
        elif field_to_plot == 'angleEx':
            Eangle = np.angle(Ec[:, 0]) / np.pi * 180
            Eabs_data = np.resize(Eangle, (npts, npts)).T
            label = r'$arg(E_x)$'
        elif field_to_plot == 'angleHy':
            Hangle = np.angle(Hc[:, 1]) / np.pi * 180
            Eabs_data = np.resize(Hangle, (npts, npts)).T
            label = r'$arg(H_y)$'

        # Rescale to better show the axes
        scale_x = np.linspace(
            min(coordX) * WL / 2.0 / np.pi, max(coordX) * WL / 2.0 / np.pi, npts)
        scale_z = np.linspace(
            min(coordZ) * WL / 2.0 / np.pi, max(coordZ) * WL / 2.0 / np.pi, npts)

        # Define scale ticks
        min_tick = np.amin(Eabs_data[~np.isnan(Eabs_data)])
        #min_tick = 0.1
        max_tick = np.amax(Eabs_data[~np.isnan(Eabs_data)])
        #max_tick = 60
        #scale_ticks = np.linspace(min_tick, max_tick, 5)
        scale_ticks = np.power(10.0, np.linspace(np.log10(min_tick), np.log10(max_tick), 6))
        #scale_ticks = [0.1,0.3,1,3,10, max_tick]
        # Interpolation can be 'nearest', 'bilinear' or 'bicubic'
        # ax.set_title(label)
        # build a rectangle in axes coords
        ax.annotate(subplot_label, xy=(0.0, 1.1), xycoords='axes fraction',  # fontsize=10,
                    horizontalalignment='left', verticalalignment='top')
        # ax.text(right, top, subplot_label,
        #         horizontalalignment='right',
        #         verticalalignment='bottom',
        #         transform=ax.transAxes)
        cax = ax.imshow(Eabs_data, interpolation='nearest', cmap=cm.jet,
                        origin='lower', vmin=min_tick, vmax=max_tick, extent=(min(scale_x), max(scale_x), min(scale_z), max(scale_z))
                        ,norm = LogNorm()
                        )
        ax.axis("image")

        # Add colorbar
        cbar = fig.colorbar(cax, ticks=[a for a in scale_ticks], ax=ax)
        # vertically oriented colorbar
        cbar.ax.set_yticklabels(['%2.1f' % (a) for a in scale_ticks])
        # pos = list(cbar.ax.get_position().bounds)
        #fig.text(pos[0] - 0.02, 0.925, '|E|/|E$_0$|', fontsize = 14)
        lp2 = -10.0
        lp1 = -1.0
        if crossplane == 'XZ':
            ax.set_xlabel('Z, ' + WL_units, labelpad=lp1)
            ax.set_ylabel('X, ' + WL_units, labelpad=lp2)
        elif crossplane == 'YZ':
            ax.set_xlabel('Z, ' + WL_units, labelpad=lp1)
            ax.set_ylabel('Y, ' + WL_units, labelpad=lp2)
        elif crossplane == 'XY':
            ax.set_xlabel('Y, ' + WL_units, labelpad=lp1)
            ax.set_ylabel('X, ' + WL_units, labelpad=lp2)
        # # This part draws the nanoshell
        from matplotlib import patches
        from matplotlib.path import Path
        for xx in x:
            r = xx * WL / 2.0 / np.pi
            s1 = patches.Arc((0, 0), 2.0 * r, 2.0 * r,  angle=0.0, zorder=1.8,
                             theta1=0.0, theta2=360.0, linewidth=outline_width, color='black')
            ax.add_patch(s1)
        #
        # for flow in range(0,flow_total):
        #     flow_x, flow_z = GetFlow(scale_x, scale_z, Ec, Hc,
        #                              min(scale_x)+flow*(scale_x[-1]-scale_x[0])/(flow_total-1),
        #                              min(scale_z),
        #                              #0.0,
        #                              npts*16)
        #     verts = np.vstack((flow_z, flow_x)).transpose().tolist()
        #     #codes = [Path.CURVE4]*len(verts)
        #     codes = [Path.LINETO]*len(verts)
        #     codes[0] = Path.MOVETO
        #     path = Path(verts, codes)
        #     patch = patches.PathPatch(path, facecolor='none', lw=1, edgecolor='yellow')
        #     ax.add_patch(patch)
        if (crossplane == 'XZ' or crossplane == 'YZ') and flow_total > 0:

            from matplotlib.path import Path
            scanSP = np.linspace(-factor * x[-1], factor * x[-1], npts)
            min_SP = -factor * x[-1]
            step_SP = 2.0 * factor * x[-1] / (flow_total - 1)
            x0, y0, z0 = 0, 0, 0
            max_length = factor * x[-1] * 10
            # max_length=factor*x[-1]*5
            max_angle = np.pi / 160
            if is_flow_extend:
                rg = range(0, flow_total * 5 + 1)
            else:
                rg = range(0, flow_total)
            for flow in rg:
                if crossplane == 'XZ':
                    if is_flow_extend:
                        x0 = min_SP * 2 + flow * step_SP
                    else:
                        x0 = min_SP + flow * step_SP
                    z0 = min_SP
                    # y0 = x[-1]/20
                elif crossplane == 'YZ':
                    if is_flow_extend:
                        y0 = min_SP * 2 + flow * step_SP
                    else:
                        y0 = min_SP + flow * step_SP
                    z0 = min_SP
                    # x0 = x[-1]/20
                flow_xSP, flow_ySP, flow_zSP = GetFlow3D(
                    x0, y0, z0, max_length, max_angle, x, m, pl)
                if crossplane == 'XZ':
                    flow_z_plot = flow_zSP * WL / 2.0 / np.pi
                    flow_f_plot = flow_xSP * WL / 2.0 / np.pi
                elif crossplane == 'YZ':
                    flow_z_plot = flow_zSP * WL / 2.0 / np.pi
                    flow_f_plot = flow_ySP * WL / 2.0 / np.pi

                verts = np.vstack(
                    (flow_z_plot, flow_f_plot)).transpose().tolist()
                codes = [Path.LINETO] * len(verts)
                codes[0] = Path.MOVETO
                path = Path(verts, codes)
                #patch = patches.PathPatch(path, facecolor='none', lw=0.2, edgecolor='white',zorder = 2.7)
                patch = patches.PathPatch(
                    path, facecolor='none', lw=0.7, edgecolor='white', zorder=1.9, alpha=0.7)
                ax.add_patch(patch)
#                ax.plot(flow_z_plot, flow_f_plot, 'x', ms=2, mew=0.1,
#                        linewidth=0.5, color='k', fillstyle='none')

    finally:
        terms, Qext, Qsca, Qabs, Qbk, Qpr, g, Albedo, S1, S2 = scattnlay(
            np.array([x]), np.array([m]))
        print("Qabs = " + str(Qabs))
    conc_label = conc_labels[ii]
    ax.set_ylabel(conc_label,rotation=0,ha='right', fontsize=mpl.rcParams['font.size'])
    if ii!=10:
        ax.set_xlabel('')
        ax.set_xticks([])
    
    if ii == 5:
        ax.text(-0.35,0.5,'fluorescein [M]', rotation=90,ha='right', fontsize=mpl.rcParams['font.size'],transform=ax.transAxes)
    if ii == 0:
        labeler.label_subplot(ax,'A')

vmin = 1e0
vmax = 1E7
#panel B
ax = plt.subplot(gs[0:9,1])
im = ax.imshow(sort_counts , interpolation='nearest', cmap=mpl.cm.hot, norm=LogNorm(vmin=vmin, vmax=vmax))
ax.set_ylabel('fluorescein [M]',labelpad=10)
ticks = range(11)
labels = ['0'] + ['$10^{%1.1f}$'%x for x in np.arange(-9.5,-4.5,0.5)]
ax.set_yticks(ticks)
ax.set_yticklabels(labels)
ax.set_xlabel('bin', labelpad=1)
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
plt.title('cells',fontsize=mpl.rcParams['font.size'])
labeler.label_subplot(ax,'B')

divider = make_axes_locatable(ax)
width = axes_size.AxesY(ax, aspect=1/30.)
pad = axes_size.Fraction(0.75, width)
cax = divider.append_axes("right", size=width, pad=pad)
Beispiel #13
0
int_density = np.transpose(int_density)
x_density = np.transpose(x_density)
y_density = np.transpose(y_density)
int_density_refined = int_density.copy()

int_density_refined[int_density_refined < threshold] = 0.0

plt.imshow(int_density_refined,
           origin='lower',
           cmap=cm.jet,
           extent=(x_density[0, 0], x_density[0,
                                              -1], y_density[0,
                                                             0], y_density[-1,
                                                                           0]),
           aspect='auto',
           norm=LogNorm(vmin=0.01, vmax=0.6),
           interpolation="nearest")
#ax2.set_ylabel('Intensity/$\mu$T',fontsize=16)

#plt.xlim(x_density[0,0],x_density[-1,0])
#plt.ylim(y_density[0,0],y_density[0,-1])
plt.xlabel('Age/yr', fontsize=16)
plt.ylabel('Intensity/$\mu$T', fontsize=16)

cb = plt.colorbar(ticks=[0.01, 0.1, 0.2, 0.3, 0.4, 0.5, .6],
                  orientation='vertical',
                  format='$%.2f$')

#cb = plt.colorbar(ticks=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6,0.7, 0.8,0.9, 1],
#             orientation='vertical')
cb.set_label('Probability', fontsize=16)
Beispiel #14
0
    print("Reading " + directory + " ...")

    for file in os.listdir(base_loc + "/" + directory):
        if fnmatch.fnmatch(file, '*_coverage_pc.obj'):
            filepath = base_loc + "/" + directory + "/" + file
            break

    coordinates = np.loadtxt(filepath, dtype=str)
    print("Done loading ...")

    coordinates = coordinates[coordinates[:, 0] == "v", 1:].astype(float)

    print("Done pruning ...")

    longitudes = np.arctan2(coordinates[:, 1], coordinates[:,
                                                           0]) * 180. / np.pi
    latitudes = np.arctan(coordinates[:, 2] / np.linalg.norm(
        coordinates[:, 0:2], axis=1)) * 180. / np.pi
    # radii = np.linalg.norm()
    print("Done computing ...")

    plt.hist2d(longitudes, latitudes, bins=(50, 25), norm=LogNorm(), cmin=30)
    plt.xlabel("Longitude (deg)")
    plt.ylabel("Latitude (deg)")
    plt.title("Coverage, case " + directory.split("_")[1])
    plt.colorbar()
    plt.tight_layout()
    plt.show()
    # plt.savefig("/Users/bbercovici/GDrive/CUBoulder/Research/conferences/GNSKi_2019/paper/Figures/coverage_" + directory + ".pdf")
    plt.clf()
Beispiel #15
0
data2 = np.random.randn(100, 2) + np.array([20, 30])
data = np.vstack([data1, data2])
print data

# display predicted scores by the model as a contour plot
x = np.linspace(-20.0, 40.0)
y = np.linspace(-20.0, 40.0)
X, Y = np.meshgrid(x, y)
XX = np.array([X.ravel(), Y.ravel()]).T

ax = []
fig, ax = plt.subplots(1, 3, figsize=(20, 10))
fig.subplots_adjust(hspace=.4)

# Plot models for various components
for components in range(1, 4):
    gmm = GMM(n_components=components, covariance_type='full')
    gmm.fit(data)
    Z = -gmm.score_samples(XX)[0]
    Z = Z.reshape(X.shape)

    CS = ax[components - 1].contour(X,
                                    Y,
                                    Z,
                                    norm=LogNorm(vmin=1.0, vmax=1000.0),
                                    levels=np.logspace(0, 3, 10))
    ax[components - 1].scatter(data[:, 0], data[:, 1], .8)

plt.colorbar(CS, shrink=0.8, extend='both')
plt.axis('tight')
plt.show()
Beispiel #16
0
    def plot_single_heatmap_general(self, heatmap_metric_specification,
                                    heatmap_axes_specification):
        # data extraction

        output_path, filename = self._construct_output_path_and_filename(
            heatmap_metric_specification, heatmap_axes_specification)

        logger.debug("output_path is {};\t filename is {}".format(
            output_path, filename))

        if not self.overwrite_existing_files and os.path.exists(filename):
            logger.info(
                "Skipping generation of {} as this file already exists".format(
                    filename))
            return

        xaxis_parameters = self.extract_parameter_values(
            heatmap_axes_specification['x_axis_parameter'])
        yaxis_parameters = self.extract_parameter_values(
            heatmap_axes_specification['y_axis_parameter'])

        # all heatmap values will be stored in X
        X = np.zeros((len(yaxis_parameters), len(xaxis_parameters)))

        fig, ax = plt.subplots(figsize=(FIGSIZE[0] - 0.75, FIGSIZE[1]))

        min_number_of_observed_values = 10000000000000
        max_number_of_observed_values = 0
        observed_values = np.empty(0)

        for x_index, x_val in enumerate(xaxis_parameters):
            # all scenario indices which has x_val as xaxis parameter (e.g. node_resource_factor = 0.5
            sub_dict = self.data_dict[x_val]
            for y_index, y_val in enumerate(yaxis_parameters):
                results = self.data_dict[x_val][y_val]
                values = [
                    heatmap_metric_specification['lookup_function'](result)
                    for result in results
                ]

                if 'metric_filter' in heatmap_metric_specification:
                    values = [
                        value for value in values
                        if heatmap_metric_specification['metric_filter'](value)
                    ]

                observed_values = np.append(observed_values, values)

                if len(values) < min_number_of_observed_values:
                    min_number_of_observed_values = len(values)
                if len(values) > max_number_of_observed_values:
                    max_number_of_observed_values = len(values)

                logger.debug("values are {}".format(values))
                if heatmap_metric_specification[
                        "plot_type"] == HeatmapPlotType.Simple_Treewidth_Evaluation_Max:
                    m = np.max(values)
                    logger.debug("max is {}".format(m))
                elif heatmap_metric_specification[
                        "plot_type"] == HeatmapPlotType.Simple_Treewidth_Evaluation_Average:
                    m = np.mean(values)
                    logger.debug("mean is {}".format(m))
                else:
                    raise ValueError("Invalid HeatmapPlotType")
                if 'rounding_function' in heatmap_metric_specification:
                    rounded_m = heatmap_metric_specification[
                        'rounding_function'](m)
                else:
                    rounded_m = float("{0:.1f}".format(round(m, 2)))
                X[y_index, x_index] = rounded_m

        if not self.paper_mode:
            if min_number_of_observed_values == max_number_of_observed_values:
                solution_count_string = "{} values per square".format(
                    min_number_of_observed_values)
            else:
                solution_count_string = "between {} and {} values per square".format(
                    min_number_of_observed_values,
                    max_number_of_observed_values)

        ax.tick_params(axis="both", **HEATMAP_MAJOR_TICK_PARAMS)

        if self.paper_mode:
            ax.set_title(heatmap_metric_specification['name'],
                         fontsize=PLOT_TITLE_FONT_SIZE)
        else:
            title = heatmap_metric_specification['name'] + "\n"
            title += solution_count_string + "\n"
            title += "min: {:.2f}; mean: {:.2f}; max: {:.2f}".format(
                np.nanmin(observed_values), np.nanmean(observed_values),
                np.nanmax(observed_values))
            ax.set_title(title)

        norm = LogNorm(vmin=X[X > 0].min(), vmax=X.max())
        heatmap = ax.pcolor(
            X,
            cmap=heatmap_metric_specification['cmap'],
            vmin=heatmap_metric_specification['vmin'],
            vmax=heatmap_metric_specification['vmax'],
            norm=norm,
        )

        if not self.paper_mode:
            fig.colorbar(heatmap,
                         label=heatmap_metric_specification['name'] +
                         ' - mean in blue')
        else:
            cbar = fig.colorbar(heatmap)
            if 'colorbar_ticks' in heatmap_metric_specification:
                ticks = heatmap_metric_specification['colorbar_ticks']
                tick_labels = [str(tick).ljust(3) for tick in ticks]
                cbar.set_ticks(ticks)
                cbar.set_ticklabels(tick_labels)
                cbar.ax.tick_params(labelsize=TICK_LABEL_FONT_SIZE)
            else:
                print "No colorbar tick labels were specified for {}".format(
                    heatmap_metric_specification["name"])
            # for label in cbar.ax.get_yticklabels():
            #    label.set_fontproperties(font_manager.FontProperties(family="Courier New",weight='bold'))
            cbar.ax.tick_params(**HEATMAP_COLORBAR_TICK_PARAMS)

        if "x_axis_ticks" in heatmap_axes_specification:
            tick_locations = [
                xaxis_parameters.index(x)
                for x in heatmap_axes_specification["x_axis_ticks"]
            ]
            tick_locations = np.array(tick_locations) + 0.5
            ax.set_xticks(tick_locations, minor=False)
            tick_locations_minor = [
                xaxis_parameters.index(x)
                for x in heatmap_axes_specification["x_axis_ticks_minor"]
            ]
            ax.set_xticks(tick_locations_minor, minor=True)
            x_labels = map(
                heatmap_axes_specification["x_axis_tick_formatting"],
                heatmap_axes_specification["x_axis_ticks"])
            ax.set_xticklabels(x_labels,
                               minor=False,
                               fontsize=TICK_LABEL_FONT_SIZE)
        else:
            ax.set_xticks(np.arange(X.shape[1]) + 0.5, minor=False)

        if "y_axis_ticks" in heatmap_axes_specification:
            tick_locations = [
                yaxis_parameters.index(x)
                for x in heatmap_axes_specification["y_axis_ticks"]
            ]
            tick_locations = np.array(tick_locations) + 0.5
            ax.set_yticks(tick_locations, minor=False)
            tick_locations_minor = [
                yaxis_parameters.index(x)
                for x in heatmap_axes_specification["y_axis_ticks_minor"]
            ]
            ax.set_yticks(tick_locations_minor, minor=True)
            y_labels = map(
                heatmap_axes_specification["y_axis_tick_formatting"],
                heatmap_axes_specification["y_axis_ticks"])
            ax.set_yticklabels(y_labels,
                               minor=False,
                               fontsize=TICK_LABEL_FONT_SIZE)
        else:
            ax.set_yticks(np.arange(X.shape[0]) + 0.5, minor=False)

        # column_labels = yaxis_parameters
        ax.set_xlabel(heatmap_axes_specification['x_axis_title'],
                      fontsize=X_AXIS_LABEL_FONT_SIZE)
        ax.set_ylabel(heatmap_axes_specification['y_axis_title'],
                      fontsize=Y_AXIS_LABEL_FONT_SIZE)
        # ax.set_yticklabels(column_labels, minor=False, fontsize=Y_AXIS_TICK_LABEL_FONT_SIZE)

        self._show_and_or_save_plots(output_path, filename)
Beispiel #17
0
    :param filter: str, filter name
    :param fpm: focal plane mask
    :param ppm: pupil plane mask - Lyot stop
    :return:
    """
    nc = webbpsf.NIRCam()
    nc.filter = filter
    nc.image_mask = fpm
    nc.pupil_mask = ppm

    return nc


if __name__ == '__main__':

    nc_coro = setup_coro('F335M', 'MASK335R', 'CIRCLYOT')
    nc_coro, ote_coro = webbpsf.enable_adjustable_ote(nc_coro)

    ote_coro.zero()
    #ote_coro._apply_hexikes_to_seg('A1', [1e-6])
    #ote_coro._apply_hexikes_to_seg('A3', [1e-6])
    #ote_coro.move_seg_local('A6', xtilt=0.5)
    psf = nc_coro.calc_psf(oversample=1)
    psf = psf[1].data

    plt.subplot(1, 2, 1)
    ote_coro.display_opd()
    plt.subplot(1, 2, 2)
    plt.imshow(psf, norm=LogNorm())
    plt.show()
A = A + A.T
X = A.copy()

ct = 0
f, ax = plt.subplots(2,nprint,sharey=True,figsize=(12,6))
for i in range(niter):
    Q, R = np.linalg.qr(X)
    X = R @ Q
    
    if i % niterprint == 0:
        
        I, J = np.where(np.abs(X) < 1e-13)
        Xtmp = X.copy()
        Xtmp[I,J] = 0.0
        
        im = ax[0,ct].imshow(np.abs(Xtmp.real), cmap=plt.cm.winter, norm=LogNorm())
        ax[0,ct].axis('off')
        
        if np.abs(Xtmp.imag).max() > 1e-13:
            im = ax[1,ct].imshow(np.abs(Xtmp.imag), cmap=plt.cm.winter, norm=LogNorm())
        ax[1,ct].axis('off')
        ct += 1
        
f.colorbar(im, ax=ax.ravel().tolist(), shrink=0.95)


# In[79]:


Xtmp
Beispiel #19
0
def show_hexbin(axes, x, y):
    axes.hexbin(x, y, cmap='Purples', gridsize=40, norm=LogNorm(), mincnt=1)
Beispiel #20
0
def plot_contour(*opts,
                 fxn_name,
                 animate_gif=True,
                 fig_size=None,
                 save_f=True,
                 f_name='v1',
                 in_type=None):
    def init():
        for line in lines:
            line.set_data([], [])
        return lines

    def animate(i):
        num1 = int(x2[i])
        for lnum, (line, scat) in enumerate(zip(lines, scats)):
            if num1 < dp[lnum]:
                #                 print(i, dp[lnum])
                line.set_data(
                    xlist[lnum][:num1],
                    ylist[lnum][:num1])  # set data for each line separately.
                scat.set_offsets([xlist[lnum][num1], ylist[lnum][num1]])
                line.set_label(nn[lnum])  # set the label and draw the legend
                plt.legend(loc="upper left")
        return lines

    if fig_size == 'small':
        fig, ax = plt.subplots(figsize=(6, 4))
    else:
        fig, ax = plt.subplots(figsize=(8.5, 6.8))
    plt.tight_layout()

    data, minima, x_lims, y_lims = plot_fxn(fxn_name, 'contour')

    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_xlim(x_lims)
    ax.set_ylim(y_lims)

    ax.contour(*data,
               levels=np.logspace(-.5, 5, 35),
               norm=LogNorm(),
               cmap='viridis',
               alpha=0.7)  #cmap=plt.cm.jet)
    ax.plot(*minima[0:2], 'x', markersize=12, mew=2, color='k')

    xlist, ylist, zlist, nn, dp = get_dlists(opts, in_type)
    n = len(xlist)
    # print(len(xlist))

    if fxn_name == 'rosenbrock':
        if in_type == 'sdict':
            c = cm.rainbow_r(np.linspace(0, 1, n))
        else:
            c = cm.jet(np.linspace(0, 1, n))
    else:
        c = cm.rainbow(np.linspace(0, 1, n))

    if animate_gif == False:
        for k in range(n):
            x_history = np.array(xlist[k])
            y_history = np.array(ylist[k])
            path = np.concatenate(
                (np.expand_dims(x_history, 1), np.expand_dims(y_history, 1)),
                axis=1).T
            ax.quiver(path[0, :-1],
                      path[1, :-1],
                      path[0, 1:] - path[0, :-1],
                      path[1, 1:] - path[1, :-1],
                      scale_units='xy',
                      angles='xy',
                      width=0.003,
                      scale=1,
                      color=c[k],
                      label=nn[k])
        plt.legend(loc="upper left")
        if save_f == True:
            plt.savefig('images/{}_path.png'.format(fxn_name))
    else:
        line, = ax.plot([], [], lw=2)  #, markersize=12)
        lines = []
        scats = []
        for index in range(n):
            l_obj = ax.plot([], [], lw=2, color=c[index])[0]
            lines.append(l_obj)
            s_obj = ax.scatter([], [], lw=2, color=c[index])
            scats.append(s_obj)
        num_min = int(len(xlist[0]) / 50)
        #         print(num_min)
        x2 = np.rint(np.linspace(0, len(xlist[1]), endpoint=False,
                                 num=200))  # fix this
        #         print(x2)
        #         x2 = np.arange(len(xlist[0]))
        # blit=True --> only re-draw the parts that have changed.
        scat = ax.scatter(
            [], [])  # Set the dot at some arbitrary position initially
        anim = animation.FuncAnimation(fig,
                                       animate,
                                       init_func=init,
                                       frames=len(x2),
                                       interval=1,
                                       blit=True)
        anim.save('images/{}_contour_{}.gif'.format(fxn_name, f_name),
                  dpi=60,
                  writer="imagemagick")

    plt.show()
    X_amplitude=100.,

    # parameter controling smoothness of the absorbing boundary, if the latter is used
    alpha=0.02,
    K=lambda p: 0.5 * p**2,
    diff_K=lambda p: p,

    # the soft core Coulomb potential
    V=lambda x: -1. / np.sqrt(x**2 + 1.37),

    # the derivative of the potential to calculate Ehrenfest
    diff_V=lambda x: x * np.power(x**2 + 1.37, -1.5),
)

# This is how to make logarithmic color plot
norm = LogNorm(vmin=1e-12, vmax=0.1)

#########################################################################
#
# Test propagation under time independent potential
#
#########################################################################

plt.subplot(121)
plt.title(
    "No absorbing boundary time independent potential, $|\\Psi(x, t)|^2$")
test(SplitOpSchrodinger1D, params)

plt.subplot(122)
plt.title("Absorbing boundary time independent potential, $|\\Psi(x, t)|^2$")
test(SplitOpSchrodinger1DAbsBoundary, params)
Beispiel #22
0
def find_cut(ds, ds_lo, write_db=False):

    #Make tier2 dataframe, get e_ftp and first pass calibration constants, then calibrate
    t2 = ds.get_t2df()
    t2 = t2.reset_index(drop=True)

    calDB = ds.calDB
    query = db.Query()
    table = calDB.table("cal_pass1")
    vals = table.all()
    df_cal = pd.DataFrame(vals) # <<---- omg awesome
    df_cal = df_cal.loc[df_cal.ds==ds_lo]
    p1cal = df_cal.iloc[0]["p1cal"]
    cal = p1cal * np.asarray(t2["e_ftp"])

    hist, bins = np.histogram(cal, bins=2000, range=[0,2000])
    b = (bins[:-1] + bins[1:]) / 2
    # np.savez('ds{}'.format(ds_lo), cal)
    # np.savez('bins_ds{}'.format(ds_lo), b)


    # plt.clf()
    plt.title('DS{}'.format(ds_lo))
    plt.plot(b, hist, ls="steps", linewidth=1.5)
    plt.ylabel('Counts')
    plt.xlabel('keV')
    plt.tight_layout()
    plt.show()
    exit()


    current = "current_max"
    e_over_unc = cal / np.asarray(t2["e_ftp"])
    y0 = np.asarray(t2[current])
    a_over_e = y0 * e_over_unc / cal

    y = linear_correction(cal, a_over_e)

    # dep_range = [1530,1620]
    # hist, bins = np.histogram(cal, bins=450, range=dep_range)
    # hist = hist * 5
    #
    def gauss(x, *params):
        y = np.zeros_like(x)
        for i in range(0, len(params) - 1, 3):
            x0 = params[i]
            a = params[i + 1]
            sigma = params[i + 2]
            y += a * np.exp(-(x - x0)**2 / (2 * sigma**2))
        y = y + params[-1]
        return y
    #
    # p0_list = [1591, 200, 3, 4]
    #
    # par, pcov = curve_fit(
    #     gauss, bins[1:], hist, p0=p0_list)
    # print(par)
    # perr = np.sqrt(np.diag(pcov))
    # print(perr)
    #
    # mu, amp, sig, bkg = par[0], par[1], par[2], par[-1]
    # print("Scanning ", mu, " peak")
    # ans = quad(gauss, 1583, 1600, args=(mu, amp, sig, bkg))
    # counts = ans[0] - ((1600-1583)*bkg)
    # print("Counts in ", mu, " peak is ", counts)
    #
    # cut = counts
    # line = .4
    #
    # y1 = y[np.where(line < y)]
    # x1 = cal[np.where(line < y)]
    # # hist1, bins1 = np.histogram(x1, bins=500, range=[1500,1700])
    # hist1, bins1 = np.histogram(x1, bins=450, range=[1530,1620])
    # hist1 = hist1*5
    #
    # print("Finding optimal cut, keeping 90% of 1592 DEP")
    # while cut > .9 * counts:
    #
    #     y1 = y[np.where(line < y)]
    #     x1 = cal[np.where(line < y)]
    #
    #     hist1, bins1 = np.histogram(x1, bins=450, range=dep_range)
    #     hist1 = hist1*5
    #
    #     par1, pcov1 = curve_fit(
    #         gauss, bins1[1:], hist1, p0=p0_list)
    #     perr1 = np.sqrt(np.diag(pcov1))
    #
    #     mu1, amp1, sig1, bkg1 = par1[0], par1[1], par1[2], par1[-1]
    #     ans1 = quad(gauss, 1583, 1600, args=(mu1, amp1, sig1, bkg1))
    #     cut = ans1[0] - ((1600-1583)*bkg1)
    #
    #     line += .0005

    line = .95

    y1 = y[np.where(line < y)]
    x1 = cal[np.where(line < y)]
    y2 = y[np.where(line > y)]
    x2 = cal[np.where(line > y)]
    np.savez('thorium', x1)
    np.savez('Ac', x2)

    # print(line, cut)
    plt.hist2d(cal, y, bins=[1000,200], range=[[0, 2000], [0, 2]], norm=LogNorm(), cmap='jet')
    plt.hlines(line, 0, 2000, color='r', linewidth=1.5)
    cbar = plt.colorbar()
    plt.title("Dataset {}".format(ds_lo))
    plt.xlabel("Energy (keV)", ha='right', x=1)
    plt.ylabel("A/Eunc", ha='right', y=1)
    cbar.ax.set_ylabel('Counts')
    plt.tight_layout()
    plt.show()

    hist, bins = np.histogram(cal, bins=2000, range=[0,2000])
    hist1, bins1 = np.histogram(x1, bins=2000, range=[0,2000])

    hist2, bins2 = np.histogram(x2, bins=2000, range=[0,2000])

    p0_list = [1593, 200, 3, 4]

    par, pcov = curve_fit(
        gauss, bins1[1:], hist1, p0=p0_list)
    print(par)
    perr = np.sqrt(np.diag(pcov))
    print(perr)

    plt.clf()
    # plt.semilogy(bins[1:], hist, color='black', ls="steps", linewidth=1.5, label='Calibrated Energy: Dataset {}'.format(ds_lo))
    plt.semilogy(bins1[1:], hist1, '-r', ls="steps", linewidth=1.5, label='AvsE Cut: Dataset {}'.format(ds_lo))
    plt.ylabel('Counts')
    plt.xlabel('keV')
    plt.legend()
    plt.tight_layout()
    plt.show()

    plt.clf()
    plt.semilogy(bins2[1:], hist2, ls="steps", linewidth=1.5)
    plt.title('Ac spectra')
    plt.ylabel('Counts')
    plt.xlabel('keV')
    plt.tight_layout()
    plt.show()

    if write_db:
        table = calDB.table("A/E_cut")
        for dset in ds.ds_list:
            row = {"ds":dset, "line":line}
            table.upsert(row, query.ds == dset)
Beispiel #23
0
def plt_snapshot(s, h, num, axis='y', savdir=None, savfig=False):
    mpl.rcParams['font.size'] = 13
    n0 = s.par['problem']['n0']

    dfi = s.dfi
    if s.par['configure']['radps'] == 'ON':
        fields = [
            'r', 'nH', '2nH2', 'nHI', 'nHII', 'ne', 'xe', 'xHI', '2xH2',
            'xHII', 'T', 'pok', 'chi_PE', 'chi_LW', 'chi_LW_dust', 'heat_rate',
            'cool_rate'
        ]
        new_cool = True
    elif s.par['configure']['new_cooling'] == 'ON':
        fields = [
            'r', 'nH', '2nH2', 'nHI', 'nHII', 'ne', 'xe', 'xHI', '2xH2',
            'xHII', 'T', 'pok', 'heat_rate', 'cool_rate'
        ]
        new_cool = True
    else:
        fields = ['r', 'nH', 'T', 'pok', 'heat_rate', 'cool_rate']
        new_cool = False

    ds = s.load_vtk(num)
    Lx = ds.domain['Lx'][0]
    slc = ds.get_slice(axis, fields)

    fig, axes = plt.subplots(2, 3, figsize=(15, 10))
    axes = axes.flatten()

    plt.sca(axes[0])
    if new_cool:
        fields = ('2nH2', 'nHI', 'nHII', 'ne')
    else:
        fields = ('nH', )
    for f in fields:
        plt.scatter(slc['r'], slc[f], s=2.0, label=slc.dfi[f]['label'])

    plt.xlim(0, 0.5 * 2.0**0.5 * Lx)
    plt.ylim(1e-6 * n0, 20.0 * n0)
    plt.yscale('log')
    plt.legend(loc=4)

    plt.sca(axes[1])
    if new_cool:
        fields = ('2xH2', 'xHI', 'xHII', 'xe')
    else:
        fields = ('nH', )
    for f in fields:
        plt.scatter(slc['r'], slc[f], s=2.0, label=slc.dfi[f]['label'])

    plt.xlim(0, 0.5 * 2.0**0.5 * Lx)
    plt.ylim(1e-6, 2.0)
    plt.yscale('log')
    plt.legend(loc=4)

    plt.sca(axes[2])
    for f in ('T', 'pok'):
        plt.scatter(slc['r'], slc[f], s=2.0, label=slc.dfi[f]['label'])
    plt.xlim(0, 0.5 * 2.0**0.5 * Lx)
    plt.ylim(1e1, 1e7)
    plt.yscale('log')
    plt.legend(loc=4)

    plt.sca(axes[4])
    for f in ('cool_rate', 'heat_rate'):
        plt.scatter(slc['r'], slc[f], s=2.0, label=f)

    plt.xlim(0, 0.5 * 2.0**0.5 * Lx)
    plt.ylim(1e-25, 1e-18)
    plt.yscale('log')
    plt.legend(loc=1)

    plt.sca(axes[5])
    #     d = ds.get_slice(axis, ['r','nH','xHI','xHII','xe','rad_energy_density_PH','T'])
    #     hnu_PH = (s.par['radps']['hnu_PH']*au.eV).cgs.value
    #     sigma_PH = s.par['radps']['sigma_HI_PH']
    #     d['xi_ph'] = ac.c.cgs.value*d['rad_energy_density_PH']*s.u.energy_density.value/hnu_PH*sigma_PH
    #     d['tphoti'] = d['xi_ph']*d['xHI']
    #     d['treci'] = d['xHII']*d['nH']*d['xe']*2.59e-13*(d['T']*1e-4)**-0.7
    #     d['tHII'] = 1.0/np.abs(d['tphoti'] - d['treci'])
    #    plt.scatter(d['r'],d['tHII'],s=2.0,label=['tHII'])
    #    plt.yscale('log')

    d = ds.get_field(['nH', 'cool_rate', 'T'])
    plt.hist2d(d['nH'].data.flatten(),
               d['T'].data.flatten(),
               bins=(np.logspace(np.log10(n0 * 1e-5), np.log10(n0 * 1e2),
                                 100), np.logspace(1, 7, 100)),
               norm=LogNorm(),
               weights=d['nH'].values.flatten())
    plt.xlabel(dfi['nH']['label'])
    plt.ylabel(dfi['T']['label'])
    plt.xscale('log')
    plt.yscale('log')
    plt.xlim(1e-5 * n0, 1e2 * n0)
    plt.ylim(1e1, 1e7)

    #     for f in ('chi_PE','chi_LW', 'chi_LW_dust'):
    #         plt.scatter(slc['r'], slc[f], s=2.0, label=slc.dfi[f]['label'])

    #     plt.xlim(0, 0.5*2.0**0.5*Lx)
    #     #plt.ylim(1e0,1e6)
    #     plt.ylim(1e5,1e15)
    #     plt.yscale('log')
    #     plt.legend(loc=1)

    # Temperature slice
    #     slc['T'].plot.imshow(ax=axes[3], norm=LogNorm(1e1,1e3),
    #                          label=slc.dfi['T']['label'],
    #                          cbar_kwargs=dict(label=slc.dfi['T']['label']))
    f = 'nH'
    slc[f].plot.imshow(
        ax=axes[3],
        norm=LogNorm(1e-4, 1e4),  # norm=slc.dfi[f]['norm'], 
        label=slc.dfi[f]['label'],
        cmap='Spectral_r',
        cbar_kwargs=dict(label=slc.dfi[f]['label']))
    axes[3].set_aspect('equal')

    plt.suptitle(f'Model: {s.basename}  ' + \
             r'num={0:2d} time={1:f}'.format(num, ds.domain['time']))
    print('time:', ds.domain['time'])
    plt.tight_layout()
    plt.subplots_adjust(top=0.94)
    if savfig:
        if savdir is None:
            savdir = osp.join('/tigress/jk11/figures/FEEDBACK-TEST',
                              s.basename)
        if not osp.exists(savdir):
            os.makedirs(savdir)

        plt.savefig(osp.join(savdir, 'slice_{0:04d}.png'.format(num)), dpi=200)

    return ds
Beispiel #24
0
alpha[np.isnan(alpha)] = 0.0
np.clip(alpha, a_min=0.0, a_max=1.0, out=alpha)

Rd = convolve(R, kernel)
Bd = convolve(B, kernel)
Gd = convolve(G, kernel)
A = convolve(alpha, kernel)

rgb = np.transpose(np.array([Rd, Gd, Bd]), axes=(1, 2, 0)).astype("float32")
rgb *= alpha[:, :, np.newaxis]

cmap = plt.cm.viridis
cmap.set_bad(color="black")

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(20, 10))
ax1.imshow(cts, origin='lower', norm=LogNorm(), cmap=cmap)
ax2.imshow(rgb, origin='lower')
fig.savefig("%s_%sdeg.png" % (basenm, angle))

hdur = fits.ImageHDU(data=Rd * A)
hdur.name = "red"
hdur.writeto("%s_red_%sdeg.fits" % (basenm, angle), overwrite=True)
hdub = fits.ImageHDU(data=Bd * A)
hdub.name = "blue"
hdub.writeto("%s_blue_%sdeg.fits" % (basenm, angle), overwrite=True)
hdug = fits.ImageHDU(data=Gd * A)
hdug.name = "green"
hdug.writeto("%s_green_%sdeg.fits" % (basenm, angle), overwrite=True)
fits.ImageHDU(data=rgb).writeto("%s_rgb_%sdeg.fits" % (basenm, angle),
                                overwrite=True)
def colorNearHist(galaxies, f):
    r"""
	Creates a 2d histogram of galaxies with color on the x-axis and
	number of nearby neighbors on the y-axis

	Parameters
		galaxies - Type: dict. A dictionary of galaxy objects to be plotted
		f - Type: str. The name of the plot's output file

	Returns none but prints two plots to the specified output files.
	"""

    errFlag = -9999
    galaxyList = list(galaxies.values())
    color = [galaxy.color for galaxy in galaxyList if galaxy.color > errFlag]
    colorSmall = [
        galaxy.color for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn > 0
    ]
    colorSmall2 = [
        galaxy.color for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn == 0
    ]
    numNear = [
        galaxy.nearby for galaxy in galaxyList if galaxy.color > errFlag
    ]
    numNearSmall = [
        galaxy.nearby for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn > 0
    ]
    numNearSmall2 = [
        galaxy.nearby for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn == 0
    ]

    # Plot the histograms
    plt.hist2d(colorSmall2,
               numNearSmall2,
               bins=100,
               norm=LogNorm(),
               cmin=1,
               cmap=plt.cm.inferno)
    plt.title("Color vs. Number of Neighbors", fontsize=14)
    plt.xlabel("Color (u - r)", fontsize=14)
    plt.ylabel("Number of nearby neighbors", fontsize=14)
    plt.colorbar()
    plt.savefig(f + 'NoAGN.png')
    print("Created near hist 1")

    plt.hist2d(colorSmall,
               numNearSmall,
               bins=100,
               norm=LogNorm(),
               cmin=1,
               cmap=plt.cm.inferno)
    plt.savefig(f + 'AGNonly.png')
    print("Created near hist 2")
    plt.clf()

    # Perform the KS test on the groups
    colorZeroes = [
        galaxy.color for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn > 0 and galaxy.nearby == 0
    ]
    colorZeroes2 = [
        galaxy.color for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn == 0 and galaxy.nearby == 0
    ]
    colorOnes = [
        galaxy.color for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn > 0 and galaxy.nearby == 1
    ]
    colorOnes2 = [
        galaxy.color for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn == 0 and galaxy.nearby == 1
    ]
    colorTwos = [
        galaxy.color for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn > 0 and galaxy.nearby == 2
    ]
    colorTwos2 = [
        galaxy.color for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn == 0 and galaxy.nearby == 2
    ]
    colorThrees = [
        galaxy.color for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn > 0 and galaxy.nearby == 3
    ]
    colorThrees2 = [
        galaxy.color for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn == 0 and galaxy.nearby == 3
    ]
    colorFours = [
        galaxy.color for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn > 0 and galaxy.nearby == 4
    ]
    colorFours2 = [
        galaxy.color for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn == 0 and galaxy.nearby == 4
    ]

    #	print("Color KS Test:", ks_2samp(np.array(colorSmall), np.array(colorSmall2)))
    #	print("NumNear KS Test:", ks_2samp(np.array(numNearSmall), np.array(numNearSmall2)))
    print("KS Test 0:",
          stats.ks_2samp(np.array(colorZeroes), np.array(colorZeroes2)))
    print("KS Test 1:",
          stats.ks_2samp(np.array(colorOnes), np.array(colorOnes2)))
    print("KS Test 2:",
          stats.ks_2samp(np.array(colorTwos), np.array(colorTwos2)))
    print("KS Test 3:",
          stats.ks_2samp(np.array(colorThrees), np.array(colorThrees2)))
    print("KS Test 4:",
          stats.ks_2samp(np.array(colorFours), np.array(colorFours2)))

    colorZeroes = [
        (galaxy.objId, galaxy.color) for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn > 0 and galaxy.nearby == 0
    ]
    colorZeroes2 = [
        (galaxy.objId, galaxy.color) for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn == 0 and galaxy.nearby == 0
    ]
    colorOnes = [
        (galaxy.objId, galaxy.color) for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn > 0 and galaxy.nearby == 1
    ]
    colorOnes2 = [
        (galaxy.objId, galaxy.color) for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn == 0 and galaxy.nearby == 1
    ]
    colorTwos = [
        (galaxy.objId, galaxy.color) for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn > 0 and galaxy.nearby == 2
    ]
    colorTwos2 = [
        (galaxy.objId, galaxy.color) for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn == 0 and galaxy.nearby == 2
    ]
    colorThrees = [
        (galaxy.objId, galaxy.color) for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn > 0 and galaxy.nearby == 3
    ]
    colorThrees2 = [
        (galaxy.objId, galaxy.color) for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn == 0 and galaxy.nearby == 3
    ]
    colorFours = [
        (galaxy.objId, galaxy.color) for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn > 0 and galaxy.nearby == 4
    ]
    colorFours2 = [
        (galaxy.objId, galaxy.color) for galaxy in galaxyList
        if galaxy.color > errFlag and galaxy.agn == 0 and galaxy.nearby == 4
    ]

    with open('galaxyData/withAGN.csv', 'w') as f:
        f.write("objID,numNear,color\n")
        for i in range(0, len(colorZeroes)):
            f.write(
                str(colorZeroes[i][0]) + ",0," + str(colorZeroes[i][1]) + "\n")
        for i in range(0, len(colorOnes)):
            f.write(str(colorOnes[i][0]) + ",1," + str(colorOnes[i][1]) + "\n")
        for i in range(0, len(colorTwos)):
            f.write(str(colorTwos[i][0]) + ",2," + str(colorTwos[i][1]) + "\n")
        for i in range(0, len(colorThrees)):
            f.write(
                str(colorThrees[i][0]) + ",3," + str(colorThrees[i][1]) + "\n")
        for i in range(0, len(colorFours)):
            f.write(
                str(colorFours[i][0]) + ",4," + str(colorFours[i][1]) + "\n")
        f.close()
    with open('galaxyData/withoutAGN.csv', 'w') as f:
        f.write("objID,numNear,color\n")
        for i in range(0, len(colorZeroes2)):
            f.write(
                str(colorZeroes2[i][0]) + ",0," + str(colorZeroes2[i][1]) +
                "\n")
        for i in range(0, len(colorOnes2)):
            f.write(
                str(colorOnes2[i][0]) + ",1," + str(colorOnes2[i][1]) + "\n")
        for i in range(0, len(colorTwos2)):
            f.write(
                str(colorTwos2[i][0]) + ",2," + str(colorTwos2[i][1]) + "\n")
        for i in range(0, len(colorThrees2)):
            f.write(
                str(colorThrees2[i][0]) + ",3," + str(colorThrees2[i][1]) +
                "\n")
        for i in range(0, len(colorFours2)):
            f.write(
                str(colorFours2[i][0]) + ",4," + str(colorFours2[i][1]) + "\n")
        f.close()
Beispiel #26
0
det = condor.Detector(distance=2., pixel_size=110E-6*ds, nx=1024/ds+1, ny=1024/ds+1, solid_angle_correction=False)

psphere = {"particle_sphere": condor.ParticleSphere(diameter=1E-9, material_type="water")}
pmap = {"particle_map": condor.ParticleMap(diameter=1E-9, material_type="water", geometry="icosahedron")}
patoms = {"particle_atoms": condor.ParticleAtoms(pdb_filename="%s/../../DNA.pdb" % this_dir)}
          
particles = [psphere, pmap, patoms]

if do_plot:
    fig, (axs1, axs2) = pyplot.subplots(2, len(particles), figsize=(3*len(particles), 3*2))

for i,par in enumerate(particles): 

    E = condor.Experiment(src, par, det)
    res = E.propagate()
    data = res["entry_1"]["data_1"]["data"]
    if do_plot:
        axs1[i].set_title("2D: " + par.keys()[0])
        lims = (data.min(), data.max())
        axs1[i].imshow(data, norm=LogNorm(lims[0], lims[1]), cmap="gnuplot")
        
    res = E.propagate3d()
    data = res["entry_1"]["data_1"]["data"][int(1024/ds/2),:,:] 
    if do_plot:
        axs2[i].set_title("3D slice: " + par.keys()[0])
        axs2[i].imshow(data, norm=LogNorm(lims[0], lims[1]), cmap="gnuplot")

if do_plot:
    fig.savefig("2Dvs3D.png", dpi=300)
    pyplot.show()
Beispiel #27
0
def plot_clouds(
    tag: str,
    offset: Optional[Tuple[float, float]] = None,
    output: Optional[str] = "clouds.pdf",
    radtrans: Optional[read_radtrans.ReadRadtrans] = None,
    composition: str = "MgSiO3",
) -> None:
    """
    Function to plot the size distributions for a given cloud composition as function as pressure.
    The size distributions are calculated for the median sample by using the radius_g (as function
    of pressure) and sigma_g.

    Parameters
    ----------
    tag : str
        Database tag with the posterior samples.
    offset : tuple(float, float), None
        Offset of the x- and y-axis label. Default values are used if set to ``None``.
    output : str
        Output filename for the plot. The plot is shown in an
        interface window if the argument is set to ``None``.
    radtrans : read_radtrans.ReadRadtrans, None
        Instance of :class:`~species.read.read_radtrans.ReadRadtrans`. Not used if set to ``None``.
    composition : str
        Cloud composition (e.g. 'MgSiO3', 'Fe', 'Al2O3', 'Na2S', 'KCl').

    Returns
    -------
    NoneType
        None
    """

    species_db = database.Database()
    box = species_db.get_samples(tag)
    median = box.median_sample

    if (
        f"{composition.lower()}_fraction" not in median
        and "log_tau_cloud" not in median
        and f"{composition}(c)" not in median
    ):

        raise ValueError(
            f"The mass fraction of the {composition} clouds is not found. The median "
            f"sample contains the following parameters: {list(median.keys())}"
        )

    if output is None:
        print(f"Plotting {composition} clouds...", end="", flush=True)
    else:
        print(f"Plotting {composition} clouds: {output}...", end="", flush=True)

    mpl.rcParams["font.serif"] = ["Bitstream Vera Serif"]
    mpl.rcParams["font.family"] = "serif"

    plt.rc("axes", edgecolor="black", linewidth=2.5)

    plt.figure(1, figsize=(4.0, 3.0))
    gridsp = mpl.gridspec.GridSpec(1, 2, width_ratios=[4, 0.25])
    gridsp.update(wspace=0.1, hspace=0.0, left=0, right=1, bottom=0, top=1)

    ax1 = plt.subplot(gridsp[0, 0])
    ax2 = plt.subplot(gridsp[0, 1])

    radtrans.get_model(median)

    cloud_index = radtrans.rt_object.cloud_species.index(f"{composition}(c)")
    radius_g = radtrans.rt_object.r_g[:, cloud_index] * 1e4  # (cm) -> (um)
    sigma_g = median["sigma_lnorm"]

    r_bins = np.logspace(-3.0, 3.0, 1000)
    radii = (r_bins[1:] + r_bins[:-1]) / 2.0

    dn_dr = np.zeros((radius_g.shape[0], radii.shape[0]))

    for i, item in enumerate(radius_g):
        dn_dr[
            i,
        ] = lognorm.pdf(radii, s=np.log(sigma_g), loc=0.0, scale=item)

    ax1.tick_params(
        axis="both",
        which="major",
        colors="black",
        labelcolor="black",
        direction="in",
        width=1,
        length=5,
        labelsize=12,
        top=True,
        bottom=True,
        left=True,
        right=True,
        labelbottom=True,
    )

    ax1.tick_params(
        axis="both",
        which="minor",
        colors="black",
        labelcolor="black",
        direction="in",
        width=1,
        length=3,
        labelsize=12,
        top=True,
        bottom=True,
        left=True,
        right=True,
        labelbottom=True,
    )

    ax2.tick_params(
        axis="both",
        which="major",
        colors="black",
        labelcolor="black",
        direction="in",
        width=1,
        length=5,
        labelsize=12,
        top=True,
        bottom=True,
        left=True,
        right=True,
    )

    ax2.tick_params(
        axis="both",
        which="minor",
        colors="black",
        labelcolor="black",
        direction="in",
        width=1,
        length=3,
        labelsize=12,
        top=True,
        bottom=True,
        left=True,
        right=True,
    )

    xx_grid, yy_grid = np.meshgrid(radii, 1e-6 * radtrans.rt_object.press)

    fig = ax1.pcolormesh(
        xx_grid,
        yy_grid,
        dn_dr,
        cmap="viridis",
        shading="auto",
        norm=LogNorm(vmin=1e-10 * np.amax(dn_dr), vmax=np.amax(dn_dr)),
    )

    cb = Colorbar(ax=ax2, mappable=fig, orientation="vertical", ticklocation="right")
    cb.ax.set_ylabel("dn/dr", rotation=270, labelpad=20, fontsize=11)

    for item in radtrans.rt_object.press * 1e-6:  # (bar)
        ax1.axhline(item, ls="-", lw=0.1, color="white")

    for item in radtrans.rt_object.cloud_radii * 1e4:  # (um)
        ax1.axvline(item, ls="-", lw=0.1, color="white")

    ax1.text(
        0.07,
        0.07,
        fr"$\sigma_\mathrm{{g}}$ = {sigma_g:.2f}",
        ha="left",
        va="bottom",
        transform=ax1.transAxes,
        color="black",
        fontsize=13.0,
    )

    ax1.set_ylabel("Pressure (bar)", fontsize=13)
    ax1.set_xlabel("Grain radius (µm)", fontsize=13)

    ax1.set_xlim(radii[0], radii[-1])
    ax1.set_ylim(
        radtrans.rt_object.press[-1] * 1e-6, radtrans.rt_object.press[0] * 1e-6
    )

    if offset is not None:
        ax1.get_xaxis().set_label_coords(0.5, offset[0])
        ax1.get_yaxis().set_label_coords(offset[1], 0.5)

    else:
        ax1.get_xaxis().set_label_coords(0.5, -0.1)
        ax1.get_yaxis().set_label_coords(-0.15, 0.5)

    ax1.set_xscale("log")
    ax1.set_yscale("log")
    ax2.set_yscale("log")

    print(" [DONE]")

    if output is None:
        plt.show()
    else:
        plt.savefig(output, bbox_inches="tight")

    plt.clf()
    plt.close()
Beispiel #28
0
def view_spectra(datacube,
                 title=None,
                 show=True,
                 logZ=False,
                 use_axis=True,
                 vlim=(None, None),
                 subplt_cols=3,
                 dx=None):
    """
    view plot of intensity in each wavelength bin at a single (last) timestep

    :param datacube: 3D spectral cube (n_wavelengths, nx, ny) at single timestep
    :param title: string, must be set or will error!
    :param show: flag possibly useful for plotting loops of things?
    :param logZ: turn logscale plotting for Z axis on or off
    :param use_axis: turn on/off using axis ticks, colorbar, etc
    :param vlim: tuple of colorbar axis limits (min,max)
    :param subplt_cols: number of subplots per row
    :param dx: sampling of the image in m. Hardcoded to convert to um
    :return:
    """
    # Create figure & adjust subplot number, layout, size, whitespace
    fig = plt.figure()
    n_colors = len(datacube)
    n_rows = int(np.ceil(n_colors / float(subplt_cols)) + 1)
    plt.axis('off')
    gs = gridspec.GridSpec(n_rows, subplt_cols, wspace=0.08, top=0.9)

    # Title
    if title is None:
        warnings.warn("Plots without titles: Don't Do It!")
        title = input("Please Enter Title: ")
        pass
    fig.suptitle(title, fontweight='bold', fontsize=16)

    # Wavelength Strings for Subplot Titles
    w_string = np.array(np.linspace(ap.wvl_range[0] * 1e9,
                                    ap.wvl_range[1] * 1e9,
                                    ap.n_wvl_final,
                                    dtype=int),
                        dtype=str)

    for w in range(n_colors):
        ax = fig.add_subplot(gs[w])
        ax.set_title(r'$\lambda$ = ' + f"{w_string[w]} nm")

        slice = opx.extract_center(datacube[w])

        # X,Y lables
        if dx is not None:
            dx[w] = dx[w] * 1e6  # [convert to um]
            # dprint(f"sampling = {sampl[w]}")
            tic_spacing = np.linspace(
                0, slice.shape[0],
                5)  # 5 (number of ticks) is set by hand, arbitrarily chosen
            tic_lables = np.round(
                np.linspace(-dx[w] * sp.maskd_size / 2,
                            dx[w] * sp.maskd_size / 2, 5)).astype(
                                int)  # nsteps must be same as tic_spacing
            tic_spacing[0] = tic_spacing[0] + 1  # hack for edge effects
            tic_spacing[-1] = tic_spacing[-1] - 1  # hack for edge effects
            plt.xticks(tic_spacing, tic_lables, fontsize=6)
            plt.yticks(tic_spacing, tic_lables, fontsize=6)
            # plt.xlabel('[um]', fontsize=8)
            # plt.ylabel('[um]', fontsize=8)

        # Z-axis scale
        if logZ:
            if np.min(slice) < 0:
                im = ax.imshow(slice,
                               interpolation='none',
                               origin='lower',
                               vmin=vlim[0],
                               vmax=vlim[1],
                               norm=SymLogNorm(linthresh=1e-5),
                               cmap="YlGnBu_r")
                clabel = "Log Normalized Intensity"
            else:
                im = ax.imshow(slice,
                               interpolation='none',
                               origin='lower',
                               vmin=vlim[0],
                               vmax=vlim[1],
                               norm=LogNorm(),
                               cmap="YlGnBu_r")
                clabel = "Log Normalized Intensity"
        else:
            im = ax.imshow(slice,
                           interpolation='none',
                           origin='lower',
                           vmin=vlim[0],
                           vmax=vlim[1],
                           cmap="YlGnBu_r")
            clabel = "Normalized Intensity"

        if use_axis == 'anno':
            ax.annotate_axis(im, ax, datacube.shape[1])
        if use_axis is None:
            plt.axis('off')

    if use_axis:
        warnings.simplefilter("ignore", category=UserWarning)
        gs.tight_layout(fig, pad=1.08,
                        rect=(0, 0, 1,
                              0.85))  # rect = (left, bottom, right, top)
        # fig.tight_layout(pad=50)
        cbar_ax = fig.add_axes([
            0.55, 0.3, 0.2, 0.05
        ])  # Add axes for colorbar @ position [left,bottom,width,height]
        cb = fig.colorbar(im, cax=cbar_ax, orientation='horizontal')  #
        cb.set_label(clabel)

    if show is True:
        plt.show(block=False)
Beispiel #29
0
def plot_opacities(
    tag: str,
    radtrans: read_radtrans.ReadRadtrans,
    offset: Optional[Tuple[float, float]] = None,
    output: Optional[str] = "opacities.pdf",
) -> None:
    """
    Function to plot the line and continuum opacity
    structure from the median posterior samples.

    Parameters
    ----------
    tag : str
        Database tag with the posterior samples.
    radtrans : read_radtrans.ReadRadtrans
        Instance of :class:`~species.read.read_radtrans.ReadRadtrans`.
        The parameter is not used if set to ``None``.
    offset : tuple(float, float), None
        Offset of the x- and y-axis label. Default values are used
        if set to ``None``.
    output : str, None
        Output filename for the plot. The plot is shown in an
        interface window if the argument is set to ``None``.

    Returns
    -------
    NoneType
        None
    """

    if output is None:
        print("Plotting opacities...", end="", flush=True)
    else:
        print(f"Plotting opacities: {output}...", end="", flush=True)

    species_db = database.Database()
    box = species_db.get_samples(tag)
    median = box.median_sample

    mpl.rcParams["font.serif"] = ["Bitstream Vera Serif"]
    mpl.rcParams["font.family"] = "serif"

    plt.rc("axes", edgecolor="black", linewidth=2.5)

    plt.figure(1, figsize=(10.0, 6.0))
    gridsp = mpl.gridspec.GridSpec(2, 5, width_ratios=[4, 0.25, 1.5, 4, 0.25])
    gridsp.update(wspace=0.1, hspace=0.1, left=0, right=1, bottom=0, top=1)

    ax1 = plt.subplot(gridsp[0, 0])
    ax2 = plt.subplot(gridsp[1, 0])
    ax3 = plt.subplot(gridsp[0, 1])
    ax4 = plt.subplot(gridsp[1, 1])

    ax5 = plt.subplot(gridsp[0, 3])
    ax6 = plt.subplot(gridsp[1, 3])
    ax7 = plt.subplot(gridsp[0, 4])
    ax8 = plt.subplot(gridsp[1, 4])

    radtrans.get_model(median)

    # Line opacities

    wavelength, opacity = radtrans.rt_object.get_opa(radtrans.rt_object.temp)

    wavelength *= 1e4  # (um)

    opacity_line = np.zeros(
        (radtrans.rt_object.freq.shape[0], radtrans.rt_object.press.shape[0])
    )

    for item in opacity.values():
        opacity_line += item

    # Continuum opacities

    opacity_cont_abs = radtrans.rt_object.continuum_opa
    opacity_cont_scat = radtrans.rt_object.continuum_opa_scat
    # opacity_cont_scat = radtrans.rt_object.continuum_opa_scat_emis
    opacity_total = opacity_line + opacity_cont_abs + opacity_cont_scat

    albedo = opacity_cont_scat / opacity_total

    # if radtrans.scattering:
    #     opacity_cont = radtrans.rt_object.continuum_opa_scat_emis
    # else:
    #     opacity_cont = radtrans.rt_object.continuum_opa_scat

    ax1.tick_params(
        axis="both",
        which="major",
        colors="black",
        labelcolor="black",
        direction="in",
        width=1,
        length=5,
        labelsize=12,
        top=True,
        bottom=True,
        left=True,
        right=True,
        labelbottom=False,
    )

    ax1.tick_params(
        axis="both",
        which="minor",
        colors="black",
        labelcolor="black",
        direction="in",
        width=1,
        length=3,
        labelsize=12,
        top=True,
        bottom=True,
        left=True,
        right=True,
        labelbottom=False,
    )

    ax2.tick_params(
        axis="both",
        which="major",
        colors="black",
        labelcolor="black",
        direction="in",
        width=1,
        length=5,
        labelsize=12,
        top=True,
        bottom=True,
        left=True,
        right=True,
    )

    ax2.tick_params(
        axis="both",
        which="minor",
        colors="black",
        labelcolor="black",
        direction="in",
        width=1,
        length=3,
        labelsize=12,
        top=True,
        bottom=True,
        left=True,
        right=True,
    )

    ax3.tick_params(
        axis="both",
        which="major",
        colors="black",
        labelcolor="black",
        direction="in",
        width=1,
        length=5,
        labelsize=12,
        top=True,
        bottom=True,
        left=True,
        right=True,
    )

    ax3.tick_params(
        axis="both",
        which="minor",
        colors="black",
        labelcolor="black",
        direction="in",
        width=1,
        length=3,
        labelsize=12,
        top=True,
        bottom=True,
        left=True,
        right=True,
    )

    ax4.tick_params(
        axis="both",
        which="major",
        colors="black",
        labelcolor="black",
        direction="in",
        width=1,
        length=5,
        labelsize=12,
        top=True,
        bottom=True,
        left=True,
        right=True,
    )

    ax4.tick_params(
        axis="both",
        which="minor",
        colors="black",
        labelcolor="black",
        direction="in",
        width=1,
        length=3,
        labelsize=12,
        top=True,
        bottom=True,
        left=True,
        right=True,
    )

    ax5.tick_params(
        axis="both",
        which="major",
        colors="black",
        labelcolor="black",
        direction="in",
        width=1,
        length=5,
        labelsize=12,
        top=True,
        bottom=True,
        left=True,
        right=True,
        labelbottom=False,
    )

    ax5.tick_params(
        axis="both",
        which="minor",
        colors="black",
        labelcolor="black",
        direction="in",
        width=1,
        length=3,
        labelsize=12,
        top=True,
        bottom=True,
        left=True,
        right=True,
        labelbottom=False,
    )

    ax6.tick_params(
        axis="both",
        which="major",
        colors="black",
        labelcolor="black",
        direction="in",
        width=1,
        length=5,
        labelsize=12,
        top=True,
        bottom=True,
        left=True,
        right=True,
    )

    ax6.tick_params(
        axis="both",
        which="minor",
        colors="black",
        labelcolor="black",
        direction="in",
        width=1,
        length=3,
        labelsize=12,
        top=True,
        bottom=True,
        left=True,
        right=True,
    )

    ax7.tick_params(
        axis="both",
        which="major",
        colors="black",
        labelcolor="black",
        direction="in",
        width=1,
        length=5,
        labelsize=12,
        top=True,
        bottom=True,
        left=True,
        right=True,
    )

    ax7.tick_params(
        axis="both",
        which="minor",
        colors="black",
        labelcolor="black",
        direction="in",
        width=1,
        length=3,
        labelsize=12,
        top=True,
        bottom=True,
        left=True,
        right=True,
    )

    ax8.tick_params(
        axis="both",
        which="major",
        colors="black",
        labelcolor="black",
        direction="in",
        width=1,
        length=5,
        labelsize=12,
        top=True,
        bottom=True,
        left=True,
        right=True,
    )

    ax8.tick_params(
        axis="both",
        which="minor",
        colors="black",
        labelcolor="black",
        direction="in",
        width=1,
        length=3,
        labelsize=12,
        top=True,
        bottom=True,
        left=True,
        right=True,
    )

    ax1.xaxis.set_major_locator(MultipleLocator(1.0))
    ax2.xaxis.set_major_locator(MultipleLocator(1.0))

    ax1.xaxis.set_minor_locator(MultipleLocator(0.2))
    ax2.xaxis.set_minor_locator(MultipleLocator(0.2))

    ax5.xaxis.set_major_locator(MultipleLocator(1.0))
    ax6.xaxis.set_major_locator(MultipleLocator(1.0))

    ax5.xaxis.set_minor_locator(MultipleLocator(0.2))
    ax6.xaxis.set_minor_locator(MultipleLocator(0.2))

    # ax1.yaxis.set_major_locator(LogLocator(base=10.))
    # ax2.yaxis.set_major_locator(LogLocator(base=10.))
    # ax3.yaxis.set_major_locator(LogLocator(base=10.))
    # ax4.yaxis.set_major_locator(LogLocator(base=10.))

    # ax1.yaxis.set_minor_locator(LogLocator(base=1.))
    # ax2.yaxis.set_minor_locator(LogLocator(base=1.))
    # ax3.yaxis.set_minor_locator(LogLocator(base=1.))
    # ax4.yaxis.set_minor_locator(LogLocator(base=1.))

    xx_grid, yy_grid = np.meshgrid(wavelength, 1e-6 * radtrans.rt_object.press)

    fig = ax1.pcolormesh(
        xx_grid,
        yy_grid,
        np.transpose(opacity_line),
        cmap="viridis",
        shading="gouraud",
        norm=LogNorm(vmin=1e-6 * np.amax(opacity_line), vmax=np.amax(opacity_line)),
    )

    cb = Colorbar(ax=ax3, mappable=fig, orientation="vertical", ticklocation="right")
    cb.ax.set_ylabel("Line opacity (cm$^2$/g)", rotation=270, labelpad=20, fontsize=11)

    fig = ax2.pcolormesh(
        xx_grid,
        yy_grid,
        np.transpose(albedo),
        cmap="viridis",
        shading="gouraud",
        norm=LogNorm(vmin=1e-4*np.amax(albedo), vmax=np.amax(albedo)),
    )

    cb = Colorbar(ax=ax4, mappable=fig, orientation="vertical", ticklocation="right")
    cb.ax.set_ylabel(
        "Single scattering albedo", rotation=270, labelpad=20, fontsize=11
    )

    fig = ax5.pcolormesh(
        xx_grid,
        yy_grid,
        np.transpose(opacity_cont_abs),
        cmap="viridis",
        shading="gouraud",
        norm=LogNorm(
            vmin=1e-6 * np.amax(opacity_cont_abs), vmax=np.amax(opacity_cont_abs)
        ),
    )

    cb = Colorbar(ax=ax7, mappable=fig, orientation="vertical", ticklocation="right")
    cb.ax.set_ylabel(
        "Continuum absorption (cm$^2$/g)", rotation=270, labelpad=20, fontsize=11
    )

    fig = ax6.pcolormesh(
        xx_grid,
        yy_grid,
        np.transpose(opacity_cont_scat),
        cmap="viridis",
        shading="gouraud",
        norm=LogNorm(
            vmin=1e-6 * np.amax(opacity_cont_scat), vmax=np.amax(opacity_cont_scat)
        ),
    )

    cb = Colorbar(ax=ax8, mappable=fig, orientation="vertical", ticklocation="right")
    cb.ax.set_ylabel(
        "Continuum scattering (cm$^2$/g)", rotation=270, labelpad=20, fontsize=11
    )

    ax1.set_ylabel("Pressure (bar)", fontsize=13)

    ax2.set_xlabel("Wavelength (µm)", fontsize=13)
    ax2.set_ylabel("Pressure (bar)", fontsize=13)

    ax5.set_ylabel("Pressure (bar)", fontsize=13)

    ax6.set_xlabel("Wavelength (µm)", fontsize=13)
    ax6.set_ylabel("Pressure (bar)", fontsize=13)

    ax1.set_xlim(wavelength[0], wavelength[-1])
    ax2.set_xlim(wavelength[0], wavelength[-1])

    ax5.set_xlim(wavelength[0], wavelength[-1])
    ax6.set_xlim(wavelength[0], wavelength[-1])

    ax1.set_ylim(
        radtrans.rt_object.press[-1] * 1e-6, radtrans.rt_object.press[0] * 1e-6
    )
    ax2.set_ylim(
        radtrans.rt_object.press[-1] * 1e-6, radtrans.rt_object.press[0] * 1e-6
    )

    ax5.set_ylim(
        radtrans.rt_object.press[-1] * 1e-6, radtrans.rt_object.press[0] * 1e-6
    )
    ax6.set_ylim(
        radtrans.rt_object.press[-1] * 1e-6, radtrans.rt_object.press[0] * 1e-6
    )

    if offset is not None:
        ax1.get_xaxis().set_label_coords(0.5, offset[0])
        ax1.get_yaxis().set_label_coords(offset[1], 0.5)

        ax2.get_xaxis().set_label_coords(0.5, offset[0])
        ax2.get_yaxis().set_label_coords(offset[1], 0.5)

        ax5.get_xaxis().set_label_coords(0.5, offset[0])
        ax5.get_yaxis().set_label_coords(offset[1], 0.5)

        ax6.get_xaxis().set_label_coords(0.5, offset[0])
        ax6.get_yaxis().set_label_coords(offset[1], 0.5)

    else:
        ax1.get_xaxis().set_label_coords(0.5, -0.1)
        ax1.get_yaxis().set_label_coords(-0.14, 0.5)

        ax2.get_xaxis().set_label_coords(0.5, -0.1)
        ax2.get_yaxis().set_label_coords(-0.14, 0.5)

        ax5.get_xaxis().set_label_coords(0.5, -0.1)
        ax5.get_yaxis().set_label_coords(-0.14, 0.5)

        ax6.get_xaxis().set_label_coords(0.5, -0.1)
        ax6.get_yaxis().set_label_coords(-0.14, 0.5)

    ax1.set_yscale("log")
    ax2.set_yscale("log")
    ax3.set_yscale("log")
    ax4.set_yscale("log")

    ax5.set_yscale("log")
    ax6.set_yscale("log")
    ax7.set_yscale("log")
    ax8.set_yscale("log")

    print(" [DONE]")

    if output is None:
        plt.show()
    else:
        plt.savefig(output, bbox_inches="tight")

    plt.clf()
    plt.close()
Beispiel #30
0
	def __call__(self, *args):
		v = LogNorm.__call__(self, *args)
		return 1.0 - v
Beispiel #31
0
def plot_NTCs_Vs_ROverZ(inputdata,axis,savename,truncation_curves=None,scaling=None):

    #Fill a 2D histogram per bunch-crossing with N_TCs (maximum over bundles) 

    #Each row represents the r/z bins in a bundle, there are n_bundles*n_events rows
    data = inputdata.reshape(-1,inputdata.shape[-1])

    #Swap axes, such that each row represents an r/z bin, there are n_roverz_bins rows (later flattened)
    data_swap = np.swapaxes(data,0,1)

    #Get the r/z bin axis indices, n_bundles*n_events*[0]+n_bundles*n_events*[1]+...n_bundles*n_events*[n_roverz_bins]
    axis_indices = np.where(data_swap==data_swap)[0]
    #Then get the roverz bin values corresponding to the indices
    roverz = np.take(axis,axis_indices)

    #Plot the 2D histogram
    pl.clf()
    pl.hist2d( roverz , data_swap.flatten() , bins = (len(axis)-1,50),range=[[0.076,0.58], [0, 50]],norm=LogNorm())
    pl.colorbar().set_label("Number of Events")
    #Plot the various 1D truncation curves
    colours = ['red','orange','cyan','green','teal','darkviolet']

    if ( truncation_curves is not None ):
        for t,truncation_option in enumerate(truncation_curves):
            scale = 1.
            if (scaling is not None):
                scale=scaling[t]
            plotted_truncation_curve = np.append(truncation_option,truncation_option[-1])/scale
            pl.step(axis,plotted_truncation_curve+1, where = 'post' , color=colours[t],linewidth='3')
            #plotted_truncation_curve+1 so that bin 'n' is visually included if the truncation value is 'n'
            #Note because of the geometric corrections the number of trigger cells might be fractional,
            #in which case the +1 is not correct (but only applies to the bins at low and high r/z)
            
    pl.xlabel('r/z')
    pl.ylabel('Number of TCs')
    pl.savefig( savename + ".png" )
    pl.clf()