Пример #1
0
def demo_grid_with_each_cbar(fig):
    """
    A grid of 2x2 images. Each image has its own colobar.
    """

    grid = AxesGrid(
        F,
        133,  # similar to subplot(122)
        nrows_ncols=(2, 2),
        axes_pad=0.1,
        label_mode="1",
        share_all=True,
        cbar_location="top",
        cbar_mode="each",
        cbar_size="7%",
        cbar_pad="2%",
    )
    Z, extent = get_demo_image()
    for i in range(4):
        im = grid[i].imshow(Z, extent=extent, interpolation="nearest")
        grid.cbar_axes[i].colorbar(im)

    # This affects all axes because we set share_all = True.
    grid.axes_llc.set_xticks([-2, 0, 2])
    grid.axes_llc.set_yticks([-2, 0, 2])
Пример #2
0
    def display_kernels(kgrid, n1, n2):
        # default: n1=12(mag), n2=17(Re)
        fig = figure(1, figsize=(12, 8))
        grid = AxesGrid(fig, (0.1, 0.15, 0.9, 0.58),
                        nrows_ncols=(n2, n1),
                        axes_pad=0.0,
                        share_all=True,
                        aspect=False)

        #grid.set_aspect(0.6)
        for i in arange(n1):
            for j in range(n2)[::-1]:
                kernel = maximum(kgrid.kernels[(i, j)].kernel, 1.e-50)
                if kgrid.kernels[(i, j)].completeness < 0:
                    kernel = kernel * 0.
                else:
                    #nf = 1.0/max(kernel.ravel())
                    kernel = kernel * kgrid.kernels[(i, j)].completeness
                #grid[(n2-j-1)*n1+i].
                grid[(n2 - j - 1) * n1 + i].imshow(kernel.swapaxes(0, 1),
                                                   origin='lower',
                                                   vmax=0.002,
                                                   aspect=0.4)
                #grid[(n2-j-1)*n1+i].xscale=1.5
                #grid[(n2-j-1)*n1+i].yscale=1.0
                grid[(n2 - j - 1) * n1 + i].get_aspect()

        grid.axes_llc.set_xticks([])
        grid.axes_llc.set_yticks([])
        draw()
Пример #3
0
def AnnotateS1Activity(exp, image, scale=0, cols=2, colorbar=True,
    normalize=True):
  """Plot the S1 activation for a given image.

  This shows the image in the background, with the activation plotted on top.
  There is one plot for each orientation band.

  :param image: Path to image on disk, or index of image in experiment.
  :param int scale: Index of scale band to use.
  :param bool colorbar: Whether to show colorbar with plot.

  """
  import matplotlib.pyplot as plt
  from mpl_toolkits.axes_grid import AxesGrid  # import must be delayed
  s1 = GetActivity(exp, image, Layer.S1)[scale]
  image = _ScaleImage(exp, GetActivity(exp, image, Layer.IMAGE), scale)
  params = exp.extractor.model.params
  left = bottom = params.s1_kwidth/2
  scale_factor = params.s1_sampling
  top = bottom + s1.shape[-2] * scale_factor
  right = left + s1.shape[-1] * scale_factor
  rows = int(np.ceil(len(s1) / float(cols)))
  grid = AxesGrid(plt.gcf(), 111,
    nrows_ncols = (rows, cols),
    axes_pad = 0.5,
    share_all = True,
    label_mode = "L",   # XXX value can be "L" or "1" -- what is this?
    cbar_location = "right",
    cbar_mode = "single",
  )
  vmin = s1.min()
  vmax = s1.max()
  for i in range(len(s1)):
    plt.sca(grid[i])
    plt.imshow(image, cmap=plt.cm.gray)
    plt.imshow(s1[i], vmin=vmin, vmax=vmax, alpha=.5,
        extent=(left,right,top,bottom), cmap=plt.cm.RdBu_r)
    plt.xticks(())
    plt.yticks(())
  if colorbar:
    img = grid[0].images[-1]
    grid.cbar_axes[0].colorbar(img)
    for cax in grid.cbar_axes:
      cax.toggle_label(True)
Пример #4
0
def demo_simple_grid(fig):
    """
    A grid of 2x2 images with 0.05 inch pad between images and only
    the lower-left axes is labeld.
    """
    grid = AxesGrid(
        fig,
        131,  # similar to subplot(131)
        nrows_ncols=(2, 2),
        axes_pad=0.05,
        label_mode="1",
    )

    Z, extent = get_demo_image()
    for i in range(4):
        im = grid[i].imshow(Z, extent=extent, interpolation="nearest")

    # This only affects axes in first column and second row as share_all = False.
    grid.axes_llc.set_xticks([-2, 0, 2])
    grid.axes_llc.set_yticks([-2, 0, 2])
Пример #5
0
def demo_grid_with_single_cbar(fig):
    """
    A grid of 2x2 images with a single colobar
    """
    grid = AxesGrid(
        fig,
        132,  # similar to subplot(132)
        nrows_ncols=(2, 2),
        axes_pad=0.0,
        share_all=True,
        label_mode="L",
        cbar_mode="single",
    )

    Z, extent = get_demo_image()
    for i in range(4):
        im = grid[i].imshow(Z, extent=extent, interpolation="nearest")
    plt.colorbar(im, cax=grid.cbar_axes[0])
    grid.cbar_axes[0].colorbar(im)

    # This affects all axes as share_all = True.
    grid.axes_llc.set_xticks([-2, 0, 2])
    grid.axes_llc.set_yticks([-2, 0, 2])
Пример #6
0
def plot(net, n, p):

    classname = net.__class__.__name__

    axes.set_xticks([])
    axes.set_yticks([])
    divider = make_axes_locatable(axes)
    subaxes = divider.new_vertical(1.0, pad=0.4, sharex=axes)
    fig.add_axes(subaxes)
    subaxes.set_xticks([])
    subaxes.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(2))
    subaxes.yaxis.set_ticks_position('right')
    subaxes.set_ylabel('Distortion')
    subaxes.set_xlabel('Time')

    Y = net.distortion[::1]
    X = np.arange(len(Y)) / float(len(Y) - 1)
    subaxes.plot(X, Y)

    if classname == 'NG':
        plt.title('Neural Gas', fontsize=20)
    elif classname == 'SOM':
        plt.title('Self-Organizing Map', fontsize=20)
    elif classname == 'DSOM':
        plt.title('Dynamic Self-Organizing Map', fontsize=20)

    axes.axis([0, 1, 0, 1])
    axes.set_aspect(1)

    bounds = divider.locate(0, 0).bounds
    grid = AxesGrid(fig,
                    bounds,
                    nrows_ncols=(n, n),
                    axes_pad=0.05,
                    label_mode="1")
    for row in range(n):
        for col in range(n):
            index = row * n + col
            Z = net.codebook[row, col].reshape(p, p)
            im = grid[index].imshow(Z,
                                    interpolation='nearest',
                                    vmin=0,
                                    vmax=1,
                                    cmap=plt.cm.hot)
            grid[index].set_yticks([])
            grid[index].set_xticks([])

    classname = net.__class__.__name__
    if classname == 'NG':
        axes.text(
            0.5,
            -0.01,
            r'$\lambda_i = %.3f,\lambda_f = %.3f, \varepsilon_i=%.3f, \varepsilon_f=%.3f$'
            % (net.sigma_i, net.sigma_f, net.lrate_i, net.lrate_f),
            fontsize=16,
            horizontalalignment='center',
            verticalalignment='top',
            transform=axes.transAxes)
    if classname == 'SOM':
        axes.text(
            0.5,
            -0.01,
            r'$\sigma_i = %.3f,\sigma_f = %.3f, \varepsilon_i=%.3f, \varepsilon_f=%.3f$'
            % (net.sigma_i, net.sigma_f, net.lrate_i, net.lrate_f),
            fontsize=16,
            horizontalalignment='center',
            verticalalignment='top',
            transform=axes.transAxes)
    elif classname == 'DSOM':
        axes.text(0.5,
                  -0.01,
                  r'$elasticity = %.2f$, $\varepsilon = %.3f$' %
                  (net.elasticity, net.lrate),
                  fontsize=16,
                  horizontalalignment='center',
                  verticalalignment='top',
                  transform=axes.transAxes)
Пример #7
0
    # This affects all axes as share_all = True.
    grid.axes_llc.set_xticks([-2, 0, 2])
    grid.axes_llc.set_yticks([-2, 0, 2])
"""

fig = plt.figure()
#fig.set_figheight(5)
#fig.set_figwidth(10)
#fig.subplots_adjust(right = 0.95)

grid = AxesGrid(
    fig,
    111,  # similar to subplot(132)
    nrows_ncols=(1, 2),
    aspect=True,
    axes_pad=1,
    share_all=False,
    label_mode="all",
    cbar_location="right",
    cbar_mode="single",
    cbar_pad="2%")

maxL = 5

Np = 5
ps = np.linspace(0.01, 0.99, Np)

lines1 = []
lines2 = []

for p in ps:
Пример #8
0
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid import AxesGrid
from demo_image import get_demo_image

F = plt.figure(1, (5.5, 3.5))
grid = AxesGrid(
    F,
    111,  # similar to subplot(111)
    nrows_ncols=(1, 3),
    axes_pad=0.1,
    add_all=True,
    label_mode="L",
)

Z, extent = get_demo_image()  # demo image

im1 = Z
im2 = Z[:, :10]
im3 = Z[:, 10:]
vmin, vmax = Z.min(), Z.max()
for i, im in enumerate([im1, im2, im3]):
    ax = grid[i]
    ax.imshow(im,
              origin="lower",
              vmin=vmin,
              vmax=vmax,
              interpolation="nearest")

plt.draw()
plt.show()
Пример #9
0
import os

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid import AxesGrid

from scikits.image.io import MultiImage
from scikits.image import data_dir

# Load the multi-layer image
fname = os.path.join(data_dir, 'multipage.tif')
img = MultiImage(fname)

# Create an image grid
fig = plt.figure()
grid = AxesGrid(fig,
                rect=(1, 1, 1),
                nrows_ncols=(1, 2),
                axes_pad=0.1)

# Plot the layers on the image grid
for i, frame in enumerate(img):
    grid[i].imshow(frame, cmap=plt.cm.gray)
    grid[i].set_xlabel('Frame %s' % i)
    grid[i].set_xticks([])
    grid[i].set_yticks([])

plt.show()
Пример #10
0
def Show2dArrayList(xs,
                    annotations=None,
                    normalize=True,
                    colorbar=False,
                    colorbars=False,
                    cols=None,
                    center_zero=True,
                    axes=None,
                    figure=None,
                    show=True,
                    title=None,
                    titles=None,
                    **args):
    """Display a list of 2-D arrays using matplotlib.

  :param xs: Input arrays.
  :type xs: iterable of 2D ndarray
  :param annotations: Small images to show with each array visualization.
  :type annotations: list of 2D ndarray
  :param bool normalize: Whether to use the same colormap range for all
     subplots.
  :param bool colorbar: Whether to show the meaning of the colormap as an extra
     subplot (implies *normalize* = True). Implies ``colorbars`` is False.
  :param bool colorbars: Whether to show a different colorbar for each subplot.
  :param int cols: Number of subplot columns to use.
  :param bool center_zero: When normalizing a range that spans zero, make sure
     zero is in the center of the colormap range.
  :param figure: The matplotlib figure into which to plot.
  :param bool show: Whether to show the figure on screen after it is drawn.
  :param str title: String to display above the set of plots.
  :param titles: Title string to include above each plotted array.
  :type titles: list of str
  :param vmin: Minimum value for colormap range.
  :param vmax: Maximum value for colormap range.
  :param mapper: Function to map locations in the foreground to corresponding
     locations in the background. (Required if *bg* is set.)

  Any remaining keyword arguments will be passed to
  :func:`matplotlib.pyplot.imshow` for each 2D array.

  """
    if 'vmin' in args and 'vmax' in args:
        vmin = args['vmin']
        vmax = args['vmax']
    elif colorbar or normalize:
        vmin = min([x.min() for x in xs])
        vmax = max([x.max() for x in xs])
        if center_zero and vmin < 0 and vmax > 0:
            vmax = max(abs(vmin), vmax)
            vmin = -vmax
        args = misc.MergeDict(args, vmin=vmin, vmax=vmax)
    if annotations == None:
        annotations = [None] * len(xs)
    else:
        assert len(annotations) == len(xs), \
            "Got %d arrays, but %d annotations (these numbers should match)" % \
            (len(xs), len(annotations))
        assert 'mapper' in args, "Using annotations requires a 'mapper'."
    if titles == None:
        titles = [""] * len(xs)
    else:
        assert len(titles) == len(xs), \
            "Got %d arrays, but %d title strings (these numbers should match)" % \
            (len(xs), len(titles))
    # Compute rows & cols
    max_plots = 64
    if len(xs) > max_plots:
        xs = xs[:max_plots]
    if cols == None:
        if len(xs) <= 16:
            cols = min(4, len(xs))
        else:
            cols = min(8, len(xs))
    rows = int(math.ceil(len(xs) / float(cols)))
    # Create the image grid
    if figure == None:
        figure = pyplot.gcf()
    figure.clf()
    if colorbar:
        grid_args = dict(cbar_location="right", cbar_mode="single")
    elif colorbars:
        grid_args = dict(cbar_location="right",
                         cbar_mode="each",
                         cbar_pad="2%")
    else:
        grid_args = {}
    grid = AxesGrid(
        figure,
        111,
        nrows_ncols=(rows, cols),
        axes_pad=0.5,
        share_all=True,
        label_mode="L",  # XXX value can be "L" or "1" -- what is this?
        **grid_args)
    if title is not None:
        figure.suptitle(title)
    # Add all subplots
    for i in range(len(xs)):
        Show2dArray(xs[i],
                    annotation=annotations[i],
                    axes=grid[i],
                    show=False,
                    title=titles[i],
                    **args)
    # Add the colorbar(s)
    if colorbar:
        img = grid[0].images[-1]
        grid.cbar_axes[0].colorbar(img)
        for cax in grid.cbar_axes:
            cax.toggle_label(True)
    elif colorbars:
        for i in range(len(xs)):
            img = grid[i].images[-1]
            ca = grid.cbar_axes[i]
            ca.colorbar(img)
            ca.toggle_label(True)
    if hasattr(figure, 'show') and show:
        figure.show()
Пример #11
0
def klfYoung():
    dbfile = '/u/jlu/data/gc/database/stars.sqlite'

    # Create a connection to the database file
    connection = sqlite.connect(dbfile)

    # Create a cursor object
    cur = connection.cursor()

    # Get info on the stars
    cur.execute('select * from stars where young = "T" and cuspPaper = "T"')

    rows = cur.fetchall()

    starCnt = len(rows)
    starName = []
    x = []
    y = []
    kp = []
    Ak = []
    starInField = []

    # Loop through each star and pull out the relevant information
    for ss in range(starCnt):
        record = rows[ss]

        name = record[0]

        # Check that we observed this star and what field it was in.
        cur.execute('select field from spectra where name = "%s"' % (name))

        row = cur.fetchone()
        if row != None:
            starInField.append(row[0])

            starName.append(name)
            kp.append(record[4])
            x.append(record[7])
            y.append(record[9])
            Ak.append(record[24])
        else:
            #print 'We do not have data on this star???'
            #starInField.append('C')
            continue

    starCnt = len(starName)
    starName = np.array(starName)
    starInField = np.array(starInField)
    x = np.array(x)
    y = np.array(y)
    kp = np.array(kp)
    Ak = np.array(Ak)

    # Now get the completeness corrections for each field.
    completenessFile = '/u/jlu/work/gc/imf/klf/2010_04_02/'
    completenessFile += 'completeness_extinct_correct.txt'
    completeness = asciidata.open(completenessFile)

    fields = ['C', 'E', 'SE', 'S', 'W', 'N', 'NE', 'SW', 'NW']

    compKp = completeness[0].tonumpy()

    comp = {}
    for ff in range(len(fields)):
        field = fields[ff]
        comp[field] = completeness[1 + ff].tonumpy()

    # Load up the areas for each field
    masksDir = '/u/jlu/work/gc/imf/klf/2010_04_02/osiris_fov/masks/'
    area = {}
    area['C'] = pyfits.getdata(masksDir + 'central.fits').sum() * 0.01**2
    area['E'] = pyfits.getdata(masksDir + 'east.fits').sum() * 0.01**2
    area['SE'] = pyfits.getdata(masksDir + 'southeast.fits').sum() * 0.01**2
    area['S'] = pyfits.getdata(masksDir + 'south.fits').sum() * 0.01**2
    area['W'] = pyfits.getdata(masksDir + 'west.fits').sum() * 0.01**2
    area['N'] = pyfits.getdata(masksDir + 'north.fits').sum() * 0.01**2
    area['NE'] = pyfits.getdata(masksDir + 'northeast.fits').sum() * 0.01**2
    area['SW'] = pyfits.getdata(masksDir + 'southwest.fits').sum() * 0.01**2
    area['NW'] = pyfits.getdata(masksDir + 'northwest.fits').sum() * 0.01**2

    KLFs = np.zeros((len(fields), len(compKp)), dtype=float)
    KLFs_ext = np.zeros((len(fields), len(compKp)), dtype=float)
    KLFs_ext_cmp = np.zeros((len(fields), len(compKp)), dtype=float)
    eKLFs_ext_cmp = np.zeros((len(fields), len(compKp)), dtype=float)

    kp_ext = kp - Ak + 3.0

    for ff in range(len(fields)):
        field = fields[ff]

        # Pull out all the stars in the field
        sdx = np.where(starInField == field)[0]

        kpInField = kp[sdx]
        AkInField = Ak[sdx]
        nameInField = starName[sdx]

        # Set all stars to Ak = 3
        kpInField_ext = kpInField - AkInField + 3.0

        # Make a binned luminosity function
        binSizeKp = compKp[1] - compKp[0]

        perAsec2Mag = area[field] * binSizeKp

        for kk in range(len(compKp)):
            kp_lo = compKp[kk]
            kp_hi = compKp[kk] + binSizeKp

            idx1 = np.where((kpInField >= kp_lo) & (kpInField < kp_hi))[0]
            KLFs[ff, kk] = len(idx1) / perAsec2Mag

            idx2 = np.where((kpInField_ext >= kp_lo)
                            & (kpInField_ext < kp_hi))[0]
            KLFs_ext[ff, kk] = len(idx2) / perAsec2Mag

            KLFs_ext_cmp[ff, kk] = KLFs_ext[ff, kk] / comp[field][kk]
            eKLFs_ext_cmp[ff, kk] = math.sqrt(len(idx2))
            eKLFs_ext_cmp[ff, kk] /= perAsec2Mag * comp[field][kk]

            idx = np.where(np.isnan(KLFs_ext_cmp[ff]) == True)[0]
            for ii in idx:
                KLFs_ext_cmp[ff, ii] = 0.0

    # ==========
    # Plot the KLF
    # ==========

    outputDir = '/u/jlu/work/gc/imf/klf/2010_04_02/plots/'

    py.clf()
    colors = [
        'blue', 'green', 'red', 'cyan', 'magenta', 'yellow', 'purple',
        'orange', 'brown'
    ]
    legendItems = []
    for ff in range(len(fields)):
        plt = py.plot(compKp, KLFs_ext_cmp[ff], 'k-', color=colors[ff])
        py.plot(compKp, KLFs_ext[ff], 'k--', color=colors[ff])
        #py.plot(compKp, KLFs[ff], 'k-.', color=colors[ff])
        legendItems.append(plt)

        print 'KLF for field ' + fields[ff]

    py.xlabel('Kp magnitude (A_Kp = 3)')
    py.ylabel('N_stars / (arcsec^2 mag)')
    py.legend(legendItems, fields, loc='upper left')
    py.savefig(outputDir + 'klf_young_fields_all.png')

    # Make a global KLF
    KLFall = KLFs_ext_cmp.sum(axis=0)
    KLFouter = KLFs_ext_cmp[1:, :].sum(axis=0)
    KLFinner = KLFs_ext_cmp[0, :]

    eKLFall = np.sqrt((eKLFs_ext_cmp**2).sum(axis=0))
    eKLFouter = np.sqrt((eKLFs_ext_cmp[1:, :]**2).sum(axis=0))
    eKLFinner = eKLFs_ext_cmp[0, :]

    p_compKp, p_KLFall = histNofill.convertForPlot(compKp, KLFall)
    p_compKp, p_KLFouter = histNofill.convertForPlot(compKp, KLFouter)
    p_compKp, p_KLFinner = histNofill.convertForPlot(compKp, KLFinner)

    py.clf()
    fig = py.figure(1)
    py.subplots_adjust(top=0.95, right=0.95)
    grid = AxesGrid(fig,
                    111,
                    nrows_ncols=(3, 1),
                    axes_pad=0.12,
                    add_all=True,
                    share_all=True,
                    aspect=False)
    grid[2].plot(p_compKp, p_KLFall, 'k-', linewidth=2)
    grid[2].errorbar(compKp + 0.25, KLFall, yerr=eKLFall, fmt='k.')
    grid[2].text(9.25, 25, 'KLF all')
    grid[2].set_xlabel('Kp magnitude (A_Kp = 3)')

    grid[1].plot(p_compKp, p_KLFouter, 'k-', linewidth=2)
    grid[1].errorbar(compKp + 0.25, KLFouter, yerr=eKLFouter, fmt='k.')
    grid[1].set_ylabel('N_stars / (arcsec^2 mag)')
    grid[1].text(9.25, 25, 'KLF outer')

    grid[0].plot(p_compKp, p_KLFinner, 'k-', linewidth=2)
    grid[0].errorbar(compKp + 0.25, KLFinner, yerr=eKLFinner, fmt='k.')
    grid[0].text(9.25, 25, 'KLF central')

    grid[0].set_xlim(9, 16)
    grid[0].set_ylim(0, 12)
    grid[1].set_ylim(0, 12)
    grid[2].set_ylim(0, 12)

    py.savefig(outputDir + 'klf_young_fields.png')

    py.clf()
    py.subplots_adjust(top=0.95, right=0.95)

    p1 = py.plot(p_compKp, p_KLFinner, 'k-', linewidth=2)
    py.errorbar(compKp + 0.25, KLFinner, yerr=eKLFinner, fmt='k.')
    p2 = py.plot(p_compKp, p_KLFouter, 'b-', linewidth=2)
    py.errorbar(compKp + 0.25, KLFouter, yerr=eKLFouter, fmt='b.')
    py.xlabel('Kp magnitude (A_Kp = 3)')
    py.ylabel('N_stars / (arcsec^2 mag)')
    py.legend((p1, p2), ('Inner', 'Outer'))
    py.xlim(9, 16)
    py.ylim(0, 12)

    py.savefig(outputDir + 'klf_young_fields_inout.png')

    # ==========
    # Convert to masses
    # Assume solar metallicity, A_K=3, distance = 8 kpc, age = 6 Myr
    # ==========
    genevaFile = '/u/jlu/work/models/geneva/iso/020/c/'
    genevaFile += 'iso_c020_0680.UBVRIJHKLM'
    model = asciidata.open(genevaFile)
    modMass = model[1].tonumpy()
    modV = model[6].tonumpy()
    modVK = model[11].tonumpy()
    modHK = model[15].tonumpy()

    modK = modV - modVK
    modH = modK + modHK

    # Convert from K to Kp (Wainscoat and Cowie 1992)
    modKp = modK + 0.22 * (modH - modK)

    dist = 8000.0
    distMod = -5.0 + 5.0 * math.log10(dist)

    # Convert our observed magnitudes to absolute magnitudes.
    # Use the differential extinction corrected individual magnitudes.
    # Also use the diff. ex. corrected and completeness corrected KLF.
    absKp = kp_ext - 3.0 - distMod
    absKpKLF = compKp - 3.0 - distMod
    p_absKpKLF = p_compKp - 3.0 - distMod

    # First, calculate the indvidiual masses
    modMassStar = np.zeros(len(absKp), dtype=float)
    modKpStar = np.zeros(len(absKp), dtype=float)
    for ii in range(len(absKp)):
        idx = abs(absKp[ii] - modKp).argmin()

        modMassStar[ii] = modMass[idx]
        modKpStar[ii] = modKp[idx]

    # Calculate the mass function
    modMassIMF = np.zeros(len(absKpKLF), dtype=float)
    modKpIMF = np.zeros(len(absKpKLF), dtype=float)
    for ii in range(len(absKpKLF)):
        idx = abs(absKpKLF[ii] - modKp).argmin()

        modMassIMF[ii] = modMass[idx]
        modKpIMF[ii] = modKp[idx]

    # Calculate the mass function we can plot
    p_modMassIMF = np.zeros(len(p_absKpKLF), dtype=float)
    p_modKpIMF = np.zeros(len(p_absKpKLF), dtype=float)
    for ii in range(len(p_absKpKLF)):
        idx = abs(p_absKpKLF[ii] - modKp).argmin()

        p_modMassIMF[ii] = modMass[idx]
        p_modKpIMF[ii] = modKp[idx]

    # ==========
    # Plot the masses and mass functions
    # ==========
    py.clf()
    py.plot(modMassStar, absKp, 'rs')
    py.plot(modMassStar, modKpStar, 'b.')
    py.xlabel('Mass (Msun)')
    py.ylabel('Kp (mag)')
    py.legend(('Observed Absolute', 'Model Absolute'))
    py.savefig(outputDir + 'pdmf_young_indiv.png')

    py.clf()
    py.plot(modMassIMF, KLFall, 'ks')
    py.plot(p_modMassIMF, p_KLFall, 'k-')
    py.xlabel('Mass (Msun)')
    py.ylabel('N')

    # Completeness correction (polynomial fits)
    comp = {
        'C': [44.6449, -14.4162, 1.75114, -0.0923230, 0.00177092],
        'E': [228.967, -71.9702, 8.43935, -0.435115, 0.00830836],
        'SE': [527.679, -172.892, 21.1500, -1.14200, 0.0229464],
        'S': [-293.901, 90.8734, -10.4823, 0.537018, -0.0103230],
        'W': [2476.22, -795.154, 95.1204, -5.02096, 0.0986629],
        'N': [334.286, -107.820, 12.8997, -0.676552, 0.0131203],
        'NE': [-686.107, 224.631, -27.3240, 1.46633, -0.0293125],
        'all':
        [-142.858, 58.5277, -9.49619, 0.768180, -0.0309478, 0.000495177]
    }

    # Make a mass function
    massEdges = 10**np.arange(1, 1.5, 0.05)
    massBins = massEdges[:-1] + ((massEdges[1:] - massEdges[:-1]) / 2.0)
    massHist = np.zeros(len(massBins), dtype=float)

    p_massBins = np.zeros(len(massBins) * 2, dtype=float)
    p_massHist = np.zeros(len(massBins) * 2, dtype=float)

    for mm in range(len(massBins)):
        m_lo = massEdges[mm]
        m_hi = massEdges[mm + 1]

        idx = np.where((modMassStar > m_lo) & (modMassStar <= m_hi))[0]

        # Find the completeness factor for this mass bin
        kpInBin = kp_ext[idx].mean()
        cmpCorr = comp['all'][0] + comp['all'][1]*kpInBin + \
            comp['all'][2]*kpInBin**2 + comp['all'][3]*kpInBin**3 +\
            comp['all'][4]*kpInBin**4 + comp['all'][5]*kpInBin**5

        print m_lo, m_hi, cmpCorr, len(idx), kpInBin
        massHist[mm] = len(idx)  # / cmpCorr

        p_massBins[2 * mm] = m_lo
        p_massBins[2 * mm + 1] = m_hi
        p_massHist[2 * mm] = len(idx)  # / cmpCorr
        p_massHist[2 * mm + 1] = len(idx)  # / cmpCorr

    py.clf()
    py.plot(p_massBins, p_massHist, 'k-')
    py.plot(massBins, massHist, 'ks')
    py.show()
Пример #12
0
    data_path + 'ngc6946_cross_robust_ca.fits',
    data_path + 'ngc6946_cross_robust_cs.fits',
    data_path + 'ngc6946_cross_robust.fits',
]
letters = ['a', 'b', 'c', 'd', 'e']
letters = ['(' + l + ')' for l in letters]
out_fname = data_path + 'ngc6946_cross_robust_maps_grid' + '.png'

# create grid
# figure
#plt.gray()
fig = plt.figure()
grid = AxesGrid(
    fig,
    111,
    nrows_ncols=(3, 2),
    axes_pad=0.0,
    share_all=True,
)
# loop on each map
for i, fname in enumerate(fname_ext):
    data = np.flipud(pyfits.fitsopen(fname)[0].data.T)
    if i == 0:
        data /= 8.
    data = data**.25
    data[np.isnan(data)] = 0
    extent = [0., 192., 0., 192.]
    im = grid[i].imshow(data, extent=extent, interpolation="nearest")
    grid[i].text(10, 170, letters[i], fontsize=20, color="white")
    data_zoom = data[135:155, 80:100, ]
    axins = zoomed_inset_axes(grid[i], 2, loc=3)  # zoom = 6
Пример #13
0
def sort_func(a, b):
    ai,aj = map(int, a.split(','))
    bi,bj = map(int, b.split(','))
    if bi > ai or (bi == ai and bj > aj): return -1
    return 1
bls.sort(cmp=sort_func)
if len(bls) == 0:
    print 'No data to plot.'
    sys.exit(0)
m2 = int(math.sqrt(len(bls)))
m1 = int(math.ceil(float(len(bls)) / m2))

# Generate all the plots
dmin,dmax = None, None
fig = p.figure()
grid = AxesGrid(fig,111,aspect=False,nrows_ncols=(m2,m1),axes_pad=0.,share_all=1,cbar_mode='single',cbar_location='top')
if not opts.src is None:fig.suptitle(opts.src)
for cnt, bl in enumerate(bls):
    d = n.ma.concatenate(plot_x[bl], axis=0)
    if opts.df: d = d[:,:-2]/2 + d[:,2:]/2 - d[:,1:-1]
    if opts.dt: d = d[:-2]/2 + d[2:]/2 - d[1:-1]
    if opts.fringe:
        d = d.filled(0)
        flags = n.where(d[:,0] != 0, 1., 0.)
        gain = n.sqrt(n.average(flags**2))
        ker = n.fft.ifft(flags)
        d = n.fft.ifft(d, axis=0)
        if not opts.clean is None:
            for chan in range(d.shape[1]):
                d[:,chan],info = a.deconv.clean(d[:,chan],ker,tol=opts.clean)
                d[:,chan] += info['res'] / gain
Пример #14
0
def plot_face_edge(isnap=28, selected_field='h2density', sizekpc=7., cutLow=1.e-5, f_out=None, save_plot=True,
                   overplot_clumps=True, incut=6., field_cut='h2density', n_cell_min=8, largeNum=1.e+42,
                   data=None, ds=None, dd=None, leaf_clumps=None, plotClumpID=False
                   ):
    """

    Parameters
    ----------
      isnap: int
             number of snaphot select for the plot

      selected_field: str
             field for image plot

      sizekpc: float
              size of the extracted region from isnap

      cutLow: float
              dynamical range for the colorbar

      f_out: str
             output filename

      save_plot: bool
             print to file

      overplot_clumps: bool
             overplot clumps

      incut: float
             threshold for clump definition

      field_cut: str
             field out of which clumps are identified

      n_cell_min: int
             min cell to define a clump

      largeNum: float
             BS to have YT to collaborate

    """

    if f_out is None:
        f_out = 'test_' + selected_field + '_out' + \
            str(isnap) + '_yt_unit_plot.png'

    from mpl_toolkits.axes_grid import AxesGrid
    import matplotlib.pyplot as plt

    # prepare input data, if not already passed as arguments
    #
    if data is None:
        data = import_fetch_gal(isnap=isnap)
    #
    if (ds is None) and (dd is None):
        ds, dd = prepare_unigrid(data=data,
                                 add_unit=True,
                                 regionsize_kpc=sizekpc,
                                 debug=False)
    #
    if overplot_clumps and (leaf_clumps is None):
        __, leaf_clumps = ytclumpfind_H2(ds, dd, field_cut, incut,
                                         c_max=None, step=1e+6,
                                         N_cell_min=n_cell_min, save=False,
                                         plot=False, saveplot=None, fold_out='./')

    if overplot_clumps:
        id_sorted = sorted(range(len(leaf_clumps)),
                           key=lambda x: np.sum(leaf_clumps[x]["density"]))

    # compute inertia tensor and it principal axes
    e_value, e_vectors = calculate_eigenvektoren(data=data, sizekpc=sizekpc)
    # references
    # los_vec = e_vectors[0,:] # face on
    # los_vec = e_vectors[1,:] # edge on
    # los_vec = e_vectors[2,:] # face on (again, perpendicular direction)
    #
    # set the camera axes along the principal axes of the inertia tensor
    vec_list = [e_vectors[2, :], e_vectors[1, :]]
    up_list = [e_vectors[0, :], e_vectors[0, :]]

    # setup the plot
    #
    fig = plt.figure()
    #
    grid = AxesGrid(fig, (0.075, 0.075, 0.85, 0.85),
                    nrows_ncols=(1, 2),
                    axes_pad=0.7,
                    #label_mode = "L",
                    label_mode="1",
                    share_all=True,
                    cbar_location="right",
                    cbar_mode="single",
                    cbar_size="3%",
                    cbar_pad=0.03)

    # plot edge on and face on
    #
    for iplot, los_vec, up_vec in zip(xrange(2), vec_list, up_list):

        prj = yt.OffAxisProjectionPlot(ds=ds, center=[0, 0, 0], normal=los_vec, fields=selected_field, width=(4, 'kpc'), north_vector=up_vec, weight_field='density',
                                       )

        prj.set_cmap(field=selected_field, cmap='inferno')

        if selected_field == 'density':
            selected_unit = 'Msun/pc**3'
        elif selected_field == 'h2density':
            selected_unit = '1/cm**3'
        else:
            raise TypeError('unit not implemented for the field')
        prj.set_unit(selected_field, selected_unit)
        prj.set_zlim(selected_field, cutLow * dd[selected_field].max().to(selected_unit),
                     dd[selected_field].max().to(selected_unit))

        # annotate clump if asked for
        if overplot_clumps:
            prj.annotate_contour(field=field_cut, ncont=1, factor=1,
                                 clim=(incut, largeNum), plot_args={
                                     'colors': 'white'}
                                 )  # to deal w/ stupid yt annotate_clump() bug

            for ileaf in id_sorted:
                _fc = np.mean(leaf_clumps[ileaf].data.fcoords[:], axis=0)

                if plotClumpID:
                    prj.annotate_marker(_fc,
                                        coord_system='data',
                                        plot_args={'color': 'red', 's': 50})
                    prj.annotate_text(_fc,
                                      ileaf + 1,
                                      coord_system='data',
                                      text_args={'color': 'red', 'size': 25},
                                      inset_box_args={'boxstyle': 'square',
                                                      'facecolor': 'white',
                                                      'linewidth': 1.0,
                                                      'edgecolor': 'white',
                                                      'alpha': 0.})

        prj.set_ylabel('kpc')
        prj.set_xlabel('kpc')
        prj.set_font({'family': 'Times',  # 'style': 'italic',
                          # 'weight': 'bold',
                          'size': 26})

        # set the plot into the grid
        plot = prj.plots[selected_field]
        plot.figure = fig
        plot.axes = grid[iplot].axes
        plot.cax = grid.cbar_axes[iplot]

        if iplot == 1:
            plot.axes.set_axis_off()
            # plot.axes.set_label('')
            # plot.axes.set_visible(False)
            plot.axes.set_xlabel('')
            plot.axes.set_xticks(())
            plot.axes.set_xticklabels('')

        # Finally, this actually redraws the plot.
        prj._setup_plots()

    for cax in grid.cbar_axes:
        cax.toggle_label(True)
        # cax.axis[cax.orientation].set_label(field_select)

    if save_plot:

        prj.save(f_out, mpl_kwargs={'bbox_inches': 'tight'})
        print 'dump to ', f_out

    return prj, plot.axes
Пример #15
0
im0 = data[..., idx].copy()
m = np.mean(data, axis=-1)
for i in xrange(data.shape[-1]):
    data[..., i] -= m

im = data[..., idx]
im_fht = fht.fht(im0)
im_fht[0, 0] = 0.

# figure
fig = pl.figure()
pl.gray()
grid = AxesGrid(
    fig,
    111,
    nrows_ncols=(3, 1),
    axes_pad=0.0,
    share_all=True,
    #                cbar_mode="each",
)

ims = grid[0].imshow(im0, interpolation="nearest")
grid[0].text(2, 4, '(a)', fontsize=20, color="white")

grid[0].set_xticks(())
grid[0].set_yticks(())

ims = grid[1].imshow(im, interpolation="nearest")
grid[1].text(2, 4, '(b)', fontsize=20, color="white")
#grid.cbar_axes[0].colorbar(ims)

ims = grid[2].imshow(im_fht, interpolation="nearest")
Пример #16
0
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid import AxesGrid
import numpy as np

im = np.arange(100)
im.shape = 10, 10

fig = plt.figure(1, (4., 4.))
grid = AxesGrid(
    fig,
    111,  # similar to subplot(111)
    nrows_ncols=(2, 2),  # creates 2x2 grid of axes
    axes_pad=0.1,  # pad between axes in inch.
)

for i in range(4):
    grid[i].imshow(im)  # The AxesGrid object work as a list of axes.

plt.show()