Пример #1
0
                  xVarName='xaxis',
                  yVarName='yaxis',
                  meshName=inGridName)

outDescriptor = get_Antarctic_stereographic_comparison_descriptor(config)
outGridName = outDescriptor.meshName

outFileName = 'Rignot_2013_melt_rates_{}.nc'.format(outGridName)

mappingFileName = 'map_{}_to_{}.nc'.format(inGridName, outGridName)

remapper = Remapper(inDescriptor, outDescriptor, mappingFileName)

remapper.build_mapping_file(method='bilinear')

remappedDataset = remapper.remap(ds, renormalizationThreshold=0.01)

remappedDataset.attrs['history'] = ' '.join(sys.argv)
remappedDataset.to_netcdf(outFileName)

norm = colors.SymLogNorm(linthresh=1, linscale=1, vmin=-100.0, vmax=100.0)

plt.figure()
plt.imshow(maskedMeltRate, origin='upper', norm=norm)
plt.colorbar()
plt.figure()
plt.imshow(remappedDataset.meltRate.values, origin='lower', norm=norm)
plt.colorbar()

plt.show()
Пример #2
0
for filename, label in {{files_and_labels}}:
    data = np.loadtxt(filename)
    all_data.append(data)
all_data = np.vstack(all_data)

ax = plt.gca()
for x_pos, label in {{lines_and_labels}}:
    next_color = ax._get_lines.get_next_color()
    plt.axvline(x_pos, label=label, color=next_color)

fig = plt.gcf()

if {{log_scale}}:
    im = ax.imshow(all_data,
                   norm=colors.SymLogNorm(1.0,
                                          vmin=np.min(all_data),
                                          vmax=np.max(all_data)),
                   cmap='hot',
                   interpolation='nearest')
else:
    im = ax.imshow(all_data, cmap='hot', interpolation='nearest')
fig.colorbar(im)

plt.title('{{title}}')
plt.xlabel('{{xlabel}}')
plt.ylabel('{{ylabel}}')
plt.legend()

if args.dump_svg:
    # Save SVG in a fake file object.
    imgdata = BytesIO()
Пример #3
0
        plt.imshow([[1, 2], [3, np.nan]])
    assert len(warns) == 0


@image_comparison(baseline_images=['imshow_flatfield'],
                  remove_text=True,
                  style='mpl20',
                  extensions=['png'])
def test_imshow_flatfield():
    fig, ax = plt.subplots()
    im = ax.imshow(np.ones((5, 5)))
    im.set_clim(.5, 1.5)


@pytest.mark.parametrize("make_norm", [
    colors.Normalize, colors.LogNorm, lambda: colors.SymLogNorm(1),
    lambda: colors.PowerNorm(1)
])
@pytest.mark.filterwarnings("ignore:Attempting to set identical left==right")
def test_empty_imshow(make_norm):
    fig, ax = plt.subplots()
    im = ax.imshow([[]], norm=make_norm())
    im.set_extent([-5, 5, -5, 5])
    fig.canvas.draw()

    with pytest.raises(RuntimeError):
        im.make_image(fig._cachedRenderer)


def test_imshow_float128():
    fig, ax = plt.subplots()
Пример #4
0
                  remove_text=True, style='mpl20')
def test_imshow_bignumbers_real():
    rcParams['image.interpolation'] = 'nearest'
    # putting a big number in an array of integers shouldn't
    # ruin the dynamic range of the resolved bits.
    fig, ax = plt.subplots()
    img = np.array([[2., 1., 1.e22], [4., 1., 3.]])
    pc = ax.imshow(img)
    pc.set_clim(0, 5)


@pytest.mark.parametrize(
    "make_norm",
    [colors.Normalize,
     colors.LogNorm,
     lambda: colors.SymLogNorm(1),
     lambda: colors.PowerNorm(1)])
def test_empty_imshow(make_norm):
    fig, ax = plt.subplots()
    with pytest.warns(UserWarning,
                      match="Attempting to set identical left == right"):
        im = ax.imshow([[]], norm=make_norm())
    im.set_extent([-5, 5, -5, 5])
    fig.canvas.draw()

    with pytest.raises(RuntimeError):
        im.make_image(fig._cachedRenderer)


def test_imshow_float128():
    fig, ax = plt.subplots()
       title=r'$Q_o$ Variance',
       units=r'W$^2$ m$^{-4}$',
       cbfrac=cbfrac,
       cmap=sstcmap,
       vmin=varmin,
       vmax=varmax)
plt.savefig(fout +
            '{:s}_Qrvar_{:1.0f}LP_{:2.0f}Nto{:2.0f}N_detr{:s}.png'.format(
                dataname, Tn / 12., latbounds[0], latbounds[1],
                str(detr)[0]))
plt.close()

lvmin = -10**4
lvmax = 10**4
lognorm = colors.SymLogNorm(linthresh=0.03,
                            linscale=0.03,
                            vmin=lvmin,
                            vmax=lvmax)

mapper = Mapper()
mapper(covQsQo,
       bnds=bnds,
       log=False,
       norm=lognorm,
       title=r'$Q_s, Q_o$ Covariance',
       units=r'W$^2$ m$^{-4}$',
       cbfrac=cbfrac,
       cmap=sstcmap,
       vmin=-varmax,
       vmax=-varmin)
plt.savefig(fout +
            '{:s}_covQsQo_{:1.0f}LP_{:2.0f}Nto{:2.0f}N_detr{:s}.png'.format(
Пример #6
0
 def stPlot(self,
            col,
            cmapType="coolwarm",
            logOption=0,
            save=None,
            savePath=None,
            clim1=None,
            clim2=None,
            hLineCoords=[0, 1, 2],
            vLineCoords=None,
            xLabel=1,
            tStart=None,
            tEnd=None):
     print(self.path + ": making ST plot for column " + str(col))
     if savePath is None:
         savePath = self.path
     if tStart is None:
         plotData = self.data[col]
         tPlotMax = self.tmax
     else:
         tiStart = self.gettindex(tStart)
         tiEnd = self.gettindex(tEnd)
         plotData = self.data[col][tiStart:tiEnd]
         tPlotMax = tEnd - tStart
     title = self.header[col]
     if logOption == 1:
         plt.imshow(
             np.transpose(np.fliplr(plotData)),
             extent=[0, tPlotMax,
                     np.log10(self.rmin),
                     np.log10(self.rmax)],
             aspect=(80 * tPlotMax / (self.rmax - self.rmin)),
             cmap=plt.get_cmap(cmapType),
             norm=LogNorm(vmin=clim1, vmax=clim2))
     if logOption == 0:
         plt.imshow(
             np.transpose(np.fliplr(plotData)),
             extent=[0, tPlotMax,
                     np.log10(self.rmin),
                     np.log10(self.rmax)],
             aspect=(80 * tPlotMax / (self.rmax - self.rmin)),
             cmap=plt.get_cmap(cmapType))
     if logOption == 2:
         plotData = plotData / np.amax(np.abs(plotData))
         plt.imshow(
             np.transpose(np.fliplr(plotData)),
             extent=[0, tPlotMax,
                     np.log10(self.rmin),
                     np.log10(self.rmax)],
             aspect=(80 * tPlotMax / (self.rmax - self.rmin)),
             cmap=cmapType,
             norm=colors.SymLogNorm(linthresh=0.0001,
                                    linscale=0.1,
                                    vmin=-1.0,
                                    vmax=1.0))
     #plt.yscale('log')
     plt.title(title)
     if xLabel == 1: plt.xlabel("Time (code units)")
     plt.ylabel("log(r) (code units)")
     plt.colorbar(
         shrink=0.5
     )  #ticks=[-10^0, -10^-1, -10^-2, -10^-3, 10^-3, 10^-2, 10^-1, 10^0])
     if (clim1 is not None and clim2 is not None):
         plt.clim(clim1, clim2)
     if (clim1 is not None and clim2 is None):
         plt.clim(clim1, np.amax(plotData))
     if (clim1 is None and clim2 is not None):
         plt.clim(np.aminx(plotData), clim2)
     if vLineCoords is not None:
         for xc in vLineCoords:
             plt.axvline(x=xc, color='g', linestyle=':')
     for yc in hLineCoords:
         plt.axhline(y=yc, color='k', linestyle='--')
     plt.tight_layout()
     if save == "png":
         plt.savefig(savePath + "ST_" + str(col) + ".png",
                     bbox_inches='tight')
         print("saved ST plot for column " + str(col) + " to png")
     if save == "pdf":
         plt.savefig(self.pdfName, format='pdf', bbox_inches='tight')
         print("saved ST plot for column " + str(col) + " to pdf")
     plt.clf()
Пример #7
0
    def multiStPlot3(self,
                     tFlip,
                     savePath=None,
                     vLinesOn=True,
                     vLineCoords1=[50],
                     ti1=None,
                     ti2=None,
                     nameTag="_"):
        print(self.path + ": making multi pannel ST plot")
        if savePath is None:
            savePath = self.path

        f, axArray = plt.subplots(4, sharex=True)

        lumRangeLogY = np.log10(np.amax(self.lum) / np.amin(self.lum))
        rangeX = self.tmax

        if ti1 is None: ti1 = 0
        if ti2 is None: ti2 = self.nt - 1

        thisNt = ti2 - ti1

        #aspect1 = 0.87 *(thisNt)/self.nr
        aspect1 = (2.0 * 15.3) * (self.t[ti2] - self.t[ti1]) / self.nr
        #aspect1 = 2.28 * (self.tmax / 30.0) * ((ti2-ti1)/ti2)

        col = 12
        axNum = 0
        title = self.header[col]
        plotData = self.data[col][ti1:ti2]
        plotData = plotData / np.amax(np.abs(plotData))
        axArray[axNum].imshow(np.transpose(np.fliplr(plotData)),
                              extent=[
                                  self.t[ti1], self.t[ti2 - 1],
                                  np.log10(self.rmin),
                                  np.log10(self.rmax)
                              ],
                              aspect=aspect1,
                              cmap='coolwarm',
                              norm=colors.SymLogNorm(linthresh=0.001,
                                                     linscale=0.5,
                                                     vmin=-1.0,
                                                     vmax=1.0))
        #, vmin=-1.0, vmax=1.0
        axArray[axNum].text(1.02,
                            0.5,
                            title,
                            fontsize=14,
                            transform=axArray[axNum].transAxes)
        axArray[axNum].set_ylabel("log(r) (AU)")
        axArray[axNum].set_yticks([-1, 0])

        col = 0
        axNum = 1
        title = self.header[col]
        plotData = self.data[col][ti1:ti2]
        axArray[axNum].imshow(np.transpose(np.fliplr(plotData)),
                              extent=[
                                  self.t[ti1], self.t[ti2 - 1],
                                  np.log10(self.rmin),
                                  np.log10(self.rmax)
                              ],
                              aspect=aspect1,
                              cmap='viridis',
                              norm=LogNorm())
        axArray[axNum].text(1.02,
                            0.5,
                            title,
                            fontsize=14,
                            transform=axArray[axNum].transAxes)
        axArray[axNum].set_ylabel("log(r) (AU)")
        axArray[axNum].set_yticks([-1, 0])

        col = 9
        axNum = 2
        title = self.header[col]
        plotData = self.data[col][ti1:ti2]
        axArray[axNum].imshow(np.transpose(np.fliplr(plotData)),
                              extent=[
                                  self.t[ti1], self.t[ti2 - 1],
                                  np.log10(self.rmin),
                                  np.log10(self.rmax)
                              ],
                              aspect=aspect1,
                              cmap='viridis',
                              norm=LogNorm())
        axArray[axNum].text(1.02,
                            0.5,
                            title,
                            fontsize=14,
                            transform=axArray[axNum].transAxes)
        axArray[axNum].set_ylabel("log(r) (AU)")
        axArray[axNum].set_yticks([-1, 0])

        axNum = 3
        title = "L"
        axArray[axNum].semilogy(self.t[ti1:ti2], self.lum[ti1:ti2])
        axArray[axNum].set_ylabel(title)
        axArray[axNum].set_xlim([self.t[ti1], self.t[ti2 - 1]])
        maxLog = np.log10(
            1.1 * np.amax(np.abs(self.lum[int((ti2 + ti1) * 0.0):ti2])))
        minLog = np.log10(
            0.9 * np.amin(np.abs(self.lum[int((ti2 + ti1) * 0.0):ti2])))
        axArray[axNum].set_ylim([np.power(10, minLog), np.power(10, maxLog)])
        axArray[axNum].set_xlabel("time (years)")

        tickVals = []
        for i in range(-5, 6):
            if minLog < i < maxLog:
                tickVals.append(np.power(10.0, i))
        axArray[axNum].set_yticks(tickVals)

        vLineCoords1 = np.zeros(int(1 + (self.tmax - tWait) / (2.0 * tFlip)))
        i = 0
        while i < len(vLineCoords1):
            vLineCoords1[i] = tWait + 2 * i * tFlip
            i = i + 1
        hLineCoords1 = np.asarray([-1])

        if vLinesOn is True:
            for axNum in np.arange(len(axArray)):
                for xc in vLineCoords1:
                    axArray[axNum].axvline(x=xc, color='r', linestyle=':')
                    axArray[axNum].axvline(x=xc + tFlip * 1.0,
                                           color='b',
                                           linestyle=':')
                    axArray[axNum].axvline(x=xc + tFlip * 0.5,
                                           color='k',
                                           linestyle=':')
                    axArray[axNum].axvline(x=xc + tFlip * 1.5,
                                           color='k',
                                           linestyle=':')
        #for axNum in [0,1,2]:
        #for yc in hLineCoords1:
        #axArray[axNum].axhline(y=yc, color='k')

        plt.savefig(savePath + "MST3" + nameTag + ".png",
                    bbox_inches='tight',
                    dpi=600)
        print("saved MST plot to png")
        plt.clf()
fig = plt.figure(figsize=(20, 20))
ax = fig.add_subplot(projection=WCS(hdr_plot), slices=('x', 'y', 1))
ax.update({
    'title': r'{} galaxy, $H\alpha$ flux'.format(obj),
    'xlabel': r'RA',
    'ylabel': r'DEC'
})

halpha_cmap = cm.gray
halpha_cmap.set_under(background_color)
im = ax.imshow(flux6563_image,
               interpolation='bicubic',
               cmap=halpha_cmap,
               norm=colors.SymLogNorm(linthresh=flux6563_levels[-2],
                                      vmin=flux6563_levels[-3],
                                      base=10))
# plt.savefig(folder/'muse_CGCG007_Halpha.png', resolution=300, bbox_inches='tight')
plt.show()

# region_idcs = np.array([0, 1, 2, 3, 4])
# for idx in region_idcs:
#
#     mask_label = f'region_{idx}'
#     mask_array = fits.getdata(db_addresss, mask_label, ver=1)
#
#     flux_Image = np.ma.masked_array(flux6563_image, mask=mask_array)
#
#     fig = plt.figure(figsize=(12, 8))
#     ax = fig.add_subplot(projection=WCS(hdr_plot), slices=('x', 'y', 1))
#     ax.update({'title': r'{} galaxy, {}, $H\alpha$ flux'.format(obj, mask_label), 'xlabel': r'RA', 'ylabel': r'DEC'})
Пример #9
0
#!/usr/bin/env python3

from matplotlib import use
use('agg')

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mplc
from matplotlib import cm
import sys
import os
from astropy.io import fits

hdu = fits.open(sys.argv[1])[0]
d = hdu.data

fig, ax = plt.subplots(1, 1, figsize=(5, 5))

vmin = d.min()
vmax = d.max()
norm = mplc.SymLogNorm(1e-9, vmin=vmin, vmax=vmax)
img = ax.imshow(d, norm=norm)
plt.colorbar(img, ax=ax, shrink=0.8)

fig.savefig(sys.argv[1][:-4] + 'png')
Пример #10
0
import matplotlib.pyplot as plt
from matplotlib import colors

# Loading a sample dataset
counts, lengths, cnv = datasets.load_sample_cancer()

normed = normalization.ICE_normalization(counts, counts_profile=cnv)

# Plotting the results using matplotlib
chromosomes = ["I", "II", "III", "IV", "V", "VI"]

fig, axes = plt.subplots(ncols=2, figsize=(12, 4))

axes[0].imshow(counts,
               cmap="RdBu_r",
               norm=colors.SymLogNorm(1),
               extent=(0, len(counts), 0, len(counts)))

[axes[0].axhline(i, linewidth=1, color="#000000") for i in lengths.cumsum()]
[axes[0].axvline(i, linewidth=1, color="#000000") for i in lengths.cumsum()]
axes[0].set_title("Raw contact counts", fontweight="bold")

m = axes[1].imshow(normed,
                   cmap="RdBu_r",
                   norm=colors.SymLogNorm(1),
                   extent=(0, len(counts), 0, len(counts)))
[axes[1].axhline(i, linewidth=1, color="#000000") for i in lengths.cumsum()]
[axes[1].axvline(i, linewidth=1, color="#000000") for i in lengths.cumsum()]
cb = fig.colorbar(m)
axes[1].set_title("Normalized contact counts with LOIC", fontweight="bold")
Пример #11
0
    for i, percentile in enumerate(levelContours):
        print(f'{i}, Level P({pertil_array[i]}) = {percentile} flux')

    maFlux_image = np.ma.masked_where(
        (flux_image >= levelContours[-5]) & (flux_image < levelContours[-4]),
        flux_image)

    fig = plt.figure(figsize=(12, 8))
    ax = fig.add_subplot(projection=WCS(cube.data_header),
                         slices=('x', 'y', 1))
    # im = ax.imshow(flux_image, vmin=0, interpolation='none')
    # im = ax.imshow(flux_image, cmap=cm.gray, norm=colors.SymLogNorm(linthresh=levelContours[1], vmin=levelContours[1], base=10))
    im = ax.imshow(maFlux_image,
                   cmap=cm.gray,
                   norm=colors.SymLogNorm(linthresh=levelContours[1],
                                          vmin=levelContours[1],
                                          base=10))
    # im = ax.imshow(flux_image, cmap=cm.gray, norm=colors.SymLogNorm(linthresh=levelContours[1], vmin=levelContours[2]))
    ax.contour(flux_image, levels=[levelContours[-5]], colors='red', alpha=0.5)

    # cbar = fig.colorbar(im, ticks=levelContours)
    print(levelContours[2:6])
    ax.set_title(f'Galaxy {obj} {lineLabel}')
    plt.show()

    # Image with a clear display of the galaxy features
    # lineLabel = 'H1_6563A'
    # lineLimits = lineAreas[lineLabel]
    #
    # # This requires the input wavelengths to be on the same scale as in the cube
    # line_image = cube.get_image(np.array(lineLimits) * (1 + z_objs[i]), subtract_off=True)
Пример #12
0
    def setup(
            self,
            image,
            ok=None,
            xaxis=None,
            yaxis=None,
            title='',  # title to go over the top of the plot
            figsize=(8, 4),  # kwargs for figure,
            dpi=100,
            hspace=0,
            wspace=0,  # kwargs for gridspec
            left=0.05,
            right=0.95,
            bottom=0.05,
            top=0.95,
            width_ratios=[1.0, 0.1],
            height_ratios=[0.1, 1.0],
            initialcrosshairs=[0.0, 0.0],  # where the crosshairs should start
            aspect='equal',  # kwargs for imshow
            vmin=None,
            vmax=None,
            scale='symlog',  # make a default that can be edited interactively (in Mask.py)
            labelfontsize=5,
            datacolor='darkorange',
            crosshaircolor='darkorange',
            **kwargs):
        '''
        Initialize the loupe
        (this has a pretty big overhead,
        so use "updateImage" if you can to update
        the data being displayed)
        '''

        self.ok = ok
        self.image = image
        # set the image
        if xaxis is not None:
            self.xaxis = xaxis
        else:
            xsize = self.imagetoplot.shape[1]
            self.xaxis = np.arange(xsize)
        if yaxis is not None:
            self.yaxis = yaxis
        else:
            ysize = self.imagetoplot.shape[0]
            self.yaxis = np.arange(ysize)

        self.dx = np.median(np.diff(self.xaxis))
        self.dy = np.median(np.diff(self.yaxis))

        self.speak('setting up loupe')

        # keep track of where the crosshair is pointing
        self.crosshair = dict(x=initialcrosshairs[0], y=initialcrosshairs[1])

        # set up the figure
        plt.ion()
        self.figure = plt.figure(figsize=figsize, dpi=dpi)
        # create an interactive plot
        self.iplot = iplot(2,
                           2,
                           hspace=hspace,
                           wspace=wspace,
                           left=left,
                           right=right,
                           bottom=bottom,
                           top=top,
                           width_ratios=width_ratios,
                           height_ratios=height_ratios)

        # a dictionary to store the axes objects
        self.ax = {}

        # for displaying the 2D image
        labelkw = dict(fontsize=labelfontsize)
        self.ax['2d'] = self.iplot.subplot(1, 0)
        plt.setp(self.ax['2d'].get_xticklabels(), **labelkw)
        plt.setp(self.ax['2d'].get_yticklabels(), **labelkw)

        # for displaying cuts along the dispersion direction
        self.ax['slicex'] = self.iplot.subplot(0, 0, sharex=self.ax['2d'])
        self.ax['slicex'].set_title(title, fontsize=8)
        plt.setp(self.ax['slicex'].get_xticklabels(), visible=False)
        plt.setp(self.ax['slicex'].get_yticklabels(), **labelkw)

        # for display cuts along the cross-dispersion direction
        self.ax['slicey'] = self.iplot.subplot(1, 1, sharey=self.ax['2d'])
        self.ax['slicey'].xaxis.tick_top()
        self.ax['slicey'].xaxis.set_label_position('top')
        plt.setp(self.ax['slicey'].get_xticklabels(), rotation=270, **labelkw)
        plt.setp(self.ax['slicey'].get_yticklabels(), visible=False)

        # set the limits of the plot
        ok = np.isfinite(self.imagetoplot)
        #self.vmin, self.vmax = np.percentile(self.imagetoplot[ok], [0,100])

        # pick a scale for the plotting
        if scale == 'symlog':
            norm = colors.SymLogNorm(linthresh=craftroom.oned.mad(
                self.imagetoplot),
                                     linscale=0.1,
                                     vmin=vmin,
                                     vmax=vmax)
        else:
            norm = None

        self.extent = [
            np.min(self.xaxis),
            np.max(self.xaxis),
            np.min(self.yaxis),
            np.max(self.yaxis)
        ]

        self.plotted = {}
        # plot the image
        self.plotted['2d'] = self.ax['2d'].imshow(self.imagetoplot,
                                                  cmap='gray',
                                                  extent=self.extent,
                                                  interpolation='nearest',
                                                  aspect=aspect,
                                                  zorder=0,
                                                  origin='lower',
                                                  norm=norm)

        # set the x and y limits
        self.ax['2d'].set_xlim(self.extent[0:2])
        self.ax['2d'].set_ylim(self.extent[2:4])

        # add crosshair
        crosskw = dict(alpha=0.5, color=crosshaircolor, linewidth=1)
        self.plotted['crossy'] = self.ax['2d'].axvline(self.crosshair['x'],
                                                       **crosskw)
        self.plotted['crossyextend'] = self.ax['slicex'].axvline(
            self.crosshair['x'], linestyle='--', **crosskw)
        self.plotted['crossx'] = self.ax['2d'].axhline(self.crosshair['y'],
                                                       **crosskw)
        self.plotted['crossxextend'] = self.ax['slicey'].axhline(
            self.crosshair['y'], linestyle='--', **crosskw)
        # plot slicey
        slicekw = dict(color=datacolor, linewidth=1)

        badalpha = 0.15
        h, v = self.slicey
        ok = self.ok_slicey
        self.plotted['slicey'] = self.ax['slicey'].plot(
            h[ok], v[ok], **slicekw)[0]
        self.plotted['slicey_bad'] = self.ax['slicey'].plot(h[ok == False],
                                                            v[ok == False],
                                                            alpha=badalpha,
                                                            **slicekw)[0]

        h, v = self.slicex
        ok = self.ok_slicex
        self.plotted['slicex'] = self.ax['slicex'].plot(
            h[ok], v[ok], **slicekw)[0]
        self.plotted['slicex_bad'] = self.ax['slicex'].plot(h[ok == False],
                                                            v[ok == False],
                                                            alpha=badalpha,
                                                            **slicekw)[0]

        # set the limits of the color scale and the plots
        for a in self.ax.values():
            a.set_autoscaley_on(False)
        self.set_limits(vmin, vmax)
Пример #13
0
def plotImage(pattern,
              logscale=True,
              offset=None,
              symlog=False,
              figsize=None,
              ax=None,
              fn_png=None,
              *argv,
              **kwargs):
    """ Workhorse function to plot an image.

    :param logscale: Whether to show the data on logarithmic scale (z axis), defaults to `True`.
    :type logscale: bool
    :param offset: Offset to apply to the pattern.
    :type offset: float
    :param symlog: To show the data on symlogarithmic scale (z axis), defaults to `False`.
    :type symlog: bool
    :param fn_png: The name of the output png file, defaults to `None`.
    :type fn_png: str

    :return: The axes class instance of the plot.
    :rtype: ``matplotlib.axes``
    """
    if ax is None:
        fig, ax = plt.subplots(figsize=figsize)
    # Get limits.
    mn, mx = pattern.min(), pattern.max()

    x_range, y_range = pattern.shape

    if offset:
        mn = pattern.min() + offset
        mx = pattern.max() + offset
        pattern = pattern.astype(float) + offset

    if (logscale and symlog):
        print('logscale and symlog are both true.\noverrided by logscale')

    if 0 in pattern and not offset and (logscale or symlog):
        print(
            'Warnning: zero-value detected. Please set a small offset (e.g. 1e-3) to get correct log display.'
        )

    if (logscale or symlog):
        kwargs['cmap'] = kwargs.pop('cmap', "viridis")
        # default plot setup
        if logscale:
            kwargs['norm'] = kwargs.pop('norm', colors.LogNorm())
        elif symlog:
            kwargs['norm'] = kwargs.pop('norm', colors.SymLogNorm(0.015))
        kwargs.pop('axes', None)
    else:
        kwargs['norm'] = kwargs.pop('norm', colors.Normalize(vmin=mn, vmax=mx))
        kwargs['cmap'] = kwargs.pop('cmap', "viridis")
    ax = plt.imshow(pattern, *argv, **kwargs)

    plt.xlabel(r'$x$ (pixel)')
    plt.ylabel(r'$y$ (pixel)')
    plt.xlim([0, x_range - 1])
    plt.ylim([0, y_range - 1])
    plt.tight_layout()
    plt.colorbar()
    if fn_png:
        plt.savefig(fn_png, dpi=300)
    return ax
Пример #14
0
def spectrogram(audiofile, samplerate=0):
    win_s = 512  # fft window size
    hop_s = win_s // 2  # hop size
    fft_s = win_s // 2 + 1  # spectrum bins

    audio_data = aubio.source(audiofile, samplerate, hop_s)  # source file
    if samplerate == 0:
        samplerate = audio_data.samplerate
    pv = aubio.pvoc(win_s, hop_s)  # phase vocoder
    specgram = np.zeros(
        [0, fft_s], dtype=aubio.float_type)  # numpy array to store spectrogram

    # analysis
    while True:
        samples, read = audio_data()  # read file
        specgram = np.vstack(
            (specgram, pv(samples).norm))  # store new norm vector
        if read < audio_data.hop_size: break

    # plotting
    #fig = plt.imshow(log10(specgram.T + .001), origin = 'bottom', aspect = 'auto', cmap=plt.cm.gray_r)
    #fig = plt.imshow(log10(specgram.T + .001), origin = 'bottom', aspect = 'auto', cmap=plt.cm.gray_r)

    plt.figure(figsize=(15, 10))
    fig = plt.imshow(np.log10(specgram.T + .001),
                     origin='bottom',
                     aspect='auto',
                     cmap=plt.cm.gray_r)

    #print dir(plt.cm)

    #fig = plt.imshow(log10(specgram.T + .001), origin = 'bottom', size=800)
    #plt.pcolormesh(t, f, Sxx)
    #plt.pcolormesh(specgram.T)

    #print dir(colors)

    #norm = colors.LogNorm(vmin=specgram.T.min(), vmax=specgram.T.max())
    #norm = colors.LogNorm(vmin=specgram.min(), vmax=specgram.max())

    #norm = colors.SymLogNorm(linthresh=0.03, linscale=0.03, vmin=specgram.min(), vmax=specgram.max())
    norm = colors.SymLogNorm(linthresh=0.08,
                             linscale=0.1,
                             vmin=specgram.min(),
                             vmax=specgram.max())

    #bounds = np.linspace(-1, 1, 10)
    #norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)

    #norm = colors.PowerNorm(gamma=1./2.)
    #norm = colors.PowerNorm(gamma=0.25)

    #plt.pcolormesh(specgram.T, norm=norm, cmap='PuBu_r')
    #plt.pcolormesh(specgram.T, norm=norm, cmap='PuBu_r')

    #plt.pcolormesh(specgram.T, norm=norm, cmap='RdBu_r')
    #plt.pcolormesh(specgram.T, norm=norm, cmap='RdBu')

    #plt.pcolormesh(specgram.T, norm=norm, cmap='gnuplot2')
    plt.pcolormesh(specgram.T, norm=norm, cmap='inferno')
    #plt.pcolormesh(specgram.T, norm=norm, cmap='hot_r')
    #plt.pcolormesh(specgram.T, norm=norm, cmap='copper')
    #plt.pcolormesh(specgram.T, norm=norm, cmap='seismic')

    ax = fig.axes
    ax.axis([0, len(specgram), 0, len(specgram[0])])

    # show axes in Hz and seconds
    time_step = hop_s / float(samplerate)
    total_time = len(specgram) * time_step
    outstr = "total time: %0.2fs" % total_time
    print(outstr + ", samplerate: %.2fkHz" % (samplerate / 1000.0))
    n_xticks = 10
    n_yticks = 10

    def get_rounded_ticks(top_pos, step, n_ticks):
        top_label = top_pos * step
        # get the first label
        ticks_first_label = top_pos * step / n_ticks
        # round to the closest .1
        ticks_first_label = round(ticks_first_label * 10.0) / 10.0
        # compute all labels from the first rounded one
        ticks_labels = [ticks_first_label * n
                        for n in range(n_ticks)] + [top_label]
        # get the corresponding positions
        ticks_positions = [ticks_labels[n] / step
                           for n in range(n_ticks)] + [top_pos]
        # convert to string
        #ticks_labels = [  "%.1f" % x for x in ticks_labels ]
        ticks_labels = ["%i" % x for x in ticks_labels]
        # return position, label tuple to use with x/yticks
        return ticks_positions, ticks_labels

    # apply to the axis
    x_ticks, x_labels = get_rounded_ticks(len(specgram), time_step, n_xticks)
    ax.set_xticks(x_ticks)
    ax.set_xticklabels(x_labels)

    #y_ticks, y_labels = get_rounded_ticks(len(specgram[0]), (samplerate / 1000. / 2.) / len(specgram[0]), n_yticks)
    y_ticks, y_labels = get_rounded_ticks(len(
        specgram[0]), (samplerate / 2.0) / len(specgram[0]), n_yticks)
    #y_ticks, y_labels = get_rounded_ticks(len(specgram[0]), 1, n_yticks)
    ax.set_yticks(y_ticks)
    ax.set_yticklabels(y_labels)
    #ax.set_yticks(range(0, 3150, 100))
    #print len(specgram), len(specgram[0]), max(specgram[0])
    #plt.yticks(range(0, 3151, 100))

    ax.set_ylabel('Frequency (Hz)')
    ax.set_xlabel('Time (s)')
    ax.set_title(os.path.basename(audiofile))
    for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
                 ax.get_xticklabels() + ax.get_yticklabels()):
        item.set_fontsize('x-small')

    #return fig

    tmpfile = NamedTemporaryFile(suffix='.png', delete=False)
    plt.savefig(tmpfile.name)
    #plt.show()

    return tmpfile.name
Пример #15
0
def main(ssh=False, labelfontsize=12, ticksize=11):
    plot_path = "../../Plots/Analytic_Covariance/"
    u_range = numpy.logspace(0, numpy.log10(500), 100)

    # 100 frequency channels is fine for now, maybe later do a higher number to push up the k_par range
    frequency_range = numpy.linspace(135, 165, 251) * 1e6

    eta, sky_only_raw, sky_only_cal = residual_ps_error(u_range,
                                                        frequency_range,
                                                        residuals='sky')
    eta, sky_and_beam_raw, sky_and_beam_cal = residual_ps_error(
        u_range, frequency_range, residuals='both')
    difference_cal = sky_and_beam_cal - sky_only_cal

    fiducial_ps = fiducial_eor(u_range, eta)

    figure, axes = pyplot.subplots(1, 3, figsize=(15, 5))

    ps_norm = colors.LogNorm(vmin=1e2, vmax=1e15)
    plot_power_spectrum(u_range,
                        eta,
                        frequency_range,
                        sky_and_beam_cal,
                        title=r"$\mathbf{C}_{r}$(sky + beam)",
                        axes=axes[0],
                        axes_label_font=labelfontsize,
                        tickfontsize=ticksize,
                        norm=ps_norm,
                        xlabel_show=True,
                        colorbar_show=True)

    diff_norm = colors.SymLogNorm(linthresh=1e2,
                                  linscale=1.5,
                                  vmin=-1e15,
                                  vmax=1e15)
    plot_power_spectrum(
        u_range,
        eta,
        frequency_range,
        difference_cal,
        axes=axes[1],
        axes_label_font=labelfontsize,
        tickfontsize=ticksize,
        norm=diff_norm,
        colorbar_show=True,
        xlabel_show=True,
        title=r"$\mathbf{C}_{r}$(sky + beam) - $\mathbf{C}_{r}$(sky) ",
        diff=True,
        colormap='coolwarm')

    ratio_norm = colors.SymLogNorm(linthresh=1e1,
                                   linscale=1,
                                   vmin=-1e1,
                                   vmax=1e5)
    plot_power_spectrum(
        u_range,
        eta,
        frequency_range,
        difference_cal / fiducial_ps,
        axes=axes[2],
        axes_label_font=labelfontsize,
        tickfontsize=ticksize,
        norm=ratio_norm,
        colorbar_show=True,
        xlabel_show=True,
        z_label="Difference Ratio",
        title=
        r"$(\mathbf{C}_{r}$(sky + beam) - $\mathbf{C}_{r}$(sky))/$\mathbf{C}_{s}$ ",
        diff=True)

    figure.tight_layout()
    figure.savefig(plot_path +
                   "Comparing_Sky_and_Beam_Errors_Post_Calibration.pdf")
    if not ssh:
        pyplot.show()
    return
Пример #16
0
# make test data
data = np.array([[random.randint(0, 100) for row in range(66)]
                 for column in range(4)])
for row in [0, 61]:
    for column in [0, 2]:
        data_tmp = random.randint(0, 100)
        data[column][row:row + 5] = data_tmp
        data[column + 1][row:row + 5] = data_tmp
for row in range(5, 61, 7):
    for column in [0, 3]:
        data[column][row:row + 7] = random.randint(0, 100)
print('data:', data)

# make log scale colorbar
norm = mcolors.SymLogNorm(linthresh=1, vmin=0, vmax=data.max() * 10)
# plot imshow and colorbar
image_imshow = ax.imshow(data, cmap="viridis", aspect='auto', norm=norm)
fig.colorbar(image_imshow, orientation='horizontal')

# hide ticks and it's label
ax.set_xticks([])
ax.set_yticks([])
ax.xaxis.set_ticklabels([])
ax.yaxis.set_ticklabels([])

# overlay rectangular area on plot
for x in range(5, 61):
    for y in range(2):
        center_area = plt.Rectangle(
            # (x,y) of upper left corner, width, hight
Пример #17
0
    def multiStPlot2(self, tFlip, savePath=None):
        print(self.path + ": making multi pannel ST plot")
        if savePath is None:
            savePath = self.path

        f, axArray = plt.subplots(6, sharex=True)

        lumRangeLogY = np.log10(np.amax(self.lum) / np.amin(self.lum))
        rangeX = self.tmax

        #self.lum[800] = self.lum[800]*10

        #ti1 = 3000
        #ti2 = 4000
        ti1 = 0
        ti2 = self.nt

        #aspect1 = 1.65 * (30.0 / self.tmax)
        aspect1 = 1.49 * (self.tmax / 30.0) * ((ti2 - ti1) / ti2)

        col = 12
        axNum = 0
        title = self.header[col]
        plotData = self.data[col][ti1:ti2]
        plotData = plotData / np.amax(np.abs(plotData))
        axArray[axNum].imshow(np.transpose(np.fliplr(plotData)),
                              extent=[
                                  self.t[ti1], self.t[ti2 - 1],
                                  np.log10(self.rmin),
                                  np.log10(self.rmax)
                              ],
                              aspect=aspect1,
                              cmap='coolwarm',
                              norm=colors.SymLogNorm(linthresh=0.0001,
                                                     linscale=0.1,
                                                     vmin=-1.0,
                                                     vmax=1.0))
        axArray[axNum].text(1.02,
                            0.5,
                            title,
                            fontsize=14,
                            transform=axArray[axNum].transAxes)
        axArray[axNum].set_ylabel("log(r)")
        axArray[axNum].set_yticks([-1, 0])

        col = 0
        axNum = 1
        title = self.header[col]
        plotData = self.data[col][ti1:ti2]
        axArray[axNum].imshow(np.transpose(np.fliplr(plotData)),
                              extent=[
                                  self.t[ti1], self.t[ti2 - 1],
                                  np.log10(self.rmin),
                                  np.log10(self.rmax)
                              ],
                              aspect=aspect1,
                              cmap='viridis',
                              norm=LogNorm())
        axArray[axNum].text(1.02,
                            0.5,
                            title,
                            fontsize=14,
                            transform=axArray[axNum].transAxes)
        axArray[axNum].set_ylabel("log(r)")
        axArray[axNum].set_yticks([-1, 0])

        col = 15
        axNum = 2
        title = self.header[col]
        plotData = self.data[col][ti1:ti2]
        axArray[axNum].imshow(np.transpose(np.fliplr(plotData)),
                              extent=[
                                  self.t[ti1], self.t[ti2 - 1],
                                  np.log10(self.rmin),
                                  np.log10(self.rmax)
                              ],
                              aspect=aspect1,
                              cmap='viridis',
                              norm=LogNorm())
        axArray[axNum].text(1.02,
                            0.5,
                            title,
                            fontsize=14,
                            transform=axArray[axNum].transAxes)
        axArray[axNum].set_ylabel("log(r)")
        axArray[axNum].set_yticks([-1, 0])

        col = 2
        axNum = 3
        title = self.header[col]
        plotData = np.power(self.data[col][ti1:ti2], 1.0)
        axArray[axNum].imshow(np.transpose(np.fliplr(plotData)),
                              extent=[
                                  self.t[ti1], self.t[ti2 - 1],
                                  np.log10(self.rmin),
                                  np.log10(self.rmax)
                              ],
                              aspect=aspect1,
                              cmap='viridis',
                              norm=LogNorm())
        axArray[axNum].text(1.02,
                            0.5,
                            title,
                            fontsize=14,
                            transform=axArray[axNum].transAxes)
        axArray[axNum].set_ylabel("log(r)")
        axArray[axNum].set_yticks([-1, 0])

        axNum = 4
        title = "L"
        axArray[axNum].semilogy(self.t[ti1:ti2], self.lum[ti1:ti2])
        axArray[axNum].set_ylabel(title)
        axArray[axNum].set_xlim([self.t[ti1], self.t[ti2 - 1]])
        maxLog = np.log10(
            1.1 * np.amax(np.abs(self.lum[int((ti2 + ti1) * 0.0):ti2])))
        minLog = np.log10(
            0.9 * np.amin(np.abs(self.lum[int((ti2 + ti1) * 0.0):ti2])))
        axArray[axNum].set_ylim([np.power(10, minLog), np.power(10, maxLog)])

        tickVals = []
        for i in range(-5, 6):
            if minLog < i < maxLog:
                tickVals.append(np.power(50.0, i))
        axArray[axNum].set_yticks(tickVals)

        axNum = 5
        title = self.header[9]
        plotData = self.data[9][ti1:ti2,
                                10] / self.data[9][self.gettindex(tWait), 10]
        axArray[axNum].semilogy(self.t[ti1:ti2], plotData)
        axArray[axNum].set_ylabel(title)
        axArray[axNum].set_xlim([self.t[ti1], self.t[ti2 - 1]])
        axArray[axNum].set_xlabel("Time")
        maxLog = np.log10(
            1.1 * np.amax(np.abs(plotData[int((ti2 + ti1) * 0.0):ti2])))
        minLog = np.log10(
            0.9 * np.amin(np.abs(plotData[int((ti2 + ti1) * 0.0):ti2])))
        axArray[axNum].set_ylim([np.power(10, minLog), np.power(10, maxLog)])
        tickVals = []
        for i in range(-5, 6):
            if minLog < i < maxLog:
                tickVals.append(np.power(10.0, i))
        axArray[axNum].set_yticks(tickVals)

        #vLineCoords1 = np.zeros(int(1+(self.tmax-50.0)/(2.0*tFlip)))
        #i=0
        #while i < len(vLineCoords1):
        #vLineCoords1[i] = 50.0 + 2*i*tFlip
        #i = i+1
        #hLineCoords1 = np.asarray([-1])

        #if self.data[12][self.gettindex(50.0), 5] > self.data[12][self.gettindex(10.5), 5]:
        #	color1 = 'b'
        #	color2 = 'r'
        #else:
        #	color1 = 'r'
        #	color2 = 'b'

        #for axNum in np.arange(len(axArray)):
        #	for xc in vLineCoords1:
        #		axArray[axNum].axvline(x=xc, color=color1, linestyle=':')
        #		axArray[axNum].axvline(x=xc+tFlip, color=color2, linestyle=':')
        #for axNum in [0,1,2]:
        #for yc in hLineCoords1:
        #axArray[axNum].axhline(y=yc, color='k')

        plt.savefig(savePath + "MST2.png", bbox_inches='tight', dpi=600)
        print("saved MST plot to png")
        plt.clf()
Пример #18
0
from matplotlib import colors

from iced import datasets
from iced.utils import get_intra_mask
from iced.utils import get_inter_mask


# Loading a sample dataset
counts, lengths = datasets.load_sample_yeast()
intra_mask = get_intra_mask(lengths)
inter_mask = get_inter_mask(lengths)

fig, axes = plt.subplots(ncols=2, figsize=(12, 6))
inter_counts = counts.copy()
inter_counts[intra_mask] = np.nan
intra_counts = counts.copy()
intra_counts[inter_mask] = np.nan

m = axes[0].matshow(intra_counts, cmap="Blues", norm=colors.SymLogNorm(1),
                    extent=(0, len(counts), 0, len(counts)))
m = axes[1].matshow(inter_counts, cmap="Blues", norm=colors.SymLogNorm(1),
                    extent=(0, len(counts), 0, len(counts)))

axes[0].set_title("Intra-chromosomal maps")
axes[1].set_title("Inter-chromosomal maps")

[axes[0].axhline(i, linewidth=1, color="#000000") for i in lengths.cumsum()]
[axes[0].axvline(i, linewidth=1, color="#000000") for i in lengths.cumsum()]
[axes[1].axhline(i, linewidth=1, color="#000000") for i in lengths.cumsum()]
[axes[1].axvline(i, linewidth=1, color="#000000") for i in lengths.cumsum()]
Пример #19
0
    def multiStPlot1cbar(self,
                         tFlip,
                         savePath=None,
                         vLinesOn=True,
                         vLineCoords1=[50],
                         ti1=None,
                         ti2=None,
                         nameTag="_"):
        print(self.path + ": making multi pannel ST plot")
        if savePath is None:
            savePath = self.path

        #f, axArray = plt.subplots(4, sharex=True)

        lumRangeLogY = np.log10(np.amax(self.lum) / np.amin(self.lum))
        rangeX = self.tmax

        if ti1 is None: ti1 = 0
        if ti2 is None: ti2 = self.nt - 1

        thisNt = ti2 - ti1

        #aspect1 = 0.87 *(thisNt)/self.nr
        aspect1 = 15.3 * (self.t[ti2] - self.t[ti1]) / self.nr
        #aspect1 = 2.28 * (self.tmax / 30.0) * ((ti2-ti1)/ti2)

        col = 12
        axNum = 0
        title = self.header[col]
        plotData = self.data[col][ti1:ti2]
        plotData = plotData / np.amax(np.abs(plotData))
        plt.imshow(np.transpose(np.fliplr(plotData)),
                   extent=[
                       self.t[ti1], self.t[ti2 - 1],
                       np.log10(self.rmin),
                       np.log10(self.rmax)
                   ],
                   aspect=aspect1,
                   cmap='coolwarm',
                   norm=colors.SymLogNorm(linthresh=0.001,
                                          linscale=0.5,
                                          vmin=-1.0,
                                          vmax=1.0))
        #axArray[axNum].text(1.02, 0.5, title, fontsize=14,transform=axArray[axNum].transAxes)
        #axArray[axNum].set_ylabel("log(r) (AU)")
        #axArray[axNum].set_yticks([-1,0])
        plt.colorbar(shrink=0.5)
        plt.savefig(savePath + "MST1cbar0" + nameTag + ".png",
                    bbox_inches='tight',
                    dpi=600)
        plt.clf()

        col = 0
        axNum = 1
        title = self.header[col]
        plotData = self.data[col][ti1:ti2]
        plt.imshow(np.transpose(np.fliplr(plotData)),
                   extent=[
                       self.t[ti1], self.t[ti2 - 1],
                       np.log10(self.rmin),
                       np.log10(self.rmax)
                   ],
                   aspect=aspect1,
                   cmap='viridis',
                   norm=LogNorm())
        #axArray[axNum].text(1.02, 0.5, title, fontsize=14,transform=axArray[axNum].transAxes)
        #axArray[axNum].set_ylabel("log(r) (AU)")
        #axArray[axNum].set_yticks([-1,0])
        plt.colorbar(shrink=0.5)
        plt.savefig(savePath + "MST1cbar1" + nameTag + ".png",
                    bbox_inches='tight',
                    dpi=600)
        plt.clf()

        col = 15
        axNum = 2
        title = self.header[col]
        plotData = self.data[col][ti1:ti2]
        plt.imshow(np.transpose(np.fliplr(plotData)),
                   extent=[
                       self.t[ti1], self.t[ti2 - 1],
                       np.log10(self.rmin),
                       np.log10(self.rmax)
                   ],
                   aspect=aspect1,
                   cmap='viridis',
                   norm=LogNorm())
        #axArray[axNum].text(1.02, 0.5, title, fontsize=14,transform=axArray[axNum].transAxes)
        #axArray[axNum].set_ylabel("log(r) (AU)")
        #axArray[axNum].set_yticks([-1,0])
        plt.colorbar(shrink=0.5)
        plt.savefig(savePath + "MST1cbar2" + nameTag + ".png",
                    bbox_inches='tight',
                    dpi=600)
        plt.clf()
Пример #20
0
def plot_continuum(cfg_par):
    '''Function to plot the continuum image from where spectra are extracted
    '''

    cont_im = cfg_par['general']['contname']
    if os.path.exists(cont_im):
        #load wcs system
        hdulist = fits.open(cont_im)  # read input
        # read data and header
        #what follows works for wcs, but can be written better
        prihdr = hdulist[0].header
        w = wcs.WCS(prihdr)

        # RS: the rest of the function requires only 2 axis images
        if w.naxis == 4:
            w = w.dropaxis(3)
            w = w.dropaxis(2)
            img = hdulist[0].data[0][0]
        elif w.naxis == 3:
            w = w.dropaxis(2)
            img = hdulist[0].data[0]

    elif os.path.exists(cfg_par['general']['cubename']):

        cube_im = cfg_par['general']['cubename']
        #load wcs system
        hdulist = fits.open(cube_im)  # read input
        # read data and header
        #what follows works for wcs, but can be written better
        prihdr = hdulist[0].header
        w = wcs.WCS(prihdr)

        # RS: the rest of the function requires only 2 axis images
        if w.naxis == 4:
            w = w.dropaxis(3)
            w = w.dropaxis(2)
            img = hdulist[0].data[0][0]
            img = np.zeros(img.shape)

        elif w.naxis == 3:
            w = w.dropaxis(2)
            img = hdulist[0].data[0]
            img = np.zeros(img.shape)
    else:
        print("ERROR: No datacube found. Check configuration file")
        sys.exit(1)

    ax = plt.subplot(projection=w)
    # ax.imshow(img, vmin=cfg_par[key]['clip'],
    #           vmax=np.max(img), norm=mc.LogNorm(cfg_par[key]['clip']), origin='lower')
    #ax.imshow(img, vmin=float(cfg_par[key]['clip'])/10000., vmax=np.min([np.max(img), float(cfg_par[key]['clip'])*1]), origin='lower')
    #fig = ax.imshow(img, vmin=0, vmax=float(cfg_par[key]['clip'])/5, origin = 'lower')

    fig = ax.imshow(img,
                    norm=mc.SymLogNorm(
                        float(cfg_par['source_finder']['clip']) / 5.,
                        vmin=float(cfg_par['source_finder']['clip']) / 5.),
                    origin='lower')

    # fig = ax.imshow(img, norm=mc.SymLogNorm(
    #   float(cfg_par[key]['clip'])*10), origin='lower')
    cbar = plt.colorbar(fig)
    cbar.set_label('Flux Density [Jy/beam]')
    #ax.imshow(img, vmin=, origin='lower')
    #ax.coords.grid(color='white', ls='solid')
    ax.coords[0].set_axislabel('Right Ascension')
    ax.coords[1].set_axislabel('Declination')
    ax.coords[0].set_major_formatter('hh:mm')
    ax.set_title("{0:s}".format(cfg_par['general']['workdir'].split('/')[-2]))
    #ax.coords[0].set_ticks(direction='in')
    #ax.coords[1].set_ticks(direction='in')
    # ax.tick_params(axis='both', bottom='on', top='on', left='on', right='on',
    #          which='major', direction='in')

    mirCatalogFile = cfg_par['general']['absdir'] + 'mir_src_sharp.csv'
    catalog_table = '{:s}{:s}'.format(
        cfg_par['general'].get('absdir'),
        cfg_par['source_catalog'].get('catalog_file'))
    catalog_pybdsf = '{:s}{:s}'.format(
        cfg_par['general'].get('workdir'),
        cfg_par['source_catalog'].get('catalog_file'))

    if os.path.exists(mirCatalogFile):
        src_list = ascii.read(mirCatalogFile)
        coord_list = SkyCoord(src_list['ra'],
                              src_list['dec'],
                              unit=(u.hourangle, u.deg),
                              frame='fk5')

        for k in range(len(coord_list.ra)):
            ax.scatter(coord_list[k].ra.value,
                       coord_list[k].dec.value,
                       transform=ax.get_transform('fk5'),
                       edgecolor='red',
                       facecolor='none')
            ax.annotate("{0:d}".format(k + 1),
                        xy=(coord_list[k].ra.value, coord_list[k].dec.value),
                        xycoords=ax.get_transform('fk5'),
                        xytext=(1, 1),
                        textcoords='offset points',
                        ha='left',
                        color="white")

    elif os.path.exists(catalog_pybdsf) and (
            cfg_par['source_catalog']['catalog'] == 'PYBDSF'):
        import Tigger
        from astropy.coordinates import Angle

        model = Tigger.load(catalog_pybdsf)
        sources = model.sources
        ra = []
        dec = []
        for source in sources:
            ra_deg_angle = Angle(np.rad2deg(source.pos.ra) * u.deg)
            dec_deg_angle = Angle(np.rad2deg(source.pos.dec) * u.deg)
            ra.append(ra_deg_angle)
            dec.append(dec_deg_angle)

        coord_list = SkyCoord(ra, dec, unit=(u.deg, u.deg), frame='fk5')

        for k in range(len(coord_list.ra)):
            ax.scatter(coord_list[k].ra.value,
                       coord_list[k].dec.value,
                       transform=ax.get_transform('fk5'),
                       edgecolor='red',
                       facecolor='none')
            ax.annotate("{0:d}".format(k + 1),
                        xy=(coord_list[k].ra.value, coord_list[k].dec.value),
                        xycoords=ax.get_transform('fk5'),
                        xytext=(1, 1),
                        textcoords='offset points',
                        ha='left',
                        color="white")

    elif os.path.exists(catalog_table) and (
            cfg_par['source_catalog']['catalog'] == 'NVSS'):

        src_list = ascii.read(catalog_table)
        ra = np.array(src_list['RAJ2000'], dtype=str)
        dec = np.array(src_list['DEJ2000'], dtype=str)
        pixels = np.zeros([len(ra), 2])
        kk = []

        cube_im = cfg_par['general']['cubename']
        #load wcs system
        hdulist = fits.open(cube_im)  # read input
        # read data and header
        #what follows works for wcs, but can be written better
        prihdr = hdulist[0].header
        w = wcs.WCS(prihdr)
        if w.naxis == 4:
            w = w.dropaxis(3)
            w = w.dropaxis(2)
        if w.naxis == 3:
            w = w.dropaxis(2)
        ra_vec = []
        dec_vec = []
        for i in xrange(0, len(ra)):
            if ra[i] == 'nan':
                pixels[i, 0] = np.nan
                pixels[i, 1] = np.nan
            else:
                ra_deg = conv_units.ra2deg(ra[i])
                dec_deg = conv_units.dec2deg(dec[i])
                px, py = w.wcs_world2pix(ra_deg, dec_deg, 0)
                if (0 < round(px, 0) < prihdr['NAXIS1']
                        and 0 < round(py, 0) < prihdr['NAXIS2']):
                    kk.append(i)
                    ra_vec.append(ra[i])
                    dec_vec.append(dec[i])
                else:
                    pass

        coord_list = SkyCoord(ra_vec,
                              dec_vec,
                              unit=(u.hourangle, u.deg),
                              frame='fk5')

        for k in range(len(coord_list.ra)):
            ax.scatter(coord_list[k].ra.value,
                       coord_list[k].dec.value,
                       transform=ax.get_transform('fk5'),
                       edgecolor='red',
                       facecolor='none')
            ax.annotate("{0:s}".format(str(kk[k])),
                        xy=(coord_list[k].ra.value, coord_list[k].dec.value),
                        xycoords=ax.get_transform('fk5'),
                        xytext=(1, 1),
                        textcoords='offset points',
                        ha='left',
                        color="white")

    output = "{0:s}{1:s}_continuum.png".format(
        cfg_par['general'].get('plotdir'),
        cfg_par['general']['workdir'].split('/')[-2])

    if cfg_par['abs_plot']['plot_format'] == "pdf":
        plt.savefig(output.replace(".png", ".pdf"),
                    overwrite=True,
                    bbox_inches='tight')
    else:
        plt.savefig(output, overwrite=True, bbox_inches='tight', dpi=300)
Пример #21
0
# to one decade in the logarithmic range.

N = 100
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2

fig, ax = plt.subplots(2, 1)

pcm = ax[0].pcolormesh(X,
                       Y,
                       Z,
                       norm=colors.SymLogNorm(linthresh=0.03,
                                              linscale=0.03,
                                              vmin=-1.0,
                                              vmax=1.0,
                                              base=10),
                       cmap='RdBu_r',
                       shading='auto')
fig.colorbar(pcm, ax=ax[0], extend='both')

pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', vmin=-np.max(Z), shading='auto')
fig.colorbar(pcm, ax=ax[1], extend='both')
plt.show()

###############################################################################
# Power-law
# ---------
#
# Sometimes it is useful to remap the colors onto a power-law
 if np.min(j_xy) == np.max(j_xy):
     continue
 tickld = [-10, -1, 0, 1, 10]
 tick_r = np.logspace(-0.5, 1.5, 20)
 tick_r = tick_r.tolist()
 tick_l = -np.logspace(-0.5, 1.5, 20)
 tick_l = tick_l.tolist()
 tick_l.reverse()
 tick_l = tick_l + tick_r
 print(tick_l)
 plt.contourf(X,
              Y,
              jx.T,
              levels=tick_l,
              norm=mcolors.SymLogNorm(linthresh=10**(-0.5),
                                      linscale=0.2,
                                      vmin=-10**1.5,
                                      vmax=10**1.5),
              cmap='RdBu')
 eee = 100.  #np.max([-np.min(ex.T),np.max(ex.T)])
 #levels = np.logspace(-1, 2, 40)
 #plt.contourf(X, Y, jx.T, norm=mcolors.SymLogNorm(linthresh=0.03, linscale=0.03, vmin=-30.0,  vmax=30.0), cmap='RdBu_r')
 #### manifesting colorbar, changing label and axis properties ####
 cbar = plt.colorbar(pad=0.01, ticks=tickld)
 cbar.set_label('$j_{x}$ [$I_A/\lambda^2$]', fontdict=font)
 cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(), fontsize=15)
 ##              s_j=1
 ##              X = X[::s_j,::s_j]
 ##              Y = Y[::s_j,::s_j]
 ##              j_xy = j_xy.T; jx = jx.T; jy=jy.T
 ##              j_xy = j_xy[::s_j,::s_j]
 ##              jx = jx[::s_j,::s_j]
def make_frame(frame_dir, frame, image_dir, frames, global_vars, add_ds_patches = False, ss= False, ds_wall_params=[0.05,0.05,0.15,0.4], fig_size=(16,16), lin_thresh = 0.1, lin_scale = 1., **kwargs):
    # print i
    global rhoMin, rhoMax
    frame_number = (frame.split("_")[1]).split(".")[0]
    QuantumState = np.load(frame_dir)
    if int(frame_number) == 0:
        set_globals(global_vars, QuantumState)
    RhoFields = []
    PhaseFields = []
    num_comps = int(len(QuantumState[0,0,0,:])/2)
    for comp in xrange(num_comps):
        rho = (QuantumState[:,:,0,2*comp]+QuantumState[:,:,0,2*comp+1])*(QuantumState[:,:,0,2*comp]+QuantumState[:,:,0,2*comp+1]).conjugate()
        RhoFields.append(rho/np.sum(rho))
        PhaseFields.append(np.arctan2((QuantumState[:,:,0,2*comp]+QuantumState[:,:,0,2*comp+1]).imag,(QuantumState[:,:,0,2*comp]+QuantumState[:,:,0,2*comp+1]).real) + np.pi)
    if int(frame_number) == 0:
        for comp in xrange(num_comps):
            if np.amax(RhoFields[comp].real)>rhoMax:
                rhoMax = np.amax(RhoFields[comp].real)
            if np.amin(RhoFields[comp].real)<rhoMin:
                rhoMin = np.amin(RhoFields[comp].real)

    fig, axs = plt.subplots(num_comps, 2, figsize=fig_size, constrained_layout=True)
    #Ref below    
    time = int(frame_number)
    time_text = plt.suptitle(r'$\tau = $' + str(time), fontsize=14, horizontalalignment='center',verticalalignment='top')
    print num_comps

    cases = np.arange(2*num_comps)
    for ax, case in zip(axs, cases):
        if case%2==0:
            print ax
            im = ax.imshow(RhoFields[int(case/2)].real, extent=(np.amin(yAxis), np.amax(yAxis), np.amin(xAxis), np.amax(xAxis)), origin = 'lower',
                alpha = 1.0, cmap=colorMapBlue, norm=colors.SymLogNorm(linthresh=lin_thresh*rhoMax,linscale=lin_scale,vmin=0.,vmax=rhoMax))
            putLabels(fig,ax,im,r'$y\ \ (\ell)$', r'$x\ \ (\ell)$', r'$\rho \ \ (\frac{1}{\ell^2})$')
            ax.set_aspect('auto')
        else:
            # # Phase
            im = ax.imshow((PhaseFields[int(case/2)].real), extent=(np.amin(yAxis), np.amax(yAxis), np.amin(xAxis), np.amax(xAxis)), origin = 'lower',
                cmap=colorMapPhase, norm=colors.Normalize(vmin=0.,vmax=2.*np.pi))
            # Any value whose absolute value is > .0001 will have zero transparency
            rhoMaxCase = np.amax(RhoFields[int(case/2)].real)
            alphas = Normalize(0, rhoMaxCase, clip=True)((rhoMaxCase-RhoFields[int(case/2)].real))
            # # alphas = colors.SymLogNorm(linthresh=linThresh*rhoMax,linscale=linScale,vmin=0.,vmax=10., clip=True)((rhoMax-RhoField.real).T)
            # alphas = np.clip(np.sqrt(alphas), 0.0, 1)  # alpha value clipped at the bottom at .4
            # Normalize the colors b/w 0 and 1, we'll then pass an MxNx4 array to imshow
            cmap = plt.cm.gist_gray.reversed()
            colorsMap = colors.SymLogNorm(linthresh=lin_thresh*rhoMaxCase,linscale=lin_scale,vmin=0.,vmax=rhoMaxCase)((0.*RhoFields[int(case/2)].real))
            colorsMap = cmap(colorsMap)

            # Now set the alpha channel to the one we created above
            colorsMap[..., -1] = alphas
            ax.imshow(colorsMap, origin = 'lower')
            putLabels(fig,ax,im,r'$y\ \ (\ell)$', r'$x\ \ (\ell)$', r'$\theta \ \ (Radians)$')

        if add_ds_patches:
            #Add walls and screen
            slit_width = ds_wall_params[0]*xSize
            wall_width = ds_wall_params[1]*xSize
            spacing = ds_wall_params[2]*xSize
            wall_center = ds_wall_params[3]*xSize
            #Double slit
            ax.add_patch(patches.Rectangle(
                (0.,wall_center-wall_width/2.), #xLoc,yLoc
                ySize/2. - spacing/2. - slit_width/2.,  #Width
                wall_width,  #Height
                color = 'black'
                )
              )
            if ss==False:
                ax.add_patch(patches.Rectangle(
                    ((ySize-1.)/2. - spacing/2. + slit_width/2.,wall_center-wall_width/2.), #xLoc,yLoc
                    spacing - slit_width,  #Width
                    wall_width,  #Height
                    color = 'black'
                    )
                  )
            ax.add_patch(patches.Rectangle(
                ((ySize-1.)/2. + spacing/2. + slit_width/2.,wall_center-wall_width/2.), #xLoc,yLoc
                ySize/2. - spacing/2. - slit_width/2.,  #Width
                wall_width,  #Height
                color = 'black'
                )
              )

            #Screen
            ax.add_patch(patches.Rectangle(
                (0.,2.*(xSize)/3.), #xLoc,yLoc
                ySize,  #Width
                wall_width/8.,  #Height
                color = 'red'
                )
              )
            #Boundary walls
            ax.add_patch(patches.Rectangle(
                (0.,0.), #xLoc,yLoc
                ySize,  #Width
                xSize/50.,  #Height
                color = 'black'
                )
              )
            ax.add_patch(patches.Rectangle(
                (0.,xSize-xSize/50.), #xLoc,yLoc
                ySize,  #Width
                xSize/50.,  #Height
                color = 'black'
                )
              )
Пример #24
0
                param_image = fits.getdata(chemMaps_fits_address, param, ver=1)
            if param == 'O':
                O2 = np.power(
                    10,
                    fits.getdata(chemMaps_fits_address, 'O2', ver=1) - 12)
                O3 = np.power(
                    10,
                    fits.getdata(chemMaps_fits_address, 'O3', ver=1) - 12)
                param_image = 12 + np.log10(O2 + O3)
                latex_labels['O'] = r'12+log(O)'
            else:
                param_image = fits.getdata(chemMaps_fits_address, param, ver=1)
            im = ax.imshow(flux6563_image,
                           cmap=halpha_cmap,
                           norm=colors.SymLogNorm(
                               linthresh=halpha_thresd_level,
                               vmin=halpha_min_level,
                               base=10))
            im2 = ax.imshow(param_image)

            cbar = fig.colorbar(im2, ax=ax)

            param_label = latex_labels[param]
            ax.update({
                'title': r'Galaxy {}, {}'.format(obj, param_label),
                'xlabel': r'RA',
                'ylabel': r'DEC'
            })
            ax.set_xlim(120, 210)
            ax.set_ylim(110, 220)
            plt.tight_layout()
            plt.show()
Пример #25
0
            60000, 100000, 200000
        ]
        #plt.contourf(x,y,data,cmap=,resolution='c')

        # ticks=[1e0,5e0,1e1,2e1,5e1,1e2,2e2,5e2,1e3,2e3,5e3,1e4,3e4,6e4,1e5]
        ticks4 = [-1e3, -1e2, -1e1, 1e1, 1e2, 1e3]
        ticks4 = [-1e3, -5e2, -1e2, -5e1, -1e1, 1e1, 5e1, 1e2, 5e2, 1e3]
        ticks4_label = [str(o) for o in ticks4]
        flag2 = ticks

        plt.contourf(x,
                     y,
                     data,
                     ticks4,
                     norm=colors.SymLogNorm(linthresh=1e1,
                                            linscale=1e0,
                                            vmin=-1e3,
                                            vmax=1e3),
                     cmap='RdYlBu_r',
                     format='%.0e')
        #plt.contourf(x,y,data,ticks3,norm=colors.LogNorm(vmin=1e-5,vmax=8e4),cmap='RdYlBu_r', format = '%.0e')
        #plt.contourf(x,y,data,ticks3,norm=colors.LogNorm(vmin=pow(10,1),vmax=pow(10,6)),cmap=plt.cm.jet,resolution='c', format = '%.0e')
        #plt.clim((pow(10,3),pow(10,7)))
        plt.plot(lat1, trop_height.data, 'k--')
        mn = 0.1
        mx = 100000
        md = (mx - mn) / 2
        print('\nThe maximum value of particle number is      = ',
              np.max(data))
        print('\nThe minimum value of particle number is      = ',
              np.min(data))
        print('\nThe mean value of particle number is         = ',
Пример #26
0
def main():
    # Load a sample air temperatures sequence.
    file_path = iris.sample_data_path("E1_north_america.nc")
    temperatures = iris.load_cube(file_path)

    # Create a year-number coordinate from the time information.
    iris.coord_categorisation.add_year(temperatures, "time")

    # Create a sample anomaly field for one chosen year, by extracting that
    # year and subtracting the time mean.
    sample_year = 1982
    year_temperature = temperatures.extract(iris.Constraint(year=sample_year))
    time_mean = temperatures.collapsed("time", iris.analysis.MEAN)
    anomaly = year_temperature - time_mean

    # Construct a plot title string explaining which years are involved.
    years = temperatures.coord("year").points
    plot_title = "Temperature anomaly"
    plot_title += "\n{} differences from {}-{} average.".format(
        sample_year, years[0], years[-1])

    # Define scaling levels for the logarithmic colouring.
    minimum_log_level = 0.1
    maximum_scale_level = 3.0

    # Use a standard colour map which varies blue-white-red.
    # For suitable options, see the 'Diverging colormaps' section in:
    # http://matplotlib.org/stable/gallery/color/colormap_reference.html
    anom_cmap = "bwr"

    # Create a 'logarithmic' data normalization.
    anom_norm = mcols.SymLogNorm(
        linthresh=minimum_log_level,
        linscale=0,
        vmin=-maximum_scale_level,
        vmax=maximum_scale_level,
    )
    # Setting "linthresh=minimum_log_level" makes its non-logarithmic
    # data range equal to our 'zero band'.
    # Setting "linscale=0" maps the whole zero band to the middle colour value
    # (i.e. 0.5), which is the neutral point of a "diverging" style colormap.

    # Create an Axes, specifying the map projection.
    plt.axes(projection=ccrs.LambertConformal())

    # Make a pseudocolour plot using this colour scheme.
    mesh = iplt.pcolormesh(anomaly, cmap=anom_cmap, norm=anom_norm)

    # Add a colourbar, with extensions to show handling of out-of-range values.
    bar = plt.colorbar(mesh, orientation="horizontal", extend="both")

    # Set some suitable fixed "logarithmic" colourbar tick positions.
    tick_levels = [-3, -1, -0.3, 0.0, 0.3, 1, 3]
    bar.set_ticks(tick_levels)

    # Modify the tick labels so that the centre one shows "+/-<minumum-level>".
    tick_levels[3] = r"$\pm${:g}".format(minimum_log_level)
    bar.set_ticklabels(tick_levels)

    # Label the colourbar to show the units.
    bar.set_label("[{}, log scale]".format(anomaly.units))

    # Add coastlines and a title.
    plt.gca().coastlines()
    plt.title(plot_title)

    # Display the result.
    iplt.show()
Пример #27
0
    def _norm_kwargs(self, element, ranges, opts, vdim, prefix=''):
        """
        Returns valid color normalization kwargs
        to be passed to matplotlib plot function.
        """
        clim = opts.pop(prefix + 'clims', None)
        values = np.asarray(element.dimension_values(vdim))
        if clim is None:
            if not len(values):
                clim = (0, 0)
                categorical = False
            elif values.dtype.kind in 'uif':
                clim = ranges[
                    vdim.name] if vdim.name in ranges else element.range(vdim)
                if self.logz:
                    # Lower clim must be >0 when logz=True
                    # Choose the maximum between the lowest non-zero value
                    # and the overall range
                    if clim[0] == 0:
                        clim = (values[values != 0].min(), clim[1])
                if self.symmetric:
                    clim = -np.abs(clim).max(), np.abs(clim).max()
                categorical = False
            else:
                clim = (0, len(np.unique(values)) - 1)
                categorical = True
        else:
            categorical = values.dtype.kind not in 'uif'

        if self.logz:
            if self.symmetric:
                norm = mpl_colors.SymLogNorm(vmin=clim[0],
                                             vmax=clim[1],
                                             linthresh=clim[1] / np.e)
            else:
                norm = mpl_colors.LogNorm(vmin=clim[0], vmax=clim[1])
            opts[prefix + 'norm'] = norm
        opts[prefix + 'vmin'] = clim[0]
        opts[prefix + 'vmax'] = clim[1]

        # Check whether the colorbar should indicate clipping
        if values.dtype.kind not in 'OSUM':
            ncolors = self.color_levels
            try:
                el_min, el_max = np.nanmin(values), np.nanmax(values)
            except ValueError:
                el_min, el_max = -np.inf, np.inf
        else:
            ncolors = clim[-1] + 1
            el_min, el_max = -np.inf, np.inf
        vmin = -np.inf if opts[prefix + 'vmin'] is None else opts[prefix +
                                                                  'vmin']
        vmax = np.inf if opts[prefix + 'vmax'] is None else opts[prefix +
                                                                 'vmax']
        if el_min < vmin and el_max > vmax:
            self._cbar_extend = 'both'
        elif el_min < vmin:
            self._cbar_extend = 'min'
        elif el_max > vmax:
            self._cbar_extend = 'max'

        # Define special out-of-range colors on colormap
        cmap = opts.get(prefix + 'cmap', 'viridis')
        colors = {}
        for k, val in self.clipping_colors.items():
            if val == 'transparent':
                colors[k] = {'color': 'w', 'alpha': 0}
            elif isinstance(val, tuple):
                colors[k] = {
                    'color': val[:3],
                    'alpha': val[3] if len(val) > 3 else 1
                }
            elif isinstance(val, util.basestring):
                color = val
                alpha = 1
                if color.startswith('#') and len(color) == 9:
                    alpha = int(color[-2:], 16) / 255.
                    color = color[:-2]
                colors[k] = {'color': color, 'alpha': alpha}

        if not isinstance(cmap, mpl_colors.Colormap):
            if isinstance(cmap, dict):
                factors = np.unique(values)
                palette = [
                    cmap.get(
                        f,
                        colors.get('NaN',
                                   {'color': self._default_nan})['color'])
                    for f in factors
                ]
            else:
                palette = process_cmap(cmap, ncolors, categorical=categorical)
            cmap = mpl_colors.ListedColormap(palette)
        if 'max' in colors: cmap.set_over(**colors['max'])
        if 'min' in colors: cmap.set_under(**colors['min'])
        if 'NaN' in colors: cmap.set_bad(**colors['NaN'])
        opts[prefix + 'cmap'] = cmap
Пример #28
0
# %%
varlist = ['NCONC01', 'NMR01', 'AWNC_incld', 'AREL_incld']
cbar_orientation = 'vertical'
cases_ctrl = cases_orig
case_oth = cases_sec[0]
ncol = len(cases_ctrl)
nrow = len(varlist)
subfig_size = 2.5
asp_ratio = 1.6
figsize = [subfig_size * ncol * asp_ratio, subfig_size * nrow]
# noinspection PyTypeChecker
fig, axs = plt.subplots(nrow, ncol, figsize=figsize, sharex=True, sharey=True)

norm_dic = dict(
    NCONC01=colors.SymLogNorm(vmin=-1e3, vmax=1e3, linthresh=10),
    NMR01=colors.SymLogNorm(vmin=-10, vmax=10, linthresh=1),# linscale=.5),
    AWNC_incld=colors.SymLogNorm(vmin=-20, vmax=20, linthresh=1),
    AREL_incld=colors.SymLogNorm(vmin=-5, vmax=5, linthresh=.1)
)
cases_dic = get_averaged_fields.get_levlat_cases(cases, varlist, startyear, endyear,
                                                 pressure_adjust=pressure_adjust)

for j, var in enumerate(varlist):
    saxs = axs[j, :]
    levlat_more_cases_var(var, case_oth, cases_ctrl, cases_dic, cbar_eq=True,
                          cbar_orientation='vertical',
                          axs=saxs,
                          norm=norm_dic[var],
                          relative=False,
                          ylim=[1e3, 200],
Пример #29
0
                       width_ratios=widthRatios)
ax = []
cax = []

for n in range(nRows):
    if n == 0: ax.append(fig.add_subplot(gs[n, 0]))
    else: ax.append(fig.add_subplot(gs[n, 0], sharex=ax[0]))
    cax.append(fig.add_subplot(gs[n, 1]))

extent = [tmin, tmax, np.log10(do.rmin), np.log10(do.rmax)]
aspect = 0.3 * (tmax - tmin) / (np.log10(do.rmax) - np.log10(do.rmin))

axNum = 0
im = ax[axNum].imshow(np.transpose(np.fliplr(do.data[12][tiMin:tiMax])),
                      extent=extent,
                      aspect=aspect,
                      cmap=plt.get_cmap('coolwarm'),
                      norm=colors.SymLogNorm(linthresh=0.1,
                                             linscale=1.0,
                                             vmin=-1.0,
                                             vmax=1.0))
ax[axNum].set_ylabel('log(r) (AU)')
ax[axNum].set_title(do.header[12] + " (G)")
#ax[axNum].axhline(np.log10(do.inp.rIn), color='k')
ax[axNum].axhline(np.log10(do.inp.rDz1), color='k', linestyle='--')
ax[axNum].set_xlabel("Time (yr)")
fig.colorbar(im, cax=cax[axNum], orientation='vertical')
plt.savefig(do.savePath + "justBz.png", bbox_inches='tight')

#
Пример #30
0
    def plot(
        self,
        i=0,
        iaz=0,
        vmin=None,
        vmax=None,
        dynamic_range=1e6,
        fpeak=None,
        axes_unit='arcsec',
        colorbar=True,
        type='I',
        scale=None,
        pola_vector=False,
        vector_color="white",
        nbin=5,
        psf_FWHM=None,
        bmaj=None,
        bmin=None,
        bpa=None,
        plot_beam=None,
        conv_method=None,
        mask=None,
        cmap=None,
        ax=None,
        no_xlabel=False,
        no_ylabel=False,
        no_xticks=False,
        no_yticks=False,
        title=None,
        limit=None,
        limits=None,
        coronagraph=None,
        clear=False,
        Tb=False,
    ):
        # Todo:
        #  - plot a selected contribution
        #  - add a mask on the star ?

        # bmin and bamj in arcsec

        if clear:
            plt.clf()

        if ax is None:
            ax = plt.gca()
            ax.cla()

        pola_needed = type in ['Q', 'U', 'Qphi', 'Uphi', 'P', 'PI', 'PA'
                               ] or pola_vector
        contrib_needed = type in ['star', 'scatt', 'em_th', 'scatt_em_th']

        if pola_needed and contrib_needed:
            raise ValueError(
                'Cannot separate both polarisation and contributions')

        # --- We first check if the requested image is present in the mcfost fits file
        ntype_flux = self.image.shape[0]
        if ntype_flux not in (4, 8):  # there is no pola
            if pola_needed:
                raise ValueError('The model does not have polarisation data')
        elif ntype_flux not in (5, 8):  # there is no contribution
            if contrib_needed:
                raise ValueError('The model does not have contribution data')

        # --- Compute pixel scale and extent of image
        if axes_unit.lower() == 'arcsec':
            pix_scale = self.pixelscale
            xlabel = r'$\Delta$ Ra ["]'
            ylabel = r'$\Delta$ Dec ["]'
        elif axes_unit.lower() == 'au':
            pix_scale = self.pixelscale * self.P.map.distance
            xlabel = 'Distance from star [au]'
            ylabel = 'Distance from star [au]'
        elif axes_unit.lower() == 'pixels' or axes_unit.lower() == 'pixel':
            pix_scale = 1
            xlabel = r'$\Delta$ x [pix]'
            ylabel = r'$\Delta$ y [pix]'
        else:
            raise ValueError("Unknown unit for axes_units: " + axes_unit)
        halfsize = np.asarray(self.image.shape[-2:]) / 2 * pix_scale
        extent = [-halfsize[0], halfsize[0], -halfsize[1], halfsize[1]]

        # --- Beam or psf: psf_FWHM and bmaj and bmin are in arcsec, bpa in deg
        i_convolve = False
        beam = None
        if psf_FWHM is not None:
            sigma = (psf_FWHM / self.pixelscale *
                     (2.0 * np.sqrt(2.0 * np.log(2))))  # in pixels
            beam = Gaussian2DKernel(sigma)
            i_convolve = True
            bmin = psf_FWHM
            bmaj = psf_FWHM
            bpa = 0
            if plot_beam is None:
                plot_beam = True

        if bmaj is not None:
            sigma_x = bmin / self.pixelscale * FWHM_to_sigma  # in pixels
            sigma_y = bmaj / self.pixelscale * FWHM_to_sigma  # in pixels
            beam = Gaussian2DKernel(sigma_x, sigma_y, bpa * np.pi / 180)
            i_convolve = True
            if plot_beam is None:
                plot_beam = True

        # --- Selecting convolution function
        if conv_method is None:
            conv_method = convolve_fft

        # --- Intermediate images
        if pola_needed:
            I = self.image[0, i, iaz, :, :]
            Q = self.image[1, i, iaz, :, :]
            U = self.image[2, i, iaz, :, :]
        elif contrib_needed:
            if pola_needed:
                n_pola = 4
            else:
                n_pola = 1
            if type == "star":
                I = self.image[n_pola, i, iaz, :, :]
            elif type == "scatt":
                I = self.image[n_pola + 1, i, iaz, :, :]
            elif type == "em_th":
                I = self.image[n_pola + 2, i, iaz, :, :]
            elif type == "scatt_em_th":
                I = self.image[n_pola + 3, i, iaz, :, :]
        else:
            if self.is_casa:
                I = self.image[i, iaz, :, :]
            else:
                I = self.image[0, i, iaz, :, :]

        # --- Convolve with beam
        if i_convolve:
            I = conv_method(I, beam)
            if pola_needed:
                Q = conv_method(Q, beam)
                U = conv_method(U, beam)

        # -- Conversion to brightness temperature
        if Tb:
            if self.is_casa:
                I = Jy_to_Tb(I, self.freq, self.pixelscale)
            else:
                I = Wm2_to_Tb(I, self.freq, self.pixelscale)
                I = np.nan_to_num(I)
                print("Max Tb=", np.max(I), "K")

        # --- Coronagraph: in mas
        if coronagraph is not None:
            halfsize = np.asarray(self.image.shape[-2:]) / 2
            posx = np.linspace(-halfsize[0], halfsize[0], self.nx)
            posy = np.linspace(-halfsize[1], halfsize[1], self.ny)
            meshx, meshy = np.meshgrid(posx, posy)
            radius_pixel = np.sqrt(meshx**2 + meshy**2)
            radius_mas = radius_pixel * pix_scale * 1000
            I[radius_mas < coronagraph] = 0.0
            if pola_needed:
                Q[radius_mas < coronagraph] = 0.0
                U[radius_mas < coronagraph] = 0.0

        # --- Selecting image to plot & convolution
        unit = self.unit
        flux_name = type
        if type == 'I':
            flux_name = 'Flux density'
            im = I
            _scale = 'log'
        elif type == 'Q':
            im = Q
            _scale = 'symlog'
        elif type == 'U':
            im = U
            _scale = 'symlog'
        elif type == 'P':
            I = I + (I == 0.0) * 1e-30
            im = 100 * np.sqrt((Q / I)**2 + (U / I)**2)
            unit = "%"
            _scale = 'lin'
        elif type == 'PI':
            im = np.sqrt(np.float64(Q)**2 + np.float64(U)**2)
            _scale = 'log'
        elif type in ('Qphi', 'Uphi'):
            X = np.arange(1, self.nx + 1) - self.cx
            Y = np.arange(1, self.ny + 1) - self.cy
            X, Y = np.meshgrid(X, Y)
            two_phi = 2 * np.arctan2(Y, X)
            if type == 'Qphi':
                im = Q * np.cos(two_phi) + U * np.sin(two_phi)
            else:  # Uphi
                im = -Q * np.sin(two_phi) + U * np.cos(two_phi)
            _scale = 'symlog'

        # --- Plot range and color scale
        if vmax is None:
            vmax = im.max()
        if fpeak is not None:
            vmax = im.max() * fpeak
        if vmin is None:
            if type in ["Q", "U"]:
                vmin = -vmax
            else:
                vmin = im.min()

        if scale is None:
            scale = _scale
        if scale == 'symlog':
            norm = colors.SymLogNorm(1e-6 * vmax,
                                     vmin=vmin,
                                     vmax=vmax,
                                     clip=True)
        elif scale == 'log':
            if vmin <= 0.0:
                vmin = 1e-6 * vmax
            print(vmin)
            norm = colors.LogNorm(vmin=vmin, vmax=vmax, clip=True)
        elif scale == 'lin':
            norm = colors.Normalize(vmin=vmin, vmax=vmax, clip=True)
        else:
            raise ValueError("Unknown color scale: " + scale)

        # --- Set color map
        if cmap is None:
            cmap = default_cmap
        try:
            cmap = copy.copy(cm.get_cmap(cmap))
        except:
            raise ValueError("Unknown colormap: " + cmap)
        try:
            cmap.set_bad(cmap.colors[0])
        except:
            try:
                cmap.set_bad(cmap(0.0))
            except:
                raise Warning("Can't set bad values from given colormap")

        # --- Making the actual plot
        img = ax.imshow(im,
                        norm=norm,
                        extent=extent,
                        origin='lower',
                        cmap=cmap)

        if limit is not None:
            limits = [-limit, limit, -limit, limit]

        if limits is not None:
            ax.set_xlim(limits[0], limits[1])
            ax.set_ylim(limits[2], limits[3])

        if not no_xlabel:
            ax.set_xlabel(xlabel)
        if not no_ylabel:
            ax.set_ylabel(ylabel)

        if no_xticks:
            ax.get_xaxis().set_visible(False)
        if no_yticks:
            ax.get_yaxis().set_visible(False)

        if title is not None:
            ax.set_title(title)

        # --- Colorbar
        if colorbar:
            divider = make_axes_locatable(ax)
            cax = divider.append_axes("right", size="5%", pad=0.05)
            cb = plt.colorbar(img, cax=cax)
            formatted_unit = unit.replace("-1",
                                          "$^{-1}$").replace("-2", "$^{-2}$")
            cb.set_label(flux_name + " [" + formatted_unit + "]")

        # --- Overplotting polarisation vectors
        if pola_vector:
            X = (np.arange(1, self.nx + 1) - self.cx) * pix_scale
            Y = (np.arange(1, self.ny + 1) - self.cy) * pix_scale
            X, Y = np.meshgrid(X, Y)

            Xb = bin_image(X, nbin, func=np.mean)
            Yb = bin_image(Y, nbin, func=np.mean)
            Ib = bin_image(I, nbin)
            Qb = bin_image(Q, nbin)
            Ub = bin_image(U, nbin)

            pola = 100 * np.sqrt((Qb / Ib)**2 + (Ub / Ib)**2)
            theta = 0.5 * np.arctan2(Ub, Qb)
            pola_x = -pola * np.sin(
                theta
            )  # Ref is N (vertical axis) --> sin, and Est is toward left --> -
            pola_y = pola * np.cos(theta)

            plt.quiver(
                Xb,
                Yb,
                pola_x,
                pola_y,
                headwidth=0,
                headlength=0,
                headaxislength=0.0,
                pivot='middle',
                color=vector_color,
            )

        # --- Adding beam
        if plot_beam:
            dx = 0.125
            dy = 0.125
            beam = Ellipse(
                ax.transLimits.inverted().transform((dx, dy)),
                width=bmin,
                height=bmaj,
                angle=bpa,
                fill=True,
                color="grey",
            )
            ax.add_patch(beam)

        # --- Adding mask
        if mask is not None:
            dx = 0.5
            dy = 0.5
            mask = Ellipse(
                ax.transLimits.inverted().transform((dx, dy)),
                width=2 * mask,
                height=2 * mask,
                fill=True,
                color='grey',
            )
            ax.add_patch(mask)

        # --- Return
        return img