def check_vpd_ks2_astrometry():
    """
    Check the VPD and quiver plots for our KS2-extracted, re-transformed astrometry.
    """
    catFile = workDir + '20.KS2_PMA/wd1_catalog.fits'
    tab = atpy.Table(catFile)

    good = (tab.xe_160 < 0.05) & (tab.ye_160 < 0.05) & \
        (tab.xe_814 < 0.05) & (tab.ye_814 < 0.05) & \
        (tab.me_814 < 0.05) & (tab.me_160 < 0.05)

    tab2 = tab.where(good)

    dx = (tab2.x_160 - tab2.x_814) * ast.scale['WFC'] * 1e3
    dy = (tab2.y_160 - tab2.y_814) * ast.scale['WFC'] * 1e3

    py.clf()
    q = py.quiver(tab2.x_814, tab2.y_814, dx, dy, scale=5e2)
    py.quiverkey(q, 0.95, 0.85, 5, '5 mas', color='red', labelcolor='red')
    py.savefig(workDir + '20.KS2_PMA/vec_diffs_ks2_all.png')

    py.clf()
    py.plot(dy, dx, 'k.', ms=2)
    lim = 30
    py.axis([-lim, lim, -lim, lim])
    py.xlabel('Y Proper Motion (mas)')
    py.ylabel('X Proper Motion (mas)')
    py.savefig(workDir + '20.KS2_PMA/vpd_ks2_all.png')

    idx = np.where((np.abs(dx) < 10) & (np.abs(dy) < 10))[0]
    print('Cluster Members (within dx < 10 mas and dy < 10 mas)')
    print(('   dx = {dx:6.2f} +/- {dxe:6.2f} mas'.format(dx=dx[idx].mean(),
                                                        dxe=dx[idx].std())))
    print(('   dy = {dy:6.2f} +/- {dye:6.2f} mas'.format(dy=dy[idx].mean(),
                                                        dye=dy[idx].std())))
예제 #2
0
def plot_vector_diff_F160W():
    """
    Using the xym2mat analysis on the F160W filter in the 2010 data set,
    plot up the positional offset vectors for each reference star in
    each star list relative to the average list. This should show
    us if there are systematic problems with the distortion solution
    or PSF variations.
    """
    x, y, m, xe, ye, me, cnt = load_catalog()

    dx = x - x[0]
    dy = y - y[0]
    dr = np.hypot(dx, dy)

    py.clf()
    py.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95)

    for ii in range(1, x.shape[0]):
        idx = np.where((x[ii,:] != 0) & (y[ii,:] != 0) & (dr[ii,:] < 0.1) &
                       (xe < 0.05) & (ye < 0.05))[0]

        py.clf()
        q = py.quiver(x[0,idx], y[0,idx], dx[ii, idx], dy[ii, idx], scale=1.0)
        py.quiverkey(q, 0.9, 0.9, 0.03333, label='2 mas', color='red')
        py.title('{0} stars in list {1}'.format(len(idx), ii))
        py.xlim(0, 4500)
        py.ylim(0, 4500)

        foo = input('Continue?')
        if foo == 'q' or foo == 'Q':
            break
예제 #3
0
def plot_vector_diff_F160W():
    """
    Using the xym2mat analysis on the F160W filter in the 2010 data set,
    plot up the positional offset vectors for each reference star in
    each star list relative to the average list. This should show
    us if there are systematic problems with the distortion solution
    or PSF variations.
    """
    x, y, m, xe, ye, me, cnt = load_catalog()

    dx = x - x[0]
    dy = y - y[0]
    dr = np.hypot(dx, dy)

    py.clf()
    py.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95)

    for ii in range(1, x.shape[0]):
        idx = np.where((x[ii, :] != 0) & (y[ii, :] != 0) & (dr[ii, :] < 0.1)
                       & (xe < 0.05) & (ye < 0.05))[0]

        py.clf()
        q = py.quiver(x[0, idx],
                      y[0, idx],
                      dx[ii, idx],
                      dy[ii, idx],
                      scale=1.0)
        py.quiverkey(q, 0.9, 0.9, 0.03333, label='2 mas', color='red')
        py.title('{0} stars in list {1}'.format(len(idx), ii))
        py.xlim(0, 4500)
        py.ylim(0, 4500)

        foo = raw_input('Continue?')
        if foo == 'q' or foo == 'Q':
            break
예제 #4
0
def check_vpd_ks2_astrometry():
    """
    Check the VPD and quiver plots for our KS2-extracted, re-transformed astrometry.
    """
    catFile = workDir + '20.KS2_PMA/wd1_catalog.fits'
    tab = atpy.Table(catFile)

    good = (tab.xe_160 < 0.05) & (tab.ye_160 < 0.05) & \
        (tab.xe_814 < 0.05) & (tab.ye_814 < 0.05) & \
        (tab.me_814 < 0.05) & (tab.me_160 < 0.05)

    tab2 = tab.where(good)

    dx = (tab2.x_160 - tab2.x_814) * ast.scale['WFC'] * 1e3
    dy = (tab2.y_160 - tab2.y_814) * ast.scale['WFC'] * 1e3

    py.clf()
    q = py.quiver(tab2.x_814, tab2.y_814, dx, dy, scale=5e2)
    py.quiverkey(q, 0.95, 0.85, 5, '5 mas', color='red', labelcolor='red')
    py.savefig(workDir + '20.KS2_PMA/vec_diffs_ks2_all.png')

    py.clf()
    py.plot(dy, dx, 'k.', ms=2)
    lim = 30
    py.axis([-lim, lim, -lim, lim])
    py.xlabel('Y Proper Motion (mas)')
    py.ylabel('X Proper Motion (mas)')
    py.savefig(workDir + '20.KS2_PMA/vpd_ks2_all.png')

    idx = np.where((np.abs(dx) < 10) & (np.abs(dy) < 10))[0]
    print('Cluster Members (within dx < 10 mas and dy < 10 mas)')
    print(('   dx = {dx:6.2f} +/- {dxe:6.2f} mas'.format(dx=dx[idx].mean(),
                                                        dxe=dx[idx].std())))
    print(('   dy = {dy:6.2f} +/- {dye:6.2f} mas'.format(dy=dy[idx].mean(),
                                                        dye=dy[idx].std())))
예제 #5
0
def plot_residuals_year_2pos(year, filt, pos1, pos2, refresh=False):
    year = str(year) 
    
    dir_xym = year + '_' + filt + '/01.XYM/'

    # Try to read from a FITS table of compiled data if possible.
    if refresh == True:
        make_residuals_table_year_2pos(year, filt, pos1, pos2)

    d = read_residuals_table_year_2pos(year, filt, pos1, pos2)

    print d.xstd_p.min(), d.xstd_p.max()

    # Remember, this was all aligned to F814W in ACS. So there is a
    # relative scale change between the transformed and the raw pixels.
    # We need to put evertyhing back on the same scale.
    # The plate scale was 0.411095 (pulled from TRANS.xym2mat.ref4)
    scale = 0.411095

    dx1 = d.xmean_p[0, :] - d.stars['x']
    dx2 = d.xmean_p[1, :] - d.stars['x']
    dy1 = d.ymean_p[0, :] - d.stars['y']
    dy2 = d.ymean_p[1, :] - d.stars['y']
    lim = 0.06
    idx = np.where((np.abs(dx1) < lim) & (np.abs(dy1) < lim) & 
                   (np.abs(dx2) < lim) & (np.abs(dy2) < lim))[0]

    # Plot the offsets for each position on a common coordinate system.
    py.clf()
    q1 = py.quiver(d.xmean[idx], d.ymean[idx], dx1[idx], dy1[idx], 
                   color='red', scale=1.8)
    q1 = py.quiver(d.xmean[idx], d.ymean[idx], dx2[idx], dy2[idx], 
                   color='blue', scale=1.8)
    py.quiverkey(q1, -0.1, -0.12, 0.02/scale, '0.02 WFC3IR pixels')
    py.axis('equal')
    py.xlabel("X (pixels)")
    py.ylabel("Y (pixels)")
    py.title(year + ',' + filt + ',' + pos1 + ',' + pos2)
    py.savefig('plots/resid_final_{0}_{1}_{2}_{3}.png'.format(year, filt, pos1, pos2))

    # Plot the offsets for each position on the raw coordinate system.
    py.clf()
    xraw1 = d.xraw[0,:,:].mean(axis=0)
    yraw1 = d.yraw[0,:,:].mean(axis=0)
    xraw2 = d.xraw[1,:,:].mean(axis=0)
    yraw2 = d.yraw[1,:,:].mean(axis=0)
    
    q1 = py.quiver(xraw1[idx], yraw1[idx], dx1[idx], dy1[idx], 
                   color='red', scale=1.8)
    q1 = py.quiver(xraw2[idx], yraw2[idx], dx2[idx], dy2[idx], 
                   color='blue', scale=1.8)
    py.quiverkey(q1, -0.1, -0.12, 0.02/scale, '0.02 WFC3IR pixels')
    py.axis('equal')
    py.xlabel("X (pixels)")
    py.ylabel("Y (pixels)")
    py.title(year + ',' + filt + ',' + pos1 + ',' + pos2)
    py.savefig('plots/resid_raw_{0}_{1}_{2}_{3}.png'.format(year, filt, pos1, pos2))
예제 #6
0
 def add_currkey(handle):
     pos = Data['kcurrpos'][ifig]
     if pos:
         pl.quiverkey(handle,
                      pos[0],
                      pos[1],
                      lcurr,
                      '%s m/s' % str(lcurr),
                      labelpos='S',
                      coordinates='axes')
예제 #7
0
 def add_currkey(handle):
     Data, err = opt.get_plconf(plconf, 'HSLICES')
     pos = Data['kcurrpos'][ifig]
     if pos:
         pl.quiverkey(handle,
                      pos[0],
                      pos[1],
                      lcurr,
                      '%s m/s' % str(lcurr),
                      labelpos='S',
                      coordinates='axes')
예제 #8
0
def main(argv=None):
    if argv is None:
        argv = sys.argv
    iresfile = argv[1]
    try:
        ct = float(argv[2])
    except:
        ct = 0.0
    ires = adore.res2dict(iresfile)
    A = ires['fine_coreg']['results']
    A = A[A[:, 5] > ct, :]
    az = int(ires['fine_coreg']['Initial offsets'].split(',')[0])
    rg = int(ires['fine_coreg']['Initial offsets'].split(',')[1])
    #figure1
    pylab.figure()
    pylab.title('Fine Correlation Results')
    Q = pylab.quiver(A[:, 2], A[:, 1], A[:, 4], A[:, 3], A[:, 5])
    azAvg = round(pylab.np.mean(A[:, 3]))
    rgAvg = round(pylab.np.mean(A[:, 4]))
    qk = pylab.quiverkey(Q,
                         0.33,
                         0.92,
                         azAvg, ('%d [px az]' % (azAvg)),
                         labelpos='W',
                         fontproperties={'weight': 'bold'})
    qk = pylab.quiverkey(Q,
                         0.66,
                         0.92,
                         rgAvg, ('%d [px rg]' % (rgAvg)),
                         labelpos='W',
                         fontproperties={'weight': 'bold'})
    pylab.colorbar()

    #figure2
    pylab.figure()
    pylab.title('Fine Correlation Deviations')
    pylab.quiver(A[:, 2], A[:, 1], A[:, 4] - rg, A[:, 3] - az, A[:, 5])
    Q = pylab.quiver(A[:, 2], A[:, 1], A[:, 4] - rg, A[:, 3] - az, A[:, 5])
    azStd = round(pylab.np.std(A[:, 3] - az))
    rgStd = round(pylab.np.std(A[:, 4] - rg))
    qk = pylab.quiverkey(Q,
                         0.33,
                         0.92,
                         azStd, ('%d [px az]' % (azStd)),
                         labelpos='W',
                         fontproperties={'weight': 'bold'})
    qk = pylab.quiverkey(Q,
                         0.66,
                         0.92,
                         rgStd, ('%d [px rg]' % (rgStd)),
                         labelpos='W',
                         fontproperties={'weight': 'bold'})
    pylab.colorbar()
    pylab.show()
    def PlotBaseFly(self):
        self.BaseFly()
        # Creates lists of x and y coordinates
        x_coords = [0, (self.displ * numpy.cos(self.head * (2 * numpy.pi) / 360))]
        y_coords = [0, (self.displ * numpy.sin(self.head * (2 * numpy.pi) / 360))]

        fig = pylab.figure()
        # Adjusts margins
        fig.subplots_adjust(left=None, bottom=0.2, right=None, top=None, wspace=None, hspace=None)

        # Plots start point
        pylab.plot(x_coords[0], y_coords[0], self.marker1, markersize=10, label='Start')
        # Plots end point
        pylab.plot(x_coords[1], y_coords[1], self.marker2, markersize=10, label='End')

        # Generates 2D wind vector field
        if self.displ < 10:
            X, Y = numpy.meshgrid(numpy.arange(-30, 30, 6), numpy.arange(-30, 30, 6))
            Q = pylab.quiver(X, Y, self.wind_U, self.wind_V, label='Wind Direction')
            QK = pylab.quiverkey(Q, 0.1, -0.08, 10, 'Wind Direction', labelpos='W',
                                 fontproperties={'weight': 'bold'})
        else:
            X, Y = numpy.meshgrid(numpy.arange(-self.displ - 20, self.displ + 20, self.displ / 5), numpy.arange(-self.displ - 20, self.displ + 20, self.displ / 5))
            Q = pylab.quiver(X, Y, self.wind_U, self.wind_V, label='Wind Direction')
            QK = pylab.quiverkey(Q, 0.1, -0.08, self.displ / 5, 'Wind Direction', labelpos='W',
                                 fontproperties={'weight': 'bold'})

        # Shows displ, head, time
        # Refer to http://docs.python.org/2/library/string.html for formatting
        # and http://stackoverflow.com/questions/19261089/how-to-use-new-style-string-formatting-in-matplotlib-figure-text
        '''
        Text = '{0} {1:10}\n'.format('Displacement: ', int(self.displ)) + \
               '{0} {1:10}\n'.format('Heading:         ', int(self.head)) + \
               '{0} {1:10}\n'.format('Flight Time:  ', int(self.time))

        fig.text(0.25, -0.01, Text, family='monospace')
        '''

        TextL = 'Displacement (m):\nHeading (Degrees):\nDescent Time (s):'
        TextR = str(int(self.displ)) + '\n' + str(int(self.head)) + '\n' + str(int(self.time))
        fig.text(0.4, 0.01, TextL, multialignment='left')
        fig.text(0.6, 0.01, TextR, multialignment='right')

        pylab.title('UAV Displacement in Y against UAV Displacement in X')
        pylab.xlabel('UAV Displacement in X')
        pylab.ylabel('UAV Displacement in Y')
        pylab.xlim(-self.displ - 20, self.displ + 20)
        pylab.ylim(-self.displ - 20, self.displ + 20)

        pylab.legend()

        pylab.show()
예제 #10
0
def main(argv=None):
    if argv is None:
        argv = sys.argv
    drsfile = argv[1]
    try:
        ct = float(argv[2])
    except:
        ct = 0.0
    if drsfile is not None:
        d = adore.drs2dict(drsfile)
        mresfile = d['general']['m_resfile'].strip()
        sresfile = d['general']['s_resfile'].strip()
        iresfile = d['general']['i_resfile'].strip()

    iobj = adore.dict2obj(adore.res2dict(iresfile))
    mobj = adore.dict2obj(adore.res2dict(mresfile))
    sobj = adore.dict2obj(adore.res2dict(sresfile))
    A = iobj.fine_coreg.results
    #ires['fine_coreg']['results'];
    A = A[A[:, 5] > ct, :]

    #figure
    pylab.figure()
    pylab.title('Range: Fine Correlation - Coregistration Polynomial')
    rg = adore.basic.rescale(
        A[:, 2], [-2, 2], arrlim=[mobj.crop.First_pixel, mobj.crop.Last_pixel])
    az = adore.basic.rescale(
        A[:, 1], [-2, 2], arrlim=[mobj.crop.First_line, mobj.crop.Last_line])
    pixelOffset = adore.polyval(rg, az,
                                iobj.comp_coregpm.Estimated_coefficientsP)
    lineOffset = adore.polyval(rg, az,
                               iobj.comp_coregpm.Estimated_coefficientsL)
    Q = pylab.quiver(A[:, 2], A[:, 1], A[:, 4] - pixelOffset,
                     A[:, 3] - lineOffset, A[:, 5])
    azStd = round(pylab.np.std(A[:, 3] - lineOffset))
    rgStd = round(pylab.np.std(A[:, 4] - pixelOffset))
    qk = pylab.quiverkey(Q,
                         0.33,
                         0.92,
                         azStd, ('%d [px az]' % (azStd)),
                         labelpos='W',
                         fontproperties={'weight': 'bold'})
    qk = pylab.quiverkey(Q,
                         0.66,
                         0.92,
                         rgStd, ('%d [px rg]' % (rgStd)),
                         labelpos='W',
                         fontproperties={'weight': 'bold'})
    pylab.colorbar()
    pylab.show()
예제 #11
0
def main(argv=None):
    if argv is None:
        argv = sys.argv
    iresfile = argv[1]
    ires = adore.res2dict(iresfile)
    A = ires['coarse_correl']['results']
    az = ires['coarse_correl']['Coarse_correlation_translation_lines']
    rg = ires['coarse_correl']['Coarse_correlation_translation_pixels']
    #figure1
    pylab.figure()
    pylab.title('Coarse Correlation Results')
    Q = pylab.quiver(A[:, 2], A[:, 1], A[:, 5], A[:, 4], A[:, 3])
    azAvg = round(pylab.np.mean(A[:, 3]))
    rgAvg = round(pylab.np.mean(A[:, 4]))
    qk = pylab.quiverkey(Q,
                         0.33,
                         0.92,
                         azAvg, ('%d [px az]' % (azAvg)),
                         labelpos='W',
                         fontproperties={'weight': 'bold'})
    qk = pylab.quiverkey(Q,
                         0.66,
                         0.92,
                         rgAvg, ('%d [px rg]' % (rgAvg)),
                         labelpos='W',
                         fontproperties={'weight': 'bold'})
    pylab.colorbar()

    #figure2
    pylab.figure()
    pylab.title('Coarse Correlation Deviations')
    Q = pylab.quiver(A[:, 2], A[:, 1], A[:, 5] - rg, A[:, 4] - az, A[:, 3])
    azStd = round(pylab.np.std(A[:, 3] - az))
    rgStd = round(pylab.np.std(A[:, 4] - rg))
    qk = pylab.quiverkey(Q,
                         0.33,
                         0.92,
                         azStd, ('%d [px az]' % (azStd)),
                         labelpos='W',
                         fontproperties={'weight': 'bold'})
    qk = pylab.quiverkey(Q,
                         0.66,
                         0.92,
                         rgStd, ('%d [px rg]' % (rgStd)),
                         labelpos='W',
                         fontproperties={'weight': 'bold'})

    pylab.colorbar()
    pylab.show()
예제 #12
0
def test_darPlusDistortion():
    data_dir = module_dir + '/distortion/'
    file_geox_darunfix = data_dir + 'nirc2dist_xgeoim.fits'
    file_geoy_darunfix = data_dir + 'nirc2dist_ygeoim.fits'

    data_dir = '/u/ghezgroup/data/m92_test/08jul_new_on/'
    file_geox_darfix = data_dir + 'reduce/kp/gc_f1/ce0249geo_x.fits'
    file_geoy_darfix = data_dir + 'reduce/kp/gc_f1/ce0249geo_y.fits'

    xon = pyfits.getdata(file_geox_darfix)
    yon = pyfits.getdata(file_geoy_darfix)
    xoff = pyfits.getdata(file_geox_darunfix)
    yoff = pyfits.getdata(file_geoy_darunfix)

    # Make arrays with the coordinates for each
    imgsize = 1024
    axisX = np.arange(imgsize, dtype=float)
    axisY = np.arange(imgsize, dtype=float)
    xcoo2d, ycoo2d = np.meshgrid(axisX, axisY)

    # Lets trim so that we only keep every 20th pixel
    idx = np.arange(25, imgsize, 50)
    xon = xon.take(idx, axis=0).take(idx, axis=1)
    yon = yon.take(idx, axis=0).take(idx, axis=1)
    xoff = xoff.take(idx, axis=0).take(idx, axis=1)
    yoff = yoff.take(idx, axis=0).take(idx, axis=1)
    xcoo2d = xcoo2d.take(idx, axis=0).take(idx, axis=1)
    ycoo2d = ycoo2d.take(idx, axis=0).take(idx, axis=1)

    # Calculate differences
    xdiff = xon - xoff
    ydiff = yon - yoff

    # Make vector plots
    py.clf()
    qvr = py.quiver2([xcoo2d], [ycoo2d], [xdiff], [ydiff],
                     units='width',
                     scale=5,
                     width=0.005,
                     headwidth=3,
                     headlength=3,
                     headaxislength=3)
    py.quiverkey(qvr, 100, 1120, 1.0, '1 pixel', coordinates='data', color='r')
    py.xlabel('NIRC2 X (pixel)')
    py.ylabel('NIRC2 Y (pixel)')
    py.title('Arrows point to DAR Fix')
    #py.savefig('plots/vector_daroffon.png')
    py.show()
예제 #13
0
def show_shwfs_vecs(
    shiftvec, subaps, refpos=None, img=None, extent=None, title=None, scale=10, pause=False, fignum=None, keep=True
):
    """
	Show a SHWFS measurements with subapertures and potentially a background 
	image. If **refpos** is given, SHWFS shift vectors will be plotted at 
	those locations, otherwise at the center of the sub apertures.

	Additionally, a background image (wavefront, sensor image) can be 
	plotted along with the measurements in the background. If the coordinate 
	system is different than that of the sub apertures, this can be fixed by 
	using the **extent** keyword.

	**Scale** tweaks the arrow length, unity being the approximate real size.
	The default is 10 to enhance the visibility.

	@param [in] shiftvec (N,2) vector with shifts
	@param [in] subaps (N,4) vector with sub aperture positions as (low0, high0, low1, high1)
	@param [in] refpos Positions to plot shift vectors at (if None use subaps center)
	@param [in] img Background image, e.g. a wavefront
	@param [in] extent Extent for the image for imshow()
	@param [in] title Plot title
	@param [in] scale Scale used for arrow width, unity is approximately
	@param [in] pause Pause before continuing
	@param [in] fignum Figure number to use for figure()
	@param [in] keep Keep plot window open after returning
	"""

    import pylab as plt
    from matplotlib.collections import PatchCollection

    sasize = np.r_[subaps[:, :2].ptp(1).mean(), subaps[:, 2:].ptp(1).mean()]
    subaps_im = [
        plt.Rectangle((subap[1], subap[0]), sasize[0], sasize[1], fc="none", ec="k") for subap in subaps[:, ::2]
    ]

    plt.figure(fignum)
    plt.clf()
    plt.title(title or "SHWFS vectors on MLA grid")

    if img != None:
        plt.imshow(img, extent=extent)

    if refpos == None:
        refpos = subaps[:, ::2] + sasize / 2

    q = plt.quiver(
        refpos[:, 1], refpos[:, 0], shiftvec[:, 1], shiftvec[:, 0], angles="xy", scale=refpos.ptp() / 10.0, color="r"
    )
    p = plt.quiverkey(q, refpos.min(0)[1], refpos.min(0)[0], 5, "5 pix.", coordinates="data", color="r")

    thisgca = plt.gca()
    thisgca.add_collection(PatchCollection(subaps_im, match_original=True))

    if pause:
        raw_input("Press any key to continue...")
    if not keep:
        plt.close()
예제 #14
0
def test_darPlusDistortion():
    data_dir = module_dir + '/distortion/'
    file_geox_darunfix = data_dir + 'nirc2dist_xgeoim.fits'
    file_geoy_darunfix = data_dir + 'nirc2dist_ygeoim.fits'

    data_dir = '/u/ghezgroup/data/m92_test/08jul_new_on/'
    file_geox_darfix = data_dir + 'reduce/kp/gc_f1/ce0249geo_x.fits'
    file_geoy_darfix = data_dir + 'reduce/kp/gc_f1/ce0249geo_y.fits'

    xon = pyfits.getdata(file_geox_darfix)
    yon = pyfits.getdata(file_geoy_darfix)
    xoff = pyfits.getdata(file_geox_darunfix)
    yoff = pyfits.getdata(file_geoy_darunfix)

    # Make arrays with the coordinates for each 
    imgsize = 1024
    axisX = np.arange(imgsize, dtype=float)
    axisY = np.arange(imgsize, dtype=float)
    xcoo2d, ycoo2d = np.meshgrid(axisX, axisY)

    # Lets trim so that we only keep every 20th pixel
    idx = np.arange(25, imgsize, 50)
    xon = xon.take(idx, axis=0).take(idx, axis=1)
    yon = yon.take(idx, axis=0).take(idx, axis=1)
    xoff = xoff.take(idx, axis=0).take(idx, axis=1)
    yoff = yoff.take(idx, axis=0).take(idx, axis=1)
    xcoo2d = xcoo2d.take(idx, axis=0).take(idx, axis=1)
    ycoo2d = ycoo2d.take(idx, axis=0).take(idx, axis=1)

    # Calculate differences
    xdiff = xon - xoff
    ydiff = yon - yoff

    # Make vector plots
    py.clf()
    qvr = py.quiver2([xcoo2d], [ycoo2d], [xdiff], [ydiff],
                     units='width', scale=5, 
                     width=0.005, headwidth=3, headlength=3, 
                     headaxislength=3)
    py.quiverkey(qvr, 100, 1120, 1.0, '1 pixel', coordinates='data', color='r')
    py.xlabel('NIRC2 X (pixel)')
    py.ylabel('NIRC2 Y (pixel)')
    py.title('Arrows point to DAR Fix')
    #py.savefig('plots/vector_daroffon.png')
    py.show()
def plot_arches_pm():
    """
    Plot the proper motion vectors for the Arches (Clarkson+ 2012).
    """
    dataFile = '/u/jlu/data/arches/clarkson2012_table5.txt'

    d = atpy.Table(dataFile, type='mrt')

    # Put into a "field" reference frame.
    idx = np.where(d.FMem > 0.9)[0]
    f_pmX = d.pmX[idx].mean()
    f_pmY = d.pmY[idx].mean()

    d.pmX -= f_pmX
    d.pmY -= f_pmY

    py.clf()
    Q = py.quiver(d.DelX, d.DelY, d.pmX, d.pmY)
    py.quiverkey(Q, 95, 95, 1, '40 km/s', coordinates='figure')
예제 #16
0
def plot_arches_pm():
    """
    Plot the proper motion vectors for the Arches (Clarkson+ 2012).
    """
    dataFile = "/u/jlu/data/arches/clarkson2012_table5.txt"

    d = atpy.Table(dataFile, type="mrt")

    # Put into a "field" reference frame.
    idx = np.where(d.FMem > 0.9)[0]
    f_pmX = d.pmX[idx].mean()
    f_pmY = d.pmY[idx].mean()

    d.pmX -= f_pmX
    d.pmY -= f_pmY

    py.clf()
    Q = py.quiver(d.DelX, d.DelY, d.pmX, d.pmY)
    py.quiverkey(Q, 95, 95, 1, "40 km/s", coordinates="figure")
예제 #17
0
    def sliceuv(self, ind, time=0, plot=False, **opts):
        savename = False
        if savename in opts.keys(): savename = opts['savename']

        if ind == 'bar':
            isK, uname, vname, ind = True, 'ubar', 'vbar', 9999
        elif ind in ('s', 'surf', 'surface'):
            isK, uname, vname, ind = True, 'u', 'v', -1
        elif ind >= 0:
            isK, uname, vname, ind = True, 'u', 'v', ind
        elif ind < 0:
            isK = False
            isK, uname, vname, ind = False, 'u', 'v', ind

        if isK:
            xu, yu, zu, u = self.slicek(uname, ind, time)
            xv, yv, zv, v = self.slicek(vname, ind, time)
        else:
            xu, yu, zu, u = self.slicez(uname, ind, time)
            xv, yv, zv, v = self.slicez(vname, ind, time)

        z = (zu[1:, :] + zu[:-1, :]) / 2.
        u = (u[1:, :] + u[:-1, :]) / 2.
        v = (v[:, 1:] + v[:, :-1]) / 2.

        x = self.grid.lonp
        y = self.grid.latp

        # rotate uv:
        ang = rt.rho2uvp(self.grid.angle, 'p')
        u, v = calc.rot2d(u, v, -ang)

        if plot:
            p = self.grid.plot(bathy=None)
            xm, ym = p(x, y)
            mm = 0 * m
            mm[::3, ::3] = 1
            mm = mm * m == 1
            s = np.sqrt(u**2 + v**2)
            q = pylab.quiver(xm[mm], ym[mm], u[mm], v[mm], s[mm])
            pylab.colorbar(shrink=.7)
            pylab.axis([p.xmin, p.xmax, p.ymin, p.ymax])
            qk = pylab.quiverkey(q,
                                 .05,
                                 .01,
                                 0.2,
                                 '0.2 m/s',
                                 labelpos='E',
                                 coordinates='axes')
            if savename:
                pylab.savefig(savename, dpi=pylab.gcf().dpi)
                pylab.close(pylab.gcf())

        return x, y, z, u, v
예제 #18
0
def plot_vpd_align(alignRoot, epoch1, epoch2, outRoot='plot_align'):
    """
    Read in an aligned data set. Plot a vector-point-diagram for the 
    positional differences between two different epochs within the data set.
    """
    s = starset.StarSet(alignRoot)

    x1 = s.getArrayFromEpoch(epoch1, 'xorig')
    y1 = s.getArrayFromEpoch(epoch1, 'yorig')
    x2 = s.getArrayFromEpoch(epoch2, 'xorig')
    y2 = s.getArrayFromEpoch(epoch2, 'yorig')

    x1e = s.getArrayFromEpoch(epoch1, 'xpixerr_p')
    y1e = s.getArrayFromEpoch(epoch1, 'ypixerr_p')
    x2e = s.getArrayFromEpoch(epoch2, 'xpixerr_p')
    y2e = s.getArrayFromEpoch(epoch2, 'ypixerr_p')

    dx = x2 - x1
    dy = y2 - y1
    dxe = np.hypot(x1e, x2e)
    dye = np.hypot(y1e, y2e)
    dr = np.hypot(dx, dy)

    idx = np.where((dxe < 0.02) & (dye < 0.02) & (dr < 3.0))[0]
    print len(x1), len(idx)

    drmax = 1.5

    py.figure(1)
    py.clf()
    py.plot(dx[idx], dy[idx], 'k.', ms=2)
    py.xlabel('Delta X (pixels)')
    py.ylabel('Delta Y (pixels)')
    py.axis([-drmax, drmax, -drmax, drmax])
    py.savefig(outRoot + '_vpd.png')

    py.figure(2)
    py.clf()
    q = py.quiver(x1[idx], y1[idx], dx[idx], dy[idx], scale=10)
    py.quiverkey(q, 0.5, 0.95, 0.05, '0.05 pix', color='red')
    py.savefig(outRoot + '_dr_vec.png')
예제 #19
0
def plot_vpd_align(alignRoot, epoch1, epoch2, outRoot='plot_align'):
    """
    Read in an aligned data set. Plot a vector-point-diagram for the 
    positional differences between two different epochs within the data set.
    """
    s = starset.StarSet(alignRoot)

    x1 = s.getArrayFromEpoch(epoch1, 'xorig')
    y1 = s.getArrayFromEpoch(epoch1, 'yorig')
    x2 = s.getArrayFromEpoch(epoch2, 'xorig')
    y2 = s.getArrayFromEpoch(epoch2, 'yorig')

    x1e = s.getArrayFromEpoch(epoch1, 'xpixerr_p')
    y1e = s.getArrayFromEpoch(epoch1, 'ypixerr_p')
    x2e = s.getArrayFromEpoch(epoch2, 'xpixerr_p')
    y2e = s.getArrayFromEpoch(epoch2, 'ypixerr_p')

    dx = x2 - x1
    dy = y2 - y1
    dxe = np.hypot(x1e, x2e)
    dye = np.hypot(y1e, y2e)
    dr = np.hypot(dx, dy)

    idx = np.where((dxe < 0.02) & (dye < 0.02) & (dr < 3.0))[0]
    print len(x1), len(idx)

    drmax = 1.5

    py.figure(1)
    py.clf()
    py.plot(dx[idx], dy[idx], 'k.', ms=2)
    py.xlabel('Delta X (pixels)')
    py.ylabel('Delta Y (pixels)')
    py.axis([-drmax, drmax, -drmax, drmax])
    py.savefig(outRoot + '_vpd.png')

    py.figure(2)
    py.clf()
    q = py.quiver(x1[idx], y1[idx], dx[idx], dy[idx], scale=10)
    py.quiverkey(q, 0.5, 0.95, 0.05, '0.05 pix', color='red')
    py.savefig(outRoot + '_dr_vec.png')
예제 #20
0
def whisker4QReduce(X2WIN_IMAGE=None,Y2WIN_IMAGE=None,XYWIN_IMAGE=None):
    """
    This function make the whisker plot based on the sextractor export from QuickReduce
    J.Hao, 12/4/2012
    """
    xpos = np.genfromtxt('xpos_ypos_fp.txt').T[0]
    ypos = np.genfromtxt('xpos_ypos_fp.txt').T[1]
    temp = np.zeros(62).astype('complex')
    temp.real = X2WIN_IMAGE - Y2WIN_IMAGE
    temp.imag = 2*XYWIN_IMAGE
    data=np.array([xpos, ypos,X2WIN_IMAGE + Y2WIN_IMAGE,temp]).T
    data = averageN30new(data)
    data = subMeanAll(data)
    pl.figure(figsize=(11,5.5))
    pl.subplot(1,2,1)
    phi22 = 0.5*np.arctan2(data[:,3].imag,data[:,3].real)
    x = data[:,0].real
    y = data[:,1].real
    u = np.abs(data[:,3])*np.cos(phi22)
    v = np.abs(data[:,3])*np.sin(phi22)
    qvr = pl.quiver(x,y,u,v,width = 0.004, color='r',pivot='middle',headwidth=0.,headlength=0.,headaxislength=0.,scale_units='width')
    qk = pl.quiverkey(qvr, -150,-240,0.3,str(0.3)+' pix^2',coordinates='data',color='blue')
    pl.plot(x,y,'b,')
    pl.xlim(-250,250)
    pl.ylim(-250,250)
    pl.grid(color='g')
    pl.xlabel('Camera WEST [mm]')
    pl.ylabel('Camera NORTH [mm]')
    pl.title('M22')
    pl.subplot(1,2,2)
    m20sqr = np.sqrt(data[:,2].real)
    x = data[:,0].real
    y = data[:,1].real
    m20sqr_med = np.median(m20sqr) 
    m20sqr_diff = m20sqr - m20sqr_med
    m20sqr_diff_absmed = np.median(np.abs(m20sqr_diff))
    plotScale = 1./m20sqr_diff_absmed*100
    pos = m20sqr_diff >=0
    neg = m20sqr_diff < 0
    pl.scatter(x[pos],y[pos],s=m20sqr_diff[pos]*plotScale,c='r',alpha=0.5)
    pl.scatter(x[neg],y[neg],s=-m20sqr_diff[neg]*plotScale,c='b',alpha=0.5)
    pl.scatter(-230,-210,s=0.01*plotScale,c='b',alpha=0.5)
    pl.text(-200,-215,'-'+str(0.01)+' pix')
    pl.scatter(-230,-230,s=0.01*plotScale,c='r',alpha=0.5)
    pl.text(-200,-235,str(0.01)+' pix')
    pl.plot(x,y,'y,')
    pl.grid(color='g')
    pl.xlim(-250,250)
    pl.ylim(-250,250)
    pl.xlabel('Camera WEST [mm]')
    pl.ylabel('Camera NORTH [mm]')
    pl.title('median '+r'$\sqrt{M20}$: '+str(round(0.27*m20sqr_med,3))+' [arcsec]')
    return '---done!--'
예제 #21
0
def whisker4QReduce(X2WIN_IMAGE=None,Y2WIN_IMAGE=None,XYWIN_IMAGE=None):
    """
    This function make the whisker plot based on the sextractor export from QuickReduce
    J.Hao, 12/4/2012
    """
    xpos = np.genfromtxt('xpos_ypos_fp.txt').T[0]
    ypos = np.genfromtxt('xpos_ypos_fp.txt').T[1]
    temp = np.zeros(62).astype('complex')
    temp.real = X2WIN_IMAGE - Y2WIN_IMAGE
    temp.imag = 2*XYWIN_IMAGE
    data=np.array([xpos, ypos,X2WIN_IMAGE + Y2WIN_IMAGE,temp]).T
    data = averageN30(data)
    data = subMeanAll(data)
    pl.figure(figsize=(11,5.5))
    pl.subplot(1,2,1)
    phi22 = 0.5*np.arctan2(data[:,3].imag,data[:,3].real)
    x = data[:,0].real
    y = data[:,1].real
    u = np.abs(data[:,3])*np.cos(phi22)
    v = np.abs(data[:,3])*np.sin(phi22)
    qvr = pl.quiver(x,y,u,v,width = 0.004, color='r',pivot='middle',headwidth=0.,headlength=0.,headaxislength=0.,scale_units='width')
    qk = pl.quiverkey(qvr, -150,-240,0.3,str(0.3)+' pix^2',coordinates='data',color='blue')
    pl.plot(x,y,'b,')
    pl.xlim(-250,250)
    pl.ylim(-250,250)
    pl.grid(color='g')
    pl.xlabel('Camera WEST [mm]')
    pl.ylabel('Camera NORTH [mm]')
    pl.title('M22')
    pl.subplot(1,2,2)
    m20sqr = np.sqrt(data[:,2].real)
    x = data[:,0].real
    y = data[:,1].real
    m20sqr_med = np.median(m20sqr) 
    m20sqr_diff = m20sqr - m20sqr_med
    m20sqr_diff_absmed = np.median(np.abs(m20sqr_diff))
    plotScale = 1./m20sqr_diff_absmed*100
    pos = m20sqr_diff >=0
    neg = m20sqr_diff < 0
    pl.scatter(x[pos],y[pos],s=m20sqr_diff[pos]*plotScale,c='r',alpha=0.5)
    pl.scatter(x[neg],y[neg],s=-m20sqr_diff[neg]*plotScale,c='b',alpha=0.5)
    pl.scatter(-230,-210,s=0.01*plotScale,c='b',alpha=0.5)
    pl.text(-200,-215,'-'+str(0.01)+' pix')
    pl.scatter(-230,-230,s=0.01*plotScale,c='r',alpha=0.5)
    pl.text(-200,-235,str(0.01)+' pix')
    pl.plot(x,y,'y,')
    pl.grid(color='g')
    pl.xlim(-250,250)
    pl.ylim(-250,250)
    pl.xlabel('Camera WEST [mm]')
    pl.ylabel('Camera NORTH [mm]')
    pl.title('median '+r'$\sqrt{M20}$: '+str(round(0.27*m20sqr_med,3))+' [arcsec]')
    return '---done!--'
예제 #22
0
def plot_pos_diff_xym1mat(xym1mat_cfile, scale=8, errMax=0.05):
    """
    Send in a match_c.txt file from xym1mat (3rd file) that has been trimmed
    of all bogus entries. Then plot of the differences in the positions
    from the 1st and 2nd starlists that went into the list matching process.
    This allows me to see any large scale systematics due to residual distortion
    or alignment errors.

    This assumes that the input starlists were in the XYMEEE format. We will
    use the frame #2 astrometric errors to trim out bad points.
    """
    t = atpy.Table(xym1mat_cfile, type='ascii')

    if errMax != None:
        x2e = t.col17
        y2e = t.col18

        err = np.hypot(x2e, y2e)

        origLen = len(t)
        t = t.where(err < errMax)
        newLen = len(t)

        print 'Trimmed %d of %d sources with errors > %.2f pix' % \
            (origLen-newLen, origLen, errMax)
        
    x1 = t.col8
    y1 = t.col9
    x2 = t.col11
    y2 = t.col12
    dx = x1 - x2
    dy = y1 - y2


    py.clf()
    q = py.quiver(x1, y1, dx, dy, scale=scale)
    py.quiverkey(q, 0.9, 0.95, 0.1, '0.1 pix', coordinates='axes', color='red')
    py.xlabel('X (pix)')
    py.ylabel('Y (pix)')
    py.savefig('pos_diff_vecs_' + xym1mat_cfile.replace('txt', 'png'))
예제 #23
0
def plot_pos_diff_xym1mat(xym1mat_cfile, scale=8, errMax=0.05):
    """
    Send in a match_c.txt file from xym1mat (3rd file) that has been trimmed
    of all bogus entries. Then plot of the differences in the positions
    from the 1st and 2nd starlists that went into the list matching process.
    This allows me to see any large scale systematics due to residual distortion
    or alignment errors.

    This assumes that the input starlists were in the XYMEEE format. We will
    use the frame #2 astrometric errors to trim out bad points.
    """
    t = atpy.Table(xym1mat_cfile, type='ascii')

    if errMax != None:
        x2e = t.col17
        y2e = t.col18

        err = np.hypot(x2e, y2e)

        origLen = len(t)
        t = t.where(err < errMax)
        newLen = len(t)

        print 'Trimmed %d of %d sources with errors > %.2f pix' % \
            (origLen-newLen, origLen, errMax)

    x1 = t.col8
    y1 = t.col9
    x2 = t.col11
    y2 = t.col12
    dx = x1 - x2
    dy = y1 - y2

    py.clf()
    q = py.quiver(x1, y1, dx, dy, scale=scale)
    py.quiverkey(q, 0.9, 0.95, 0.1, '0.1 pix', coordinates='axes', color='red')
    py.xlabel('X (pix)')
    py.ylabel('Y (pix)')
    py.savefig('pos_diff_vecs_' + xym1mat_cfile.replace('txt', 'png'))
예제 #24
0
  def sliceuv(self,ind,time=0,plot=False,**opts):
    savename=False
    if savename in opts.keys(): savename=opts['savename']

    if ind=='bar':
      isK,uname,vname,ind = True, 'ubar','vbar', 9999
    elif ind in ('s','surf','surface'):
      isK,uname,vname,ind = True,  'u','v', -1
    elif ind>=0:
      isK,uname,vname,ind = True,  'u','v', ind
    elif ind <0:
      isK=False
      isK,uname,vname,ind = False, 'u','v', ind


    if isK:
      xu,yu,zu,u=self.slicek(uname,ind,time)
      xv,yv,zv,v=self.slicek(vname,ind,time)
    else:
      xu,yu,zu,u=self.slicez(uname,ind,time)
      xv,yv,zv,v=self.slicez(vname,ind,time)

    z=(zu[1:,:]+zu[:-1,:])/2.
    u=( u[1:,:]+ u[:-1,:])/2.
    v=( v[:,1:]+ v[:,:-1])/2.

    x=self.grid.lonp
    y=self.grid.latp

    # rotate uv:
    ang=rt.rho2uvp(self.grid.angle,'p')
    u,v=calc.rot2d(u,v,-ang)


    if plot:
      p=self.grid.plot(bathy=None)
      xm, ym = p(x,y)
      mm=0*m
      mm[::3,::3]=1
      mm=mm*m==1
      s=np.sqrt(u**2+v**2)
      q=pylab.quiver(xm[mm],ym[mm],u[mm],v[mm],s[mm])
      pylab.colorbar(shrink=.7)
      pylab.axis([p.xmin, p.xmax, p.ymin, p.ymax])
      qk = pylab.quiverkey(q, .05, .01, 0.2, '0.2 m/s',labelpos='E',
                                              coordinates='axes')
      if savename:
        pylab.savefig(savename,dpi=pylab.gcf().dpi)
        pylab.close(pylab.gcf())

    return x,y,z,u,v
예제 #25
0
def plot_residuals_year_pos(year, filt, pos, refresh=False):
    year = str(year) 
    
    dir_xym = year + '_' + filt + '_' + pos + '/01.XYM/'

    # Try to read from a FITS table of compiled data if possible.
    if refresh == True:
        make_residuals_table_year_pos(year, filt, pos)

    d = read_residuals_table_year_pos(year, filt, pos)

    print d.xstd.min(), d.xstd.max()
    
    # Look at the variance in the raw X pixels.
    py.clf()
    q = py.quiver(d.xmean, d.ymean, d.xstd, d.ystd, scale=0.7)
    py.quiverkey(q, -0.1, -0.12, 0.02, '0.02 pixels', color='red')
    py.xlim(0, 1050)
    py.xlabel("X (pixels)")
    py.ylabel("Y (pixels)")
    py.title(year + ',' + filt + ',' + pos)
    
    py.savefig('plots/resid_errors_{0}_{1}_{2}.png'.format(year, filt, pos))
예제 #26
0
    def sliceuv(self, ind, time=0, plot=False, **opts):
        savename = False
        if savename in opts.keys():
            savename = opts["savename"]

        if ind == "bar":
            isK, uname, vname, ind = True, "ubar", "vbar", 9999
        elif ind in ("s", "surf", "surface"):
            isK, uname, vname, ind = True, "u", "v", -1
        elif ind >= 0:
            isK, uname, vname, ind = True, "u", "v", ind
        elif ind < 0:
            isK = False
            isK, uname, vname, ind = False, "u", "v", ind

        if isK:
            xu, yu, zu, u = self.slicek(uname, ind, time)
            xv, yv, zv, v = self.slicek(vname, ind, time)
        else:
            xu, yu, zu, u = self.slicez(uname, ind, time)
            xv, yv, zv, v = self.slicez(vname, ind, time)

        z = (zu[1:, :] + zu[:-1, :]) / 2.0
        u = (u[1:, :] + u[:-1, :]) / 2.0
        v = (v[:, 1:] + v[:, :-1]) / 2.0

        x = self.grid.lonp
        y = self.grid.latp

        # rotate uv:
        ang = rt.rho2uvp(self.grid.angle, "p")
        u, v = calc.rot2d(u, v, -ang)

        if plot:
            p = self.grid.plot(bathy=None)
            xm, ym = p(x, y)
            mm = 0 * m
            mm[::3, ::3] = 1
            mm = mm * m == 1
            s = np.sqrt(u ** 2 + v ** 2)
            q = pylab.quiver(xm[mm], ym[mm], u[mm], v[mm], s[mm])
            pylab.colorbar(shrink=0.7)
            pylab.axis([p.xmin, p.xmax, p.ymin, p.ymax])
            qk = pylab.quiverkey(q, 0.05, 0.01, 0.2, "0.2 m/s", labelpos="E", coordinates="axes")
            if savename:
                pylab.savefig(savename, dpi=pylab.gcf().dpi)
                pylab.close(pylab.gcf())

        return x, y, z, u, v
예제 #27
0
def display_2nd_moments(data=None):
    # remove the mean for all moments
    datamean = data.mean(axis = 0)
    data = subMeanAll(data)
    pl.figure(figsize=(11,5.5))
    pl.subplot(1,2,1)
    phi22 = 0.5*np.arctan2(data[:,3].imag,data[:,3].real)
    x = data[:,0].real
    y = data[:,1].real
    #phi22[x<0] = phi22+np.deg2rad(180)
    u = np.abs(data[:,3])*np.cos(phi22)
    v = np.abs(data[:,3])*np.sin(phi22)
    qvr = pl.quiver(x,y,u,v,width = 0.004, color='r',pivot='middle',headwidth=0.,headlength=0.,headaxislength=0.,scale_units='width')
    #qk = pl.quiverkey(qvr, -150,-240,np.max(np.sqrt(u**2+v**2)),str(round(np.max(np.sqrt(u**2+v**2)),3))+' pix^2',coordinates='data',color='blue')
    qk = pl.quiverkey(qvr, -150,-240,0.3,str(0.3)+' pix^2',coordinates='data',color='blue')
    pl.plot(x,y,'b,')
    pl.xlim(-250,250)
    pl.ylim(-250,250)
    pl.grid(color='g')
    pl.xlabel('Camera WEST [mm]')
    pl.ylabel('Camera NORTH [mm]')
    pl.title('mean |M22|= '+str(round(abs(datamean[:,3]),5))+' pix^2')
    pl.subplot(1,2,2)
    m20sqr = np.sqrt(data[:,2].real)
    x = data[:,0].real
    y = data[:,1].real
    m20sqr_med = np.median(m20sqr) 
    m20sqr_diff = m20sqr - m20sqr_med
    m20sqr_diff_absmed = np.median(np.abs(m20sqr_diff))
    plotScale = 1./m20sqr_diff_absmed*100
    pos = m20sqr_diff >=0
    neg = m20sqr_diff < 0
    pl.scatter(x[pos],y[pos],s=m20sqr_diff[pos]*plotScale,c='r',alpha=0.5)
    pl.scatter(x[neg],y[neg],s=-m20sqr_diff[neg]*plotScale,c='b',alpha=0.5)
    pl.scatter(-230,-210,s=0.01*plotScale,c='b',alpha=0.5)
    pl.text(-200,-215,'-'+str(0.01)+' pix')
    pl.scatter(-230,-230,s=0.01*plotScale,c='r',alpha=0.5)
    pl.text(-200,-235,str(0.01)+' pix')
    pl.plot(x,y,'y,')
    pl.grid(color='g')
    pl.xlim(-250,250)
    pl.ylim(-250,250)
    pl.xlabel('Camera WEST [mm]')
    pl.ylabel('Camera NORTH [mm]')
    pl.title('median '+r'$\sqrt{M20}$: '+str(round(scale*m20sqr_med,3))+' [arcsec]')
    return '---done!--'
예제 #28
0
def display_2nd_moments(data=None):
    # remove the mean for all moments
    datamean = data.mean(axis = 0)
    data = subMeanAll(data)
    pl.figure(figsize=(11,5.5))
    pl.subplot(1,2,1)
    phi22 = 0.5*np.arctan2(data[:,3].imag,data[:,3].real)
    x = data[:,0].real
    y = data[:,1].real
    #phi22[x<0] = phi22+np.deg2rad(180)
    u = np.abs(data[:,3])*np.cos(phi22)
    v = np.abs(data[:,3])*np.sin(phi22)
    qvr = pl.quiver(x,y,u,v,width = 0.004, color='r',pivot='middle',headwidth=0.,headlength=0.,headaxislength=0.,scale_units='width')
    #qk = pl.quiverkey(qvr, -150,-240,np.max(np.sqrt(u**2+v**2)),str(round(np.max(np.sqrt(u**2+v**2)),3))+' pix^2',coordinates='data',color='blue')
    qk = pl.quiverkey(qvr, -150,-240,0.3,str(0.3)+' pix^2',coordinates='data',color='blue')
    pl.plot(x,y,'b,')
    pl.xlim(-250,250)
    pl.ylim(-250,250)
    pl.grid(color='g')
    pl.xlabel('Camera WEST [mm]')
    pl.ylabel('Camera NORTH [mm]')
    pl.title('mean |M22|= '+str(round(abs(datamean[:,3]),5))+' pix^2')
    pl.subplot(1,2,2)
    m20sqr = np.sqrt(data[:,2].real)
    x = data[:,0].real
    y = data[:,1].real
    m20sqr_med = np.median(m20sqr) 
    m20sqr_diff = m20sqr - m20sqr_med
    m20sqr_diff_absmed = np.median(np.abs(m20sqr_diff))
    plotScale = 1./m20sqr_diff_absmed*100
    pos = m20sqr_diff >=0
    neg = m20sqr_diff < 0
    pl.scatter(x[pos],y[pos],s=m20sqr_diff[pos]*plotScale,c='r',alpha=0.5)
    pl.scatter(x[neg],y[neg],s=-m20sqr_diff[neg]*plotScale,c='b',alpha=0.5)
    pl.scatter(-230,-210,s=0.01*plotScale,c='b',alpha=0.5)
    pl.text(-200,-215,'-'+str(0.01)+' pix')
    pl.scatter(-230,-230,s=0.01*plotScale,c='r',alpha=0.5)
    pl.text(-200,-235,str(0.01)+' pix')
    pl.plot(x,y,'y,')
    pl.grid(color='g')
    pl.xlim(-250,250)
    pl.ylim(-250,250)
    pl.xlabel('Camera WEST [mm]')
    pl.ylabel('Camera NORTH [mm]')
    pl.title('median '+r'$\sqrt{M20}$: '+str(round(scale*m20sqr_med,3))+' [arcsec]')
    return '---done!--'
예제 #29
0
    def plot_disp(self,
                  d,
                  sites,
                  sites_subset=None,
                  X=0.1,
                  Y=0.1,
                  U=1.,
                  label='1m',
                  color='black',
                  scale=None,
                  font_size=10):
        ''' Plot displacment
'''

        lons, lats = vj.sites_db.get_pos(sites)
        es = d[0::3]
        ns = d[1::3]
        us = d[2::3]

        if sites_subset is not None:
            ch = ch_sub_set(sites, sites_subset)
            lons = lons[ch]
            lats = lats[ch]
            es = es[ch]
            ns = ns[ch]

        Qu = self.basemap.quiver(lons,
                                 lats,
                                 es,
                                 ns,
                                 color=color,
                                 scale=scale,
                                 edgecolor=color,
                                 latlon=True)

        qk = quiverkey(Qu,
                       X,
                       Y,
                       U,
                       label,
                       labelpos='N',
                       fontproperties={'size': font_size})
예제 #30
0
파일: plot_slice.py 프로젝트: sleitner/cart
def add_arrows(fieldx,fieldy):
	norm=abs(np.concatenate((fieldx,fieldy)).max())/1. #1d norm
	freq=4
	M = py.sqrt(pow(fieldx, 2) + pow(fieldy, 2))
	X,Y = py.meshgrid( py.arange(0,nx,1),py.arange(0,ny,1) )

        if(1==1):
            Q = py.quiver( 
		X[::freq, ::freq], Y[::freq, ::freq], 
		fieldx[::freq, ::freq], fieldy[::freq, ::freq], 
                #		M[::freq, ::freq],cmap=py.cm.jet,
                #		,color='yellow'
		#M[::freq, ::freq],cmap=py.cm.gray, alpha=0.2,
#		facecolors=mycmap(M[::freq, ::freq]),
                #		width=0.4,linewidths=(.5), edgecolors=('k'), 
#                color=colors,
		width=(0.2*py.sqrt(freq)),linewidths=(.2),
#		pivot='mid', 
#		pivot='tail', 
		units='x',
		headaxislength=5 ,
		scale=norm/freq)
            colors=mycmap_rgba(M[::freq, ::freq])
            Q.set_facecolor(colors)
            Q.set_edgecolor('k')
            Q.set_edgecolor(colors)
        else:
            Q = py.quiver( 
		X[::freq, ::freq], Y[::freq, ::freq], 
		fieldx[::freq, ::freq], fieldy[::freq, ::freq], 
                #		M[::freq, ::freq],cmap=py.cm.gray, alpha=1,
		width=0.2,
		units='x',
		headaxislength=5 ,
		scale=norm/2)

        legend='{:.2g}km/s'.format(norm)
        qk = py.quiverkey(Q, 0.9, 1.05, norm, legend,
                          labelpos='E',
                          fontproperties={'weight': 'bold'})
    def PlotFlightContour(self):

        # Creates list for UAV directions from 0 to 359
        uav_direction_0_359 = numpy.arange(0, 360, 0.1)

        # Creates empty list to store distance travelled by UAV
        displacement = []

        # Creates empty lists to store x and y coordinates
        x_coords = []
        y_coords = []

        # For-loop to run through the possible UAV directions
        for x in uav_direction_0_359:
            self.uav_U = self.uav_speed * numpy.cos(x * (2 * numpy.pi) / 360)
            self.uav_V = self.uav_speed * numpy.sin(x * (2 * numpy.pi) / 360)
            y = self.BaseFly()
            # Appends results of BaseFly into relevant lists
            displacement.append(y[0])
            x_coords.append(y[0] * numpy.cos(y[1] * (2 * numpy.pi) / 360))
            y_coords.append(y[0] * numpy.sin(y[1] * (2 * numpy.pi) / 360))

        # Generates 2D wind vector field
        X, Y = numpy.meshgrid(numpy.arange(min(x_coords) - 80, max(x_coords) + 80, (max(x_coords) - min(x_coords)) / 5),
                              numpy.arange(min(y_coords) - 80, max(y_coords) + 80, (max(y_coords) - min(y_coords)) / 5))
        Q = pylab.quiver(X, Y, self.wind_U, self.wind_V, label='Wind Direction')
        QK = pylab.quiverkey(Q, 0.1, -0.08, 10, 'Wind Direction', labelpos='W',
                             fontproperties={'weight': 'bold'})

        pylab.plot(x_coords, y_coords, self.marker3, label='Displacement Contour')
        pylab.plot(0, 0, self.marker1, label="Start")
        pylab.title('UAV Displacement in Y against UAV Displacement in X\n(Varying UAV Direction from 0 to 359)')
        pylab.xlabel('UAV Displacement in X')
        pylab.ylabel('UAV Displacement in Y')

        pylab.legend()

        pylab.show()
예제 #32
0
def velocity_image(sim,
                   width="10 kpc",
                   vector_color='black',
                   edgecolor='black',
                   vector_resolution=40,
                   scale=None,
                   mode='quiver',
                   key_x=0.3,
                   key_y=0.9,
                   key_color='white',
                   key_length="100 km s**-1",
                   density=1.0,
                   **kwargs):
    """

    Make an SPH image of the given simulation with velocity vectors overlaid on top.

    For a description of additional keyword arguments see :func:`~pynbody.plot.sph.image`,
    or see the `tutorial <http://pynbody.github.io/pynbody/tutorials/pictures.html#velocity-vectors>`_.

    **Keyword arguments:**

    *vector_color* (black): The color for the velocity vectors

    *edgecolor* (black): edge color used for the lines - using a color
     other than black for the *vector_color* and a black *edgecolor*
     can result in poor readability in pdfs

    *vector_resolution* (40): How many vectors in each dimension (default is 40x40)

    *scale* (None): The length of a vector that would result in a displayed length of the
    figure width/height.

    *mode* ('quiver'): make a 'quiver' or 'stream' plot

    *key_x* (0.3): Display x (width) position for the vector key (quiver mode only)

    *key_y* (0.9): Display y (height) position for the vector key (quiver mode only)

    *key_color* (white): Color for the vector key (quiver mode only)

    *key_length* (100 km/s): Velocity to use for the vector key (quiver mode only)

    *density* (1.0): Density of stream lines (stream mode only)

    """

    subplot = kwargs.get('subplot', False)
    if subplot:
        p = subplot
    else:
        import matplotlib.pylab as p

    vx = image(sim,
               qty='vx',
               width=width,
               log=False,
               resolution=vector_resolution,
               noplot=True)
    vy = image(sim,
               qty='vy',
               width=width,
               log=False,
               resolution=vector_resolution,
               noplot=True)
    key_unit = _units.Unit(key_length)

    if isinstance(width, str) or issubclass(width.__class__, _units.UnitBase):
        if isinstance(width, str):
            width = _units.Unit(width)
        width = width.in_units(sim['pos'].units, **sim.conversion_context())

    width = float(width)

    X, Y = np.meshgrid(
        np.arange(-width / 2, width / 2, width / vector_resolution),
        np.arange(-width / 2, width / 2, width / vector_resolution))

    im = image(sim, width=width, **kwargs)

    if mode == 'quiver':
        if scale is None:
            Q = p.quiver(X, Y, vx, vy, color=vector_color, edgecolor=edgecolor)
        else:
            Q = p.quiver(X,
                         Y,
                         vx,
                         vy,
                         scale=_units.Unit(scale).in_units(sim['vel'].units),
                         color=vector_color,
                         edgecolor=edgecolor)
        p.quiverkey(Q,
                    key_x,
                    key_y,
                    key_unit.in_units(sim['vel'].units,
                                      **sim.conversion_context()),
                    r"$\mathbf{" + key_unit.latex() + "}$",
                    labelcolor=key_color,
                    color=key_color,
                    fontproperties={'size': 16})
    elif mode == 'stream':
        Q = p.streamplot(X, Y, vx, vy, color=vector_color, density=density)

    return im
예제 #33
0
p.figure()
p.plot(r, f)
p.xlabel('x')
p.ylabel('y')
p.title('phase plane')


# make a direction field plot with quiver
rmax = 1.1 * r.max()
fmax = 1.1 * f.max()
R, F = n.meshgrid(n.arange(0, rmax, .05), n.arange(0, fmax,.05))
dR = dr(R, F)
dF = df(R, F)
p.quiver(R, F, dR, dF)
qk = p.quiverkey(R,F, 0.03, 1, r'$1 \frac{m}{s}$',
                   fontproperties={'weight': 'bold'})


R, F = n.meshgrid(n.arange(0, rmax, .1), n.arange(0, fmax, .1))
dR = dr(R, F)
dF = df(R, F)

p.contour(R, F, dR, levels=[0], linewidths=1, colors='black')
p.contour(R, F, dF, levels=[0], linewidths=1, colors='black')
p.ylabel('y')
p.title('trajectory, direction field and null clines of Brusselator model at a = 1, b = 3.0')

p.savefig('lotka_volterra_pplane.png', dpi=150)
p.savefig('lotka_volterra_pplane.eps')

예제 #34
0
def plot_vpd_across_field(nside=4, interact=False):
    """
    Plot the VPD at different field positions so we can see if there are
    systematic discrepancies due to residual distortions.
    """
    # Read in matched and aligned star lists from the *.ref5 analysis.
    # Recall these data sets are in the F814W reference frame with a 50 mas plate scale.
    t2005 = starlists.read_matchup(workDir + '02.MAT/MATCHUP.XYMEEE.F814W.ref5')
    t2010 = starlists.read_matchup(workDir + '02.MAT/MATCHUP.XYMEEE.F125W.ref5')

    scale = 50.0 # mas per pixel
    

    # Trim down to only those stars that are detected in both epochs.
    # Also make cuts on astrometric/photometric errors, etc.
    # We only want the well measured stars in this analysis.
    perrLim814 = 1.0 / scale
    perrLim125 = 4.0 / scale
    merrLim814 = 0.05
    merrLim125 = 0.1
    
    cond = ((t2005.m != 0) & (t2010.m != 0) &
            (t2005.xe < perrLim814) & (t2005.ye < perrLim814) &
            (t2010.xe < perrLim125) & (t2010.ye < perrLim125) &
            (t2005.me < merrLim814) & (t2010.me < merrLim125))

    t2005 = t2005.where(cond)
    t2010 = t2010.where(cond)

    # Calculate proper motions
    dt = years['2010_F125W'] - years['2005_F814W']
    dx = t2010.x - t2005.x
    dy = t2010.y - t2005.y
    pmx = dx * scale / dt
    pmy = dy * scale / dt
    pm = np.hypot(pmx, pmy)

    t2005.add_column('pmx', pmx)
    t2005.add_column('pmy', pmy)
    t2005.add_column('pm', pm)


    # Divide up the region into N x N boxes and plot up the VPD for each.
    xlo = math.floor(t2005.x.min())
    xhi = math.ceil(t2005.x.max())
    ylo = math.floor(t2005.y.min())
    yhi = math.ceil(t2005.y.max())
    xboxsize = round((xhi - xlo) / nside)
    yboxsize = round((yhi - ylo) / nside)

    # Setup colors
    jet = py.get_cmap('jet')
    cNorm = colors.Normalize(vmin=0, vmax=nside**2)
    colorMap = py.cm.ScalarMappable(norm=cNorm, cmap=jet)

    # Save the average proper motions in each box
    pmx = np.zeros((nside, nside), dtype=float)
    pmy = np.zeros((nside, nside), dtype=float)
    pmxe = np.zeros((nside, nside), dtype=float)
    pmye = np.zeros((nside, nside), dtype=float)
    xcen = np.zeros((nside, nside), dtype=float)
    ycen = np.zeros((nside, nside), dtype=float)

    pmCut = 1.0

    # Calculate the global mean proper motion
    # Start by trimming down to a 1 mas/yr radius
    idx2 = np.where(pm < pmCut)[0]
    pmx_all = np.median( t2005.pmx[idx2] )
    pmy_all = np.median( t2005.pmy[idx2] )
    
    out = 'All X:{0:5.0f}-{1:5.0f}  Y:{2:5.0f}-{3:5.0f}  '
    out += 'PMX:{4:5.2f} +/- {5:5.2f} PMY:{6:5.2f} +/- {7:5.2f}  '
    out += 'N:{8:5d}'
    print((out.format(xlo, xhi, ylo, yhi, pmx_all, 0.0, pmy_all, 0.0, len(idx2))))

    # Make a global proper motion diagram of star with a proper motion within
    # 1 mas/yr. This is mainly to see systematic flows due to residual distortion.
    pmTot = np.hypot(t2005.pmx, t2005.pmy)
    clust = np.where(pmTot < pmCut)[0]
    py.clf()
    q = py.quiver(t2005.x[clust], t2005.y[clust], t2005.pmx[clust], t2005.pmy[clust],
                  scale=18)
    py.quiverkey(q, 0.5, 0.98, 1, '1 mas/yr', color='red', labelcolor='red')
    py.xlabel('X Position (pixels)')
    py.ylabel('Y Position (pixels)')
    py.xlim(xlo, xhi)
    py.ylim(ylo, yhi)
    out = '{0}/plots/vec_proper_motion_all.png'
    py.savefig(out.format(workDir))
    
    py.clf()
    for xx in range(nside):
        for yy in range(nside):
            xlo_box = xlo + xx * xboxsize
            ylo_box = ylo + yy * yboxsize
            xhi_box = xlo + (1+xx) * xboxsize
            yhi_box = ylo + (1+yy) * yboxsize

            idx = np.where((t2005.x > xlo_box) & (t2005.x <= xhi_box) &
                           (t2005.y > ylo_box) & (t2005.y <= yhi_box))[0]


            if interact:
                color = colorMap.to_rgba(yy + xx * nside)
                lim = 5

                py.plot(t2005.pmx[idx], t2005.pmy[idx], 'k.', ms=2, color=color)
                py.axis([-lim, lim, -lim, lim])

                py.xlabel('X Proper Motion (mas/yr)')
                py.ylabel('Y Proper Motion (mas/yr)')

            # Lets get the mean and std-dev (iterative) for the box.
            # Start by trimming down to a 1 mas/yr circle.
            idx2 = np.where(t2005.pm[idx] < pmCut)[0]
            xmean = np.median( t2005.pmx[idx][idx2] )
            ymean = np.median( t2005.pmy[idx][idx2] )
            xstd = t2005.pmx[idx][idx2].std()
            ystd = t2005.pmy[idx][idx2].std()
            xmean_err = xstd / np.sqrt(len(idx2))
            ymean_err = ystd / np.sqrt(len(idx2))

            xcen[xx, yy] = xlo_box + (xboxsize / 2.0)
            ycen[xx, yy] = ylo_box + (yboxsize / 2.0)
            pmx[xx, yy] = xmean - pmx_all
            pmy[xx, yy] = ymean - pmx_all
            pmxe[xx, yy] = xmean_err
            pmye[xx, yy] = ymean_err

            out = 'Box X:{0:5.0f}-{1:5.0f}  Y:{2:5.0f}-{3:5.0f}  '
            out += 'PMX:{4:5.2f} +/- {5:5.2f} PMY:{6:5.2f} +/- {7:5.2f}  '
            out += 'N:{8:5d}  '

            if interact:
                out += 'Continue?'
                input(out.format(xlo_box, xhi_box, ylo_box, yhi_box,
                                     xmean, xmean_err, ymean, ymean_err, len(idx2)))
            else:
                print((out.format(xlo_box, xhi_box, ylo_box, yhi_box,
                                 xmean, xmean_err, ymean, ymean_err, len(idx2))))


    if interact:
        out = '{0}/plots/vpd_grid_nside{1}.png'
        py.savefig(out.format(workDir, nside))

    py.clf()
    q = py.quiver(xcen, ycen, pmx, pmy)
    py.quiverkey(q, 0.5, 0.98, 0.1, '0.1 mas/yr', color='red', labelcolor='red')
    py.xlabel('X Position (pixels)')
    py.ylabel('Y Position (pixels)')
    py.xlim(xlo, xhi)
    py.ylim(ylo, yhi)
    for xx in range(nside+1):
        py.axvline(xlo + xx * xboxsize, linestyle='--', color='grey')
    for yy in range(nside+1):
        py.axhline(ylo + yy * yboxsize, linestyle='--', color='grey')
    out = '{0}/plots/vec_proper_motion_grid_nside{1}.png'
    py.savefig(out.format(workDir, nside))

    py.clf()
    q = py.quiver(xcen, ycen, pmx/pmxe, pmy/pmye)
    py.quiverkey(q, 0.5, 0.98, 3, '3 sigma', color='red', labelcolor='red')
    py.xlabel('X Position (pixels)')
    py.ylabel('Y Position (pixels)')
    py.xlim(xlo, xhi)
    py.ylim(ylo, yhi)
    for xx in range(nside+1):
        py.axvline(xlo + xx * xboxsize, linestyle='--', color='grey')
    for yy in range(nside+1):
        py.axhline(ylo + yy * yboxsize, linestyle='--', color='grey')
    out = '{0}/plots/vec_proper_motion_grid_sig_nside{1}.png'
    py.savefig(out.format(workDir, nside))
예제 #35
0
def plot_pos_diff(suffix='_t'):
    for ii in range(1, 4+1):
        t = pyfits.getdata('catalog_quad_{0}{1}.fits'.format(ii, suffix))

        x = t[0]
        y = t[1]
        m = t[2]

        n_users = x.shape[0]
        n_frames = x.shape[1]
        n_stars = x.shape[2]

        xerr_0 = x[0, :, :].std(axis=0)
        xerr_1 = x[1, :, :].std(axis=0)
        xerr_2 = x[2, :, :].std(axis=0)
        yerr_0 = y[0, :, :].std(axis=0)
        yerr_1 = y[1, :, :].std(axis=0)
        yerr_2 = y[2, :, :].std(axis=0)
        merr_0 = m[0, :, :].std(axis=0)
        merr_1 = m[1, :, :].std(axis=0)
        merr_2 = m[2, :, :].std(axis=0)
        m_0 = m[0, :, :].mean(axis=0)
        m_1 = m[1, :, :].mean(axis=0)
        m_2 = m[1, :, :].mean(axis=0)

        py.figure(1)
        py.clf()
        
        f, (ax1, ax2) = py.subplots(2, 1, sharex=True)
        f.subplots_adjust(hspace=0.)

        ax1.plot(xerr_2, xerr_1 - xerr_2, 'ro', label='X', mec='none', ms=5)
        ax1.plot(yerr_2, yerr_1 - yerr_2, 'bo', label='Y', mec='none', ms=5)
        ax1.axhline(0, linestyle='--', color='black')
        ax1.legend(numpoints=1)
        ax1.set_title('Compare Pos RMS Error')
        ax1.set_ylabel(r'$\sigma_{BN} - \sigma_{JL}$ (pix)')
        ax1.set_ylim(-0.3, 0.3)
        ax1.set_xlim(0, 0.3)

        ax2.plot(xerr_2, xerr_0 - xerr_2, 'ro', label='X', mec='none', ms=5)
        ax2.plot(yerr_2, yerr_0 - yerr_2, 'bo', label='Y', mec='none', ms=5)
        ax2.axhline(0, linestyle='--', color='black')
        ax2.set_xlabel(r'$\sigma_{JL}$ (pix)')
        ax2.set_ylabel(r'$\sigma_{BN} - \sigma_{JL}$ (pix)')
        ax2.set_ylim(-0.3, 0.3)
        ax2.set_xlim(0, 0.3)
        py.savefig('plots/pos_err_compare_q{0}.png'.format(ii))
        py.close()
    

        print '      X_RMS_Error    Y_RMS_Error   (Quad={0})'.format(ii)
        print ' JL   {0:11.2f}    {1:11.2f}'.format(xerr_2.mean(), yerr_2.mean())
        print ' BN   {0:11.2f}    {1:11.2f}'.format(xerr_1.mean(), yerr_1.mean())
        print ' MA   {0:11.2f}    {1:11.2f}'.format(xerr_0.mean(), yerr_0.mean())
                

        for ff in range(n_frames):
            dx1 = x[0, ff, :] - x[2, ff, :]
            dy1 = y[0, ff, :] - y[2, ff, :]
            dr1 = np.hypot(dx1, dy1)

            dx2 = x[1, ff, :] - x[2, ff, :]
            dy2 = y[1, ff, :] - y[2, ff, :]
            dr2 = np.hypot(dx2, dy2)

            dm1 = m[0, ff, :] - m[2, ff, :]
            dm2 = m[1, ff, :] - m[2, ff, :]
            
            # Make a histogram of dx and dy
            py.figure(1)
            py.clf()
            bins = np.arange(-1, 1, 0.05)

            py.subplot(211)
            py.hist(dx1, histtype='step', color='red', bins=bins, label='X')
            py.hist(dy1, histtype='step', color='blue', bins=bins, label='Y')
            py.ylabel('N stars (MA - JLU)')
            py.title('Frame ' + str(58+ff) + ', Quad ' + str(ii))
            py.legend()

            py.subplot(212)
            py.hist(dx2, histtype='step', color='red', bins=bins)
            py.hist(dy2, histtype='step', color='blue', bins=bins)
            py.ylabel('N stars (BN - JLU)')
            py.xlabel('Position Difference (pix)')

            py.savefig('plots/hist_pos_q{0}_f{1}.png'.format(ii, ff))

            # Make a histogram of dm
            py.figure(2)
            py.clf()
            py.subplot(111)
            bins = np.arange(-4.6, -3.2, 0.1)
            py.hist(dm1, histtype='step', color='red', bins=bins, label='MA-JLU')
            py.hist(dm2, histtype='step', color='blue', bins=bins, label='BN-JLU')
            py.xlabel('Magnitude Difference')
            py.ylabel('N stars')
            py.legend()
            py.title('Frame ' + str(58+ff) + ', Quad ' + str(ii))
            py.savefig('plots/hist_mag_q{0}_f{1}.png'.format(ii, ff))

            print 'Median Zeropoint (Quad={0}, Frame={1}):'.format(ii, 58+ff)
            print 'Nstars = {0}'.format(x.shape[2])
            print '   MA = {0:.2f}'.format(dm1.mean())
            print '   BN = {0:.2f}'.format(dm2.mean())

            # Make a 2 panel quiver plot with positional offsets relative to
            # JLU position.
            py.close(3)
            py.figure(3, figsize=(10,5))
            qscale = 1
            py.subplots_adjust(left=0.1, wspace=0.3, bottom=0.13)

            py.subplot(121)
            q = py.quiver(x[2, ff, :], y[2, ff, :], dx1, dy1, scale=qscale)
            py.quiverkey(q, 0.9, 0.9, 0.1, '2 mas')
            py.xlabel('X JLU (pixels)')
            py.ylabel('X JLU (pixels)')
            py.axis('equal')
            rng = py.axis()
            py.axis([rng[0], rng[0]+2500, rng[2], rng[2]+2500])
            py.title('MA - JLU: Frame ' + str(58+ff) + ', Quad ' + str(ii))

            py.subplot(122)
            q = py.quiver(x[2, ff, :], y[2, ff, :], dx2, dy2, scale=qscale)
            py.quiverkey(q, 0.9, 0.9, 0.1, '2 mas')
            py.xlabel('X JLU (pixels)')
            py.ylabel('X JLU (pixels)')
            py.axis('equal')
            rng = py.axis()
            py.axis([rng[0], rng[0]+2500, rng[2], rng[2]+2500])
            py.title('BN - JLU: Frame ' + str(58+ff) + ', Quad ' + str(ii))

            py.savefig('plots/quiver_q{0}_f{1}.png'.format(ii, ff))
def plot_quiver_one_pass(reread=False):
    """
    Plot a quiver vector plot between F814W in 2005 and F160W in 2010 and 2013.
    This is just to check that we don't hae any gross flows between the two cameras.
    """
    if reread:
        t2005 = starlists.read_matchup('MATCHUP.XYMEEE.F814W.ref5')
        t2010 = starlists.read_matchup('MATCHUP.XYMEEE.F160W.2010.ref5')
        t2013 = starlists.read_matchup('MATCHUP.XYMEEE.F160W.2013.ref5')

        t2005.write('MATCHUP.XYMEEE.F814W.ref5.fits')
        t2010.write('MATCHUP.XYMEEE.F160W.2010.ref5.fits')
        t2013.write('MATCHUP.XYMEEE.F160W.2013.ref5.fits')
    else:
        t2005 = Table.read('MATCHUP.XYMEEE.F814W.ref5.fits')
        t2010 = Table.read('MATCHUP.XYMEEE.F160W.2010.ref5.fits')
        t2013 = Table.read('MATCHUP.XYMEEE.F160W.2013.ref5.fits')

    good = np.where((t2005['m'] < -8) & (t2010['m'] < -8) & (t2013['m'] < -8) &
                    (t2005['xe'] < 0.05) & (t2010['xe'] < 0.05) & (t2013['xe'] < 0.05) & 
                    (t2005['ye'] < 0.05) & (t2010['ye'] < 0.05) & (t2013['ye'] < 0.05) & 
                    (t2005['me'] < 0.05) & (t2010['me'] < 0.05) & (t2013['me'] < 0.05))[0]

    g2005 = t2005[good]
    g2010 = t2010[good]
    g2013 = t2013[good]

    dx_05_10 = (g2010['x'] - g2005['x']) * ast.scale['WFC'] * 1e3
    dy_05_10 = (g2010['y'] - g2005['y']) * ast.scale['WFC'] * 1e3

    dx_05_13 = (g2013['x'] - g2005['x']) * ast.scale['WFC'] * 1e3
    dy_05_13 = (g2013['y'] - g2005['y']) * ast.scale['WFC'] * 1e3

    dx_10_13 = (g2013['x'] - g2010['x']) * ast.scale['WFC'] * 1e3
    dy_10_13 = (g2013['y'] - g2010['y']) * ast.scale['WFC'] * 1e3

    small = np.where((np.abs(dx_05_10) < 20) & (np.abs(dy_05_10) < 20) & 
                     (np.abs(dx_05_13) < 20) & (np.abs(dy_05_13) < 20) & 
                     (np.abs(dx_10_13) < 20) & (np.abs(dy_10_13) < 20))[0]

    print(len(g2005), len(small), len(dx_05_10))
    g2005 = g2005[small]
    g2010 = g2010[small]
    g2013 = g2013[small]
    dx_05_10 = dx_05_10[small]
    dx_05_13 = dx_05_13[small]
    dx_10_13 = dx_10_13[small]
    dy_05_10 = dy_05_10[small]
    dy_05_13 = dy_05_13[small]
    dy_10_13 = dy_10_13[small]
    print(len(g2005), len(small), len(dx_05_10))
    
    py.clf()
    q = py.quiver(g2005['x'], g2005['y'], dx_05_10, dy_05_10, scale=2e2)
    py.quiverkey(q, 0.95, 0.95, 5, '5 mas', color='red', labelcolor='red')
    py.title('2010 - 2005')
    py.savefig('vec_diff_ref5_05_10.png')

    py.clf()
    q = py.quiver(g2005['x'], g2005['y'], dx_05_13, dy_05_13, scale=2e2)
    py.quiverkey(q, 0.95, 0.95, 5, '5 mas', color='red', labelcolor='red')
    py.title('2013 - 2005')
    py.savefig('vec_diff_ref5_05_13.png')

    py.clf()
    q = py.quiver(g2005['x'], g2005['y'], dx_10_13, dy_10_13, scale=1e2)
    py.quiverkey(q, 0.95, 0.95, 5, '5 mas', color='red', labelcolor='red')
    py.title('2013 - 2010')
    py.savefig('vec_diff_ref5_10_13.png')

    py.clf()
    py.plot(dx_05_10, dy_05_10, 'k.', ms=2)
    lim = 10
    py.axis([-lim, lim, -lim, lim])
    py.xlabel('X Proper Motion (mas)')
    py.ylabel('Y Proper Motion (mas)')
    py.title('2010 - 2005')
    py.savefig('pm_diff_ref5_05_10.png')

    py.clf()
    py.plot(dx_05_13, dy_05_13, 'k.', ms=2)
    py.axis([-lim, lim, -lim, lim])
    py.xlabel('X Proper Motion (mas)')
    py.ylabel('Y Proper Motion (mas)')
    py.title('2013 - 2005')
    py.savefig('pm_diff_ref5_05_13.png')

    py.clf()
    py.plot(dx_10_13, dy_10_13, 'k.', ms=2)
    py.axis([-lim, lim, -lim, lim])
    py.xlabel('X Proper Motion (mas)')
    py.ylabel('Y Proper Motion (mas)')
    py.title('2013 - 2010')
    py.savefig('pm_diff_ref5_10_13.png')

    print('2010 - 2005')
    print('   dx = {dx:6.2f} +/- {dxe:6.2f} mas'.format(dx=dx_05_10.mean(), dxe=dx_05_10.std()))
    print('   dy = {dy:6.2f} +/- {dye:6.2f} mas'.format(dy=dy_05_10.mean(), dye=dy_05_10.std()))

    print('2013 - 2005')
    print('   dx = {dx:6.2f} +/- {dxe:6.2f} mas'.format(dx=dx_05_13.mean(), dxe=dx_05_13.std()))
    print('   dy = {dy:6.2f} +/- {dye:6.2f} mas'.format(dy=dy_05_13.mean(), dye=dy_05_13.std()))

    print('2013 - 2010')
    print('   dx = {dx:6.2f} +/- {dxe:6.2f} mas'.format(dx=dx_10_13.mean(), dxe=dx_10_13.std()))
    print('   dy = {dy:6.2f} +/- {dye:6.2f} mas'.format(dy=dy_10_13.mean(), dye=dy_10_13.std()))
예제 #37
0
# create a figure, add an axes.
fig = figure(figsize=(8, 8))
ax = fig.add_axes([0.1, 0.1, 0.7, 0.7])
# rotate wind vectors to map projection coordinates.
# (also compute native map projections coordinates of lat/lon grid)
# only do Northern Hemisphere.
urot, vrot, x, y = m.rotate_vector(u[36:, :],
                                   v[36:, :],
                                   lons[36:, :],
                                   lats[36:, :],
                                   returnxy=True)
# plot filled contours over map.
cs = m.contourf(x, y, p[36:, :], 15, cmap=cm.jet)
# plot wind vectors over map.
Q = m.quiver(x, y, urot, vrot)  #or specify, e.g., width=0.003, scale=400)
qk = quiverkey(Q, 0.95, 1.05, 25, '25 m/s', labelpos='W')
cax = axes([0.875, 0.1, 0.05, 0.7])  # setup colorbar axes.
colorbar(cax=cax)  # draw colorbar
axes(ax)  # make the original axes current again
m.drawcoastlines()
m.drawcountries()
# draw parallels
delat = 20.
circles = arange(0.,90.+delat,delat).tolist()+\
          arange(-delat,-90.-delat,-delat).tolist()
m.drawparallels(circles, labels=[1, 1, 1, 1])
# draw meridians
delon = 45.
meridians = arange(-180, 180, delon)
m.drawmeridians(meridians, labels=[1, 1, 1, 1])
title('Surface Winds Winds and Pressure (lat-lon grid)', y=1.075)
예제 #38
0
파일: utils.py 프로젝트: Joz84/pywrf
def plot_slab(lon, lat, slab,
  map = None,
  figsize = None,
  cntr_lvl = None,
  title_string = 'N/A',
  meridians_delta = 15,
  parallels_delta = 15,
  file_name = None,
  dpi = 80,
  wind_vector =None,
  quiv_skip = 5,
  frame_width = 5,
  significant_digits = 0,
  colorbar = False,
  contour_labels = True,
  monochrome = False,
  quiverkey_length = 10,
  return_map = False
  ):
    from matplotlib.cm import gist_ncar as cmap
    # let's make sure the lat and lon arrays are 2D
    if len(lon.shape) < 2:
        lon, lat = p.meshgrid(lon,lat)
    if map is None:
        map = set_default_basemap(lon,lat,frame_width)
    if not figsize:
        fig = p.figure()
    else:
        fig = p.figure(figsize=figsize)
    if cntr_lvl is not None:
        if monochrome:
            cset = map.contour(lon, lat, slab, cntr_lvl, colors='black')
        else:
            csetf = map.contourf(lon, lat, slab, 
              cntr_lvl, 
              cmap=cmap)
            if wind_vector is None:
                cset = map.contour(lon, lat, slab, cntr_lvl, colors='lightslategray')
    else:
        if monochrome:
            cset = map.contour(lon, lat, slab, colors='black')
        else:
            csetf = map.contourf(lon, lat, slab, cmap=cmap)
            if wind_vector is None:
                cset = map.contour(lon, lat, slab, colors='lightslategray')
    if wind_vector is not None:
        quiv = map.quiver(lon[::quiv_skip,::quiv_skip], 
          lat[::quiv_skip,::quiv_skip],
          wind_vector[0][::quiv_skip,::quiv_skip],
          wind_vector[1][::quiv_skip,::quiv_skip])
        from scipy.stats import median
        p.quiverkey(quiv, 
          0.855, 
          0.115, 
          quiverkey_length,
          str(int(quiverkey_length)) + ' m/s',
          labelpos='S',
          coordinates='figure')
    # plot grid outline
    map.plot(lon[0,:],lat[0,:],color='lightslategray')
    map.plot(lon[-1,:],lat[-1,:],color='lightslategray')
    map.plot(lon[:,0],lat[:,0],color='lightslategray')
    map.plot(lon[:,-1],lat[:,-1],color='lightslategray')
    if monochrome:
        map.fillcontinents(color='0.95')

    map.drawcoastlines()

    # todo
    # the +5 is a hack in case one uses the default map it should be made an
    # an explicit parameter that is passed around...
    meridians = n.arange(int(round(lon.min(),0)), 
      #int(round(lon.max(),0)) + a_small_number, meridians_delta)
      int(round(lon.max(),0)) + 5 + a_small_number, meridians_delta)
    meridians = n.array(meridians)
    map.drawmeridians(meridians, labels=[1,0,0,1])

    parallels = n.arange(int(round(lat.min(),0)), 
      #int(round(lat.max(),0)) + a_small_number, parallels_delta)
      int(round(lat.max(),0)) + 5 + a_small_number, parallels_delta)
    parallels = n.array(parallels)
    map.drawparallels(parallels, labels=[1,0,0,1])

    #plot canberra
    if 1:
        map.plot([149.133],[-35.283],'bo', ms=3)

    if contour_labels:
        p.clabel(cset, cset.levels[::2], 
          colors='k', fontsize=8, fmt='%i')

    if colorbar:
        format = '%.'+ str(significant_digits) + 'f'
        p.colorbar(csetf, orientation='horizontal', shrink=0.7, 
          fraction=0.02, pad=0.07, aspect=70, 
          format = format)

    p.title(title_string)
    if file_name:
        p.savefig(file_name,dpi=dpi)
        p.close(fig)
        del fig
    if not monochrome:
        del csetf
    if wind_vector is None:
        del cset
    if wind_vector is not None:
        del quiv
    gc.collect()
    if return_map:
        return map
    else:
        del map
        gc.collect()
        return
예제 #39
0
# north polar projection.
m = Basemap(lon_0=-135,boundinglat=25,
            resolution='c',area_thresh=10000.,projection='npstere')
# create a figure, add an axes.
fig=figure(figsize=(8,8))
ax = fig.add_axes([0.1,0.1,0.7,0.7])
# rotate wind vectors to map projection coordinates.
# (also compute native map projections coordinates of lat/lon grid)
# only do Northern Hemisphere.
urot,vrot,x,y = m.rotate_vector(u[36:,:],v[36:,:],lons[36:,:],lats[36:,:],returnxy=True)
# plot filled contours over map.
cs = m.contourf(x,y,p[36:,:],15,cmap=cm.jet)
# plot wind vectors over map.
Q = m.quiver(x,y,urot,vrot) #or specify, e.g., width=0.003, scale=400)
qk = quiverkey(Q, 0.95, 1.05, 25, '25 m/s', labelpos='W')
cax = axes([0.875, 0.1, 0.05, 0.7]) # setup colorbar axes.
colorbar(cax=cax) # draw colorbar
axes(ax)  # make the original axes current again
m.drawcoastlines()
m.drawcountries()
# draw parallels
delat = 20.
circles = arange(0.,90.+delat,delat).tolist()+\
          arange(-delat,-90.-delat,-delat).tolist()
m.drawparallels(circles,labels=[1,1,1,1])
# draw meridians
delon = 45.
meridians = arange(-180,180,delon)
m.drawmeridians(meridians,labels=[1,1,1,1])
title('Surface Winds Winds and Pressure (lat-lon grid)',y=1.075)
예제 #40
0
plt.plot(targets[0][0],
         targets[0][1],
         'ko',
         markersize=10,
         markerfacecolor='none')

plt.subplot(224)

Q = plt.quiver(X,Y,uwind, vwind, \

           scale=5,scale_units='inches',color='black',alpha=0.5)

qk = plt.quiverkey(Q,
                   51.75,
                   32.1,
                   1,
                   r'$1 \frac{m}{s}$',
                   labelpos='E',
                   coordinates='data')

plt.plot(targets[0][0],
         targets[0][1],
         'ko',
         markersize=10,
         markerfacecolor='none')

#

# Source pixel method

#
예제 #41
0
def velocity_image(sim,
                   width="10 kpc",
                   vector_color='black',
                   edgecolor='black',
                   quiverkey_bg_color=None,
                   vector_resolution=40,
                   scale=None,
                   mode='quiver',
                   key_x=0.3,
                   key_y=0.9,
                   key_color='white',
                   key_length="100 km s**-1",
                   quiverkey=True,
                   density=1.0,
                   vector_qty='vel',
                   **kwargs):
    """

    Make an SPH image of the given simulation with velocity vectors overlaid on top.

    For a description of additional keyword arguments see :func:`~pynbody.plot.sph.image`,
    or see the `tutorial <http://pynbody.github.io/pynbody/tutorials/pictures.html#velocity-vectors>`_.

    **Keyword arguments:**

    *vector_color* (black): The color for the velocity vectors

    *edgecolor* (black): edge color used for the lines - using a color
     other than black for the *vector_color* and a black *edgecolor*
     can result in poor readability in pdfs

    *vector_resolution* (40): How many vectors in each dimension (default is 40x40)

    *quiverkey_bg_color* (none): The color for the legend (scale) background

    *scale* (None): The length of a vector that would result in a displayed length of the
    figure width/height.

    *mode* ('quiver'): make a 'quiver' or 'stream' plot

    *key_x* (0.3): Display x (width) position for the vector key (quiver mode only)

    *key_y* (0.9): Display y (height) position for the vector key (quiver mode only)

    *key_color* (white): Color for the vector key (quiver mode only)

    *key_length* (100 km/s): Velocity to use for the vector key (quiver mode only)

    *density* (1.0): Density of stream lines (stream mode only)

    *quiverkey* (True): Whether or not to inset the key

    *vector_qty* ('vel'): The name of the vector field to plot
    """

    subplot = kwargs.get('subplot', False)
    av_z = kwargs.get('av_z', None)
    if subplot:
        p = subplot
    else:
        import matplotlib.pylab as p

    vx_name, vy_name, _ = sim._array_name_ND_to_1D(vector_qty)

    vx = image(sim,
               qty=vx_name,
               width=width,
               log=False,
               resolution=vector_resolution,
               noplot=True,
               av_z=av_z)
    vy = image(sim,
               qty=vy_name,
               width=width,
               log=False,
               resolution=vector_resolution,
               noplot=True,
               av_z=av_z)
    key_unit = _units.Unit(key_length)

    if isinstance(width, str) or issubclass(width.__class__, _units.UnitBase):
        if isinstance(width, str):
            width = _units.Unit(width)
        width = width.in_units(sim['pos'].units, **sim.conversion_context())

    width = float(width)

    pixel_size = width / vector_resolution
    X, Y = np.meshgrid(
        np.arange(-width / 2 + pixel_size / 2, width / 2 + pixel_size / 2,
                  pixel_size),
        np.arange(-width / 2 + pixel_size / 2, width / 2 + pixel_size / 2,
                  pixel_size))

    im = image(sim, width=width, **kwargs)

    if mode == 'quiver':
        if scale is None:
            Q = p.quiver(X, Y, vx, vy, color=vector_color, edgecolor=edgecolor)
        else:
            Q = p.quiver(X,
                         Y,
                         vx,
                         vy,
                         scale=_units.Unit(scale).in_units(sim['vel'].units),
                         color=vector_color,
                         edgecolor=edgecolor)
        if quiverkey:
            qk = p.quiverkey(Q,
                             key_x,
                             key_y,
                             key_unit.in_units(sim['vel'].units,
                                               **sim.conversion_context()),
                             r"$\mathbf{" + key_unit.latex() + "}$",
                             labelcolor=key_color,
                             color=key_color,
                             fontproperties={'size': 24})
        if quiverkey_bg_color is not None:
            qk.text.set_backgroundcolor(quiverkey_bg_color)
    elif mode == 'stream':
        Q = p.streamplot(X, Y, vx, vy, color=vector_color, density=density)

# RS - if a axis object is passed in, use the right limit call
    if subplot:
        p.set_xlim(-width / 2, width / 2)
        p.set_ylim(-width / 2, width / 2)
    else:
        p.xlim(-width / 2, width / 2)
        p.ylim(-width / 2, width / 2)

    return im
예제 #42
0
        diffyf = [diffys[0]]
        
        
        print "Selecting low density..."
        
        for goodx, goody, diffx, diffy in zip(goodxs, goodys, diffxs, diffys):
            if min(sqrt((goodx - array(goodxf))**2 + (goody - array(goodyf))**2)) > opts.quiv_dist:
                goodxf.append(goodx)
                goodyf.append(goody)
                diffxf.append(diffx)
                diffyf.append(diffy)
    
        if not opts.quiet:
            figure()
            Q = quiver(goodxf, goodyf, diffxf, diffyf, 
                        angles='xy', minshaft=2, units='dots', scale=1)
            scale = math.sqrt(median(array(diffx)**2 + array(diffy)**2)) 
            title('%s with mapping %s and error < %d' % 
                        (os.path.dirname(fname) ,
                         str(opts.map or opts.yshift), 
                         opts.max_r))
            print scale
            if scale < 50:
                quiverkey(Q, .1, .1, 10, '$10 nm$', color="blue")
            else:
                quiverkey(Q, .1, .1, 1000, r'$1\mu m$', color="blue")
            figure()
            plot(diffxs, diffys, 'ro')
            title(os.path.dirname(fname))

예제 #43
0
def show_shwfs_vecs(shiftvec,
                    subaps,
                    refpos=None,
                    img=None,
                    extent=None,
                    title=None,
                    scale=10,
                    pause=False,
                    fignum=None,
                    keep=True):
    """
	Show a SHWFS measurements with subapertures and potentially a background 
	image. If **refpos** is given, SHWFS shift vectors will be plotted at 
	those locations, otherwise at the center of the sub apertures.

	Additionally, a background image (wavefront, sensor image) can be 
	plotted along with the measurements in the background. If the coordinate 
	system is different than that of the sub apertures, this can be fixed by 
	using the **extent** keyword.

	**Scale** tweaks the arrow length, unity being the approximate real size.
	The default is 10 to enhance the visibility.

	@param [in] shiftvec (N,2) vector with shifts
	@param [in] subaps (N,4) vector with sub aperture positions as (low0, high0, low1, high1)
	@param [in] refpos Positions to plot shift vectors at (if None use subaps center)
	@param [in] img Background image, e.g. a wavefront
	@param [in] extent Extent for the image for imshow()
	@param [in] title Plot title
	@param [in] scale Scale used for arrow width, unity is approximately
	@param [in] pause Pause before continuing
	@param [in] fignum Figure number to use for figure()
	@param [in] keep Keep plot window open after returning
	"""

    import pylab as plt
    from matplotlib.collections import PatchCollection

    sasize = np.r_[subaps[:, :2].ptp(1).mean(), subaps[:, 2:].ptp(1).mean()]
    subaps_im = [
        plt.Rectangle((subap[1], subap[0]),
                      sasize[0],
                      sasize[1],
                      fc='none',
                      ec='k') for subap in subaps[:, ::2]
    ]

    plt.figure(fignum)
    plt.clf()
    plt.title(title or "SHWFS vectors on MLA grid")

    if (img != None): plt.imshow(img, extent=extent)

    if (refpos == None): refpos = subaps[:, ::2] + sasize / 2

    q = plt.quiver(refpos[:, 1],
                   refpos[:, 0],
                   shiftvec[:, 1],
                   shiftvec[:, 0],
                   angles='xy',
                   scale=refpos.ptp() / 10.,
                   color='r')
    p = plt.quiverkey(q,
                      refpos.min(0)[1],
                      refpos.min(0)[0],
                      5,
                      "5 pix.",
                      coordinates='data',
                      color='r')

    thisgca = plt.gca()
    thisgca.add_collection(PatchCollection(subaps_im, match_original=True))

    if (pause): raw_input("Press any key to continue...")
    if (not keep): plt.close()
예제 #44
0
def residInPixels(tab, binpix=256, scaleFudge=1., maxErr=50):
    '''
    Return a 2d vector diagram of weighted mean astrometric residual in pixelized areas.
    Residuals shown in milliarcsec, and the binned resid arrays are returned.
    binpix is the width of cells (in nominal pixel size)
    scaleFudge is multiplier of arrow length scaling (and key size) 
    to apply to default choice. By default, arrows are scaled so that 
    typical arrow is of length equal to the distance between arrows (cell size).

    maxErr is the largest error that a binned vector can have (mas) and still be plotted,
    to avoid cluttering up the plot with noisy arrows.
    '''

    noData = np.nan

    if len(tab) < 100:
        # Not enough residuals to even try.
        return None
    # use exposure coordinates:
    x = tab['u']  ### Problem is these are not relative to array center!!
    y = tab['v']
    residx = tab['dx']
    residy = tab['dy']
    sig = tab['measErr']
    xyBuffer = 0.05  # buffer in degrees
    cellSize = binpix * pixScale / (1000. * 3600.)

    weight = np.where(sig > 0, 1. / (sig * sig), 0.)
    xmin = np.min(x)
    xmax = np.max(x)
    ymin = np.min(y)
    ymax = np.max(y)

    xsize = int(np.ceil((xmax - xmin) / cellSize))
    ysize = int(np.ceil((ymax - ymin) / cellSize))

    # Figure out the image pixel for each residual point
    ix = np.array(np.floor((x - xmin) / cellSize), dtype=int)
    ix = np.clip(ix, 0, xsize - 1)
    iy = np.array(np.floor((y - ymin) / cellSize), dtype=int)
    iy = np.clip(iy, 0, ysize - 1)
    index = iy * xsize + ix

    sumxw = np.histogram(index,
                         bins=xsize * ysize,
                         range=(-0.5, xsize * ysize + 0.5),
                         weights=weight * residx)[0]
    sumyw = np.histogram(index,
                         bins=xsize * ysize,
                         range=(-0.5, xsize * ysize + 0.5),
                         weights=weight * residy)[0]
    sumw = np.histogram(index,
                        bins=xsize * ysize,
                        range=(-0.5, xsize * ysize + 0.5),
                        weights=weight)[0]
    # Smallest weight that we'd want to plot a point for
    minWeight = maxErr**(-2)
    # Value to put in where weight is below threshold:
    sumxw = np.where(sumw > minWeight, sumxw / sumw, noData)
    sumyw = np.where(sumw > minWeight, sumyw / sumw, noData)
    sumw = np.where(sumw > minWeight, 1. / sumw, noData)
    rmsx = np.std(sumxw[sumw > 0.])
    rmsy = np.std(sumyw[sumw > 0.])
    print('RMSx, RMSy, noise:', rmsx, rmsy, np.sqrt(np.mean(sumw[sumw > 0.])))

    # Make an x and y position for each cell to be the center of its cell
    xpos = np.arange(xsize * ysize, dtype=int)
    xpos = ((xpos % xsize) + 0.5) * cellSize + xmin
    ypos = np.arange(xsize * ysize, dtype=int)
    ypos = ((ypos // xsize) + 0.5) * cellSize + ymin

    useful = np.logical_and(sumw != 0, sumw < (maxErr * maxErr))
    dx = sumxw[useful]
    dy = sumyw[useful]
    xpos = xpos[useful]
    ypos = ypos[useful]

    # Choose a scale which makes arrow length similar to spacing,
    # with a choice of round numbers for scale equal to spacing.
    typicalArrow = np.percentile(np.hypot(dx, dy), 90.)
    # Choose a scale at a round number, 1/2/5 x 10^N
    choices = np.array([1., 2., 5.])
    i = np.floor(np.log10(typicalArrow))
    j = np.where(typicalArrow / 10.**i >= choices)[0][-1]
    keyLength = choices[j] * 10**i
    arrowScale = keyLength / cellSize
    arrowScale /= scaleFudge  # Adjust lengths of arrows if desired

    # Now make the plot
    q = pl.quiver(
        xpos,
        ypos,
        dx,
        dy,
        pivot='middle',
        color='green',
        angles='xy',
        scale_units='xy',
        scale=arrowScale,
        #scale=0.001,
        units='x')  ##width=5.,headlength=10,headwidth=8 )

    QK = pl.quiverkey(q,
                      0.5,
                      0.5,
                      keyLength,
                      '{:.1f} mas'.format(keyLength),
                      coordinates='axes',
                      color='red',
                      labelpos='N',
                      labelcolor='red')
    pl.xlim(xmin - xyBuffer, xmax + xyBuffer)
    pl.ylim(ymin - xyBuffer, ymax + xyBuffer)

    pl.gca().set_aspect('equal')
    pl.grid()

    return dx, dy, xpos, ypos, sumw
예제 #45
0
 # plot wind vectors on lat/lon grid.
 # rotate wind vectors to map projection coordinates.
 #urot,vrot = m.rotate_vector(u[nt,:,:],v[nt,:,:],lons,lats)
 # plot wind vectors over map.
 #Q = m.quiver(x,y,urot,vrot,scale=500) 
 # plot wind vectors on projection grid (looks better).
 # first, shift grid so it goes from -180 to 180 (instead of 0 to 360
 # in longitude).  Otherwise, interpolation is messed up.
 ugrid,newlons = shiftgrid(180.,u[nt,:,:],longitudes,start=False)
 vgrid,newlons = shiftgrid(180.,v[nt,:,:],longitudes,start=False)
 # transform vectors to projection grid.
 urot,vrot,xx,yy = m.transform_vector(ugrid,vgrid,newlons,latitudes,51,51,returnxy=True,masked=True)
 # plot wind vectors over map.
 Q = m.quiver(xx,yy,urot,vrot,scale=500)
 # make quiver key.
 qk = p.quiverkey(Q, 0.1, 0.1, 20, '20 m/s', labelpos='W')
 # draw coastlines, parallels, meridians, title.
 m.drawcoastlines(linewidth=1.5)
 m.drawparallels(parallels)
 m.drawmeridians(meridians)
 p.title('SLP and Wind Vectors '+date)
 if nt == 0: # plot colorbar on a separate axes (only for first frame)
     cax = p.axes([l+w-0.05, b, 0.03, h]) # setup colorbar axes
     fig.colorbar(CS,drawedges=True, cax=cax) # draw colorbar
     cax.text(0.0,-0.05,'mb')
     p.axes(ax) # reset current axes
 p.draw() # draw the plot
 # save first and last frame n1 times 
 # (so gif animation pauses at beginning and end)
 if nframe == 0 or nt == slp.shape[0]-1:
    for n in range(n1):
예제 #46
0
def myplot(path='.',output=-1,sink=False,center=[0.5,0.5,0.5],los='x',size=[0.5,0.5], \
           minimum=None,maximum=None,typlot='rho',record=False,igrp=-1,plot_velocity=False,slice=False):

    filerep = path
    if (record):
        savedir = os.path.join(filerep, "results")
        if not os.path.exists(savedir):
            os.makedirs(savedir)
        #mu,alpha,lmax = parseDirSink(directory)
        #savedir       = checkDir(savedir, "mu" + mu)
        #savedir       = checkDir(savedir, "lmax" + lmax)

    # if output=-1, take last output
    if output == -1:
        outputname = np.sort(glob.glob(os.path.join(filerep,
                                                    "output_?????")))[-1]
        output = int(outputname.split('_')[-1])

    # Define the file
    ro = pm.RamsesOutput(filerep, output)

    if igrp != -1 and (igrp > ro.info["ngrp"] or igrp < 0):
        print(bold + 'PROBLEM:' + reset + ' igrp=' + str(igrp) +
              '  but simulation with ngrp=' + str(ro.info["ngrp"]))
        sys.exit(1)

    # Define the output data structure (to use with pymses5)
    ro.define_amr_scalar_field("hydro", "rho", 0)
    ro.define_amr_vector_field("hydro", "vel", [1, 2, 3])
    ro.define_amr_vector_field("hydro", "Bl", [4, 5, 6])
    ro.define_amr_vector_field("hydro", "Br", [7, 8, 9])
    ro.define_amr_scalar_field("hydro", "P", 10)
    ro.define_amr_multivalued_field("hydro", "Er", 11, ro.info["ngrp"])
    ro.define_amr_vector_field(
        "hydro", "J",
        [11 + ro.info["ngrp"], 12 + ro.info["ngrp"], 13 + ro.info["ngrp"]])
    ro.define_amr_scalar_field("hydro", "eint", 14 + ro.info["ngrp"])
    if ro.info["eos"]:
        ro.define_amr_scalar_field("hydro", "T", 15 + ro.info["ngrp"])
    ro.define_amr_vector_field("grav", "g", [0, 1, 2])

    time = ro.info["time"] * ro.info["unit_time"].express(ct.kyr)
    if (sink):
        # Read sink particles
        sink_filename = os.path.join(
            filerep, 'output_%05d' % output + '/sink_%05d' % output + '.csv')
        print("Reading sinks     : " + reset + sink_filename)
        sinkp = np.loadtxt(sink_filename,
                           dtype={
                               'names':
                               ('Id', 'mass', 'x', 'y', 'z', 'vx', 'vy', 'vz',
                                'rot_period', 'lx', 'ly', 'lz', 'acc_rate',
                                'acc_lum', 'age', 'int_lum', 'Teff'),
                               'formats':
                               ('i', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f',
                                'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f')
                           },
                           delimiter=',')
        sinkp = np.atleast_1d(sinkp)  # to work even if only 1 sink
        nsink = sinkp.size

        # Define the accretion radius
        if ("ncell_racc" in ro.info):
            ncell_racc = ro.info['ncell_racc']
        else:
            ncell_racc = 4

        dxmin = 0.5**ro.info['levelmax'] * ro.info["unit_length"].express(
            ct.au)
        r_acc = dxmin * ncell_racc
        #area  = np.pi*r_acc**2

        xc, yc, zc = sinkp['x'] / ro.info['boxlen'], sinkp['y'] / ro.info[
            'boxlen'], sinkp['z'] / ro.info['boxlen']
    else:
        nsink = 0

    if nsink == 0:
        nsink = 1
        # Center
        xc, yc, zc = np.atleast_1d(center[0]), np.atleast_1d(
            center[1]), np.atleast_1d(center[2])

    cmap = pl.cm.get_cmap('seismic', 100)
    if typlot == 'rho':
        cmap = pl.cm.get_cmap('jet', 100)
    elif typlot == 'Tr':
        cmap = pl.cm.get_cmap('hot', 100)
    elif typlot == 'B':
        cmap = pl.cm.get_cmap('PuOr', 100)
    elif typlot == 'beta_plasma':
        cmap = pl.cm.get_cmap('seismic', 100)
    else:
        cmap = pl.cm.get_cmap('jet', 100)

    # Width of the region to plot
    xr, yr = size[0], size[1]
    xbl = (-xr / 2. * ro.info["unit_length"]).express(ct.au)
    xbr = (+xr / 2. * ro.info["unit_length"]).express(ct.au)
    ybl = (-yr / 2. * ro.info["unit_length"]).express(ct.au)
    ybr = (+yr / 2. * ro.info["unit_length"]).express(ct.au)
    extent = [xbl, xbr, ybl, ybr]

    # Define camera
    if los == 'x':
        upvec = "z"
        vx = 1
        vy = 2
        labelx = 'Y (AU)'
        labely = 'Z (AU)'
        plane = 'yz'
    elif los == 'y':
        upvec = "x"
        vx = 2
        vy = 0
        labelx = 'Z (AU)'
        labely = 'X (AU)'
        plane = 'zx'
    elif los == 'z':
        upvec = "y"
        vx = 0
        vy = 1
        labelx = 'X (AU)'
        labely = 'Y (AU)'
        plane = 'xy'

    def plot_func(dset):
        if typlot == 'rho':
            return dset['rho'] * ro.info["unit_density"].express(
                ct.g / ct.cm**3)
        if typlot == 'eint':
            return dset['eint'] * (ro.info["unit_density"] *
                                   ro.info["unit_velocity"]**2).express(
                                       ct.erg / ct.cm**3)
        if typlot == 'T':
            if ro.info["eos"]:
                return dset['T']
            else:
                return dset['P'] / dset['rho'] * ro.info[
                    "unit_temperature"].express(ct.K) * ro.info["mu_gas"]
        if typlot == 'B':
            B = 1./4*( (dset['Bl'][:,0]+dset['Br'][:,0])**2  \
                      +(dset['Bl'][:,1]+dset['Br'][:,1])**2  \
                      +(dset['Bl'][:,2]+dset['Br'][:,2])**2)
            return B
        # To use with pymses5
        if typlot == 'Er' or typlot == 'Tr':
            if igrp == -1:
                Er = np.sum(dset['Er'], axis=-1) * (
                    ro.info["unit_density"] *
                    ro.info["unit_velocity"]**2).express(ct.erg / ct.cm**3)
            else:
                Er = dset['Er'][:, igrp - 1] * (
                    ro.info["unit_density"] *
                    ro.info["unit_velocity"]**2).express(ct.erg / ct.cm**3)

            if typlot == 'Er':
                return Er
            else:
                return (Er / ct.a_R.express(ct.erg / ct.cm**3 / ct.K**4))**0.25

        if typlot == 'entropy':
            return dset['P'] / dset['rho']**ro.hydro_info["gamma"]

        if typlot == 'Pth_Pdyn':
            return dset['P'] / (0.5 * dset['rho'] *
                                np.sum(dset['vel']**2, axis=-1))

        if typlot == 'beta_plasma':
            B = 1./4.*( (dset['Bl'][:,0]+dset['Br'][:,0])**2  \
                      +(dset['Bl'][:,1]+dset['Br'][:,1])**2  \
                      +(dset['Bl'][:,2]+dset['Br'][:,2])**2)
            if igrp == -1:
                Er = np.sum(
                    dset['Er'], axis=-1
                )  #*(ro.info["unit_density"]*ro.info["unit_velocity"]**2).express(ct.erg/ct.cm**3)
            else:
                Er = dset[
                    'Er'][:, igrp -
                          1]  #*(ro.info["unit_density"]*ro.info["unit_velocity"]**2).express(ct.erg/ct.cm**3)

            return dset['P'] / (B)  #/dset['rho'])

        else:
            print(bold + 'Problem in typlot')
            sys.exit()

    # Fields to be read
    fields_to_read = []
    if (not ro.info["eos"] and typlot == 'T') or typlot == 'entropy':
        fields_to_read = ["rho", "P"]
    elif typlot == 'Tr':
        fields_to_read = ["Er"]
    elif typlot == 'Pth_Pdyn':
        fields_to_read = ["P", "rho", "vel"]
    elif typlot == 'B':
        fields_to_read = ["Bl", "Br"]
    elif typlot == 'beta_plasma':
        fields_to_read = ["Bl", "Br", "rho", "P", "Er"]
    else:
        fields_to_read = [typlot]
    if (plot_velocity):
        fields_to_read.append("vel")
    if not slice:
        fields_to_read.append("rho")

    fields_to_read = list(set(fields_to_read))  #to remove duplicates

    if slice:
        source = ro.amr_source(fields_to_read)
        varplot_op = ScalarOperator(plot_func)
    else:
        rt = raytracing.RayTracer(ro, fields_to_read)

        if typlot == 'rho':
            func = lambda dset: plot_func(dset) * ro.info["unit_length"
                                                          ].express(ct.cm)
            varplot_op = ScalarOperator(func)
        else:
            up_func = lambda dset: (dset["rho"] * ro.info["unit_density"].
                                    express(ct.g / ct.cm**3) * plot_func(dset))
            down_func = lambda dset: (dset["rho"] * ro.info["unit_density"].
                                      express(ct.g / ct.cm**3))
            varplot_op = FractionOperator(up_func, down_func)

    for i in range(nsink):
        fig = pl.figure()
        ax = pl.subplot(111)

        pl.xlabel(labelx)
        pl.ylabel(labely)

        cam = Camera(center=[xc[i], yc[i], zc[i]],line_of_sight_axis=los,region_size=[xr, yr] \
                         , up_vector=upvec,map_max_size=512, log_sensitive=True)

        if slice:
            mapx = SliceMap(source, cam, varplot_op, z=0.)
        else:
            # WARNING! surf_qty=True to get an integral over dz and not dSdz
            # so that if typlot=='rho', get surface density map
            # and if not, get a density-weighted map (and not a mass-weighted map)
            mapx = rt.process(varplot_op, cam, surf_qty=True)

        if typlot == 'Pth_Pdyn':
            imx    = pl.imshow(mapx.transpose(), extent = extent, origin='lower' \
                                   , vmin = minimum, vmax = maximum,cmap=cmap)
            #imx    = pl.contourf(mapx.transpose(), extent = extent, origin='lower' \
            #                       , vmin = minimum, vmax = maximum)
            cbar = pl.colorbar()
            cbar.set_label(typlot)
        else:
            imx    = pl.imshow(np.log10(mapx.transpose()), extent = extent, origin='lower' \
                                   , vmin = minimum, vmax = maximum,cmap=cmap)
            #imx    = pl.contourf(np.log10(mapx.transpose()), extent = extent, origin='lower' \
            #                       , vmin = minimum, vmax = maximum)
            cbar = pl.colorbar()

            #            cmap = pl.cm.get_cmap('jet',100)

            if typlot == 'rho':
                cbar.set_label(r'$\mathrm{log(}\rho)$', fontsize=15)
            elif typlot == 'Tr':
                cbar.set_label(r'$\mathrm{log(T_r)}$', fontsize=15)
            elif typlot == 'Pth_Pdyn':
                cbar.set_label('Pth/Pdyn')
            elif typlot == 'B':
                cbar.set_label('log(|B|)')
            elif typlot == 'beta_plasma':
                cbar.set_label(r'$\mathrm{log(}\beta)$', fontsize=15)
            else:
                cbar.set_label('Log(' + typlot + ')')

        if (sink):
            for isink in range(nsink):
                # Plot sinks position
                mass = sinkp[isink]["mass"]
                col = cmap(int(mass * 100))
                xp = (sinkp[isink]['x'] / ro.info['boxlen'] -
                      xc[i]) * ro.info["unit_length"].express(ct.au)
                yp = (sinkp[isink]['y'] / ro.info['boxlen'] -
                      yc[i]) * ro.info["unit_length"].express(ct.au)
                zp = (sinkp[isink]['z'] / ro.info['boxlen'] -
                      zc[i]) * ro.info["unit_length"].express(ct.au)

                if los == 'x':
                    ax.add_patch(
                        pl.Circle((yp, zp),
                                  radius=r_acc,
                                  fc='white',
                                  alpha=0.65))
                    ax.add_patch(
                        pl.Circle((yp, zp),
                                  radius=(r_acc / ncell_racc),
                                  fc=col,
                                  ec=col))
                #pl.plot(yp,zp,'k+',mew=2,ms=10)
                elif los == 'y':
                    ax.add_patch(
                        pl.Circle((zp, xp),
                                  radius=r_acc,
                                  fc='white',
                                  alpha=0.65))
                    ax.add_patch(
                        pl.Circle((zp, xp),
                                  radius=(r_acc / ncell_racc),
                                  fc=col,
                                  ec=col))
                #pl.plot(zp,xp,'k+',mew=2,ms=10)
                elif los == 'z':
                    ax.add_patch(
                        pl.Circle((xp, yp),
                                  radius=r_acc,
                                  fc='white',
                                  alpha=0.65))
                    ax.add_patch(
                        pl.Circle((xp, yp),
                                  radius=(r_acc / ncell_racc),
                                  fc=col,
                                  ec=col))
                #pl.plot(xp,yp,'k+',mew=2,ms=10)

        # Plot velocity field
        if (slice and plot_velocity):
            p = cam.get_slice_points(0.0)
            nx, ny = cam.get_map_size()
            dset = pm.analysis.sample_points(source, p)
            vel = dset["vel"] * ro.info["unit_velocity"].express(ct.km / ct.s)
            rs = 32
            x = np.linspace(xbl, xbr, nx)
            y = np.linspace(ybl, ybr, ny)
            u, v = np.zeros((nx, ny)), np.zeros((nx, ny))
            mask = np.zeros((nx, ny))
            for ii in range(nx):
                for jj in range(ny):
                    if (ii % rs == 0 and jj % rs == 0):
                        u[ii, jj] = vel[:, vx].reshape(nx, ny)[ii, jj]
                        v[ii, jj] = vel[:, vy].reshape(nx, ny)[ii, jj]
                    else:
                        u[ii, jj] = 'Inf'
                        v[ii, jj] = 'Inf'
                        mask[ii, jj] = 1

            u2 = u[::rs, ::rs]
            v2 = v[::rs, ::rs]
            x2 = x[::rs]
            y2 = y[::rs]

            vel_mean = np.mean(np.sqrt(u2**2 + v2**2))
            vel_max = np.max(np.sqrt(u2**2 + v2**2))

            #pl.quiver(x,y,u.transpose(),v.transpose(),scale=20*nx)
            #Q=pl.quiver(x,y,u.transpose(),v.transpose(),scale=100,pivot='mid')
            #u_masked=np.ma.masked_array(u,mask=mask)
            #v_masked=np.ma.masked_array(v,mask=mask)
            #vel_mean=np.mean(np.sqrt(u_masked**2+v_masked**2))

            Q = pl.quiver(x2,
                          y2,
                          u2.transpose(),
                          v2.transpose(),
                          scale=100,
                          pivot='mid')
            #pl.quiverkey(Q,0.7,0.92,vel_mean,r'%.2f km/s'%vel_mean,coordinates='figure')
            pl.quiverkey(Q,
                         0.7,
                         0.92,
                         vel_max,
                         r'%.2f km/s' % vel_max,
                         coordinates='figure')
            pl.axis(extent)
            del (u, v, x, y, u2, v2, x2, y2)

            if (sink):
                # Print the mass of the sinks
                mass = 0
                for j in range(nsink):
                    mass = mass + sinkp["mass"][j]

                pl.figtext(0.01,
                           00.01,
                           "$\mathrm{M}_*=$" + "%4.1f " % mass + "$M_\odot$",
                           fontsize=15)

        pl.suptitle("%.3f kyr" % time)

        if (record):
            for format in ("png", "eps", "pdf"):
                if slice:
                    namefig = os.path.join(
                        savedir, "slice_" + typlot + "_" + plane + "_eps" +
                        "_%.3f" % size[0] + "_out" + "_%05d" % output +
                        "_isink_%05d." % sinkp['Id'][i] + format)
                else:
                    namefig = os.path.join(
                        savedir, "proj_" + typlot + "_" + plane + "_eps" +
                        "_%.3f" % size[0] + "_out" + "_%05d" % output +
                        "_isink_%05d." % sinkp['Id'][i] + format)
                print(bold + "Save figure: " + reset + namefig)
                pl.savefig(namefig)
            pl.close()
        else:
            pl.ion()
            pl.show()

    if (sink):
        # Print the mass of the sinks
        for i in range(nsink):
            mass = sinkp["mass"][i]
            print(bold + "Mass(" + str(i) + "): " + reset + "%.2e Msun" % mass)
예제 #47
0
def display_moments(data=None):
    # remove the mean for all moments
    data = subMeanAll(data)
    pl.figure(figsize=(11,11))
    pl.subplot(2,2,1)
    phi22 = 0.5*np.arctan2(data[:,3].imag,data[:,3].real)
    x = data[:,0].real
    y = data[:,1].real
    phi22[x<0] = phi22+np.deg2rad(180)
    u = np.abs(data[:,3])*np.cos(phi22)
    v = np.abs(data[:,3])*np.sin(phi22)
    qvr = pl.quiver(x,y,u,v,width = 0.004, color='r',pivot='middle',headwidth=0.,headlength=0.,headaxislength=0.,scale_units='width')
    qk = pl.quiverkey(qvr, -150,-240,np.max(np.sqrt(u**2+v**2)),str(round(np.max(np.sqrt(u**2+v**2)),3))+' pix^2',coordinates='data',color='blue')
    pl.plot(x,y,'b,')
    pl.xlim(-250,250)
    pl.ylim(-250,250)
    pl.grid(color='g')
    pl.xlabel('X [mm] (WEST)')
    pl.ylabel('Y [mm] (NORTH)')
    pl.title('M22')
    pl.subplot(2,2,2)
    phi31 = np.arctan2(data[:,4].imag,data[:,4].real)
    u = np.abs(data[:,4])*np.cos(phi31)
    v = np.abs(data[:,4])*np.sin(phi31)
    qvr=pl.quiver(x,y,u,v,width=0.003,color='r',pivot='middle',headwidth=4)
    qk = pl.quiverkey(qvr, -150,-240,np.max(np.sqrt(u**2+v**2)),str(round(np.max(np.sqrt(u**2+v**2)),3))+' pix^3',coordinates='data',color='blue')
    pl.plot(x,y,'b,')
    pl.xlim(-250,250)
    pl.ylim(-250,250)
    pl.grid(color='g')
    pl.xlabel('X [mm] (WEST)')
    pl.ylabel('Y [mm] (NORTH)')
    pl.title('M31')
    pl.subplot(2,2,3)
    phi33 = np.arctan2(data[:,5].imag,data[:,5].real)/3.
    u = np.abs(data[:,5])*np.cos(phi33)
    v = np.abs(data[:,5])*np.sin(phi33)
    pl.quiver(x,y,u,v,width=0.003,color='r',headwidth=4)
    u = np.abs(data[:,5])*np.cos(phi33+np.deg2rad(120))
    v = np.abs(data[:,5])*np.sin(phi33+np.deg2rad(120))
    pl.quiver(x,y,u,v,width=0.003,color='r',headwidth=4)
    u = np.abs(data[:,5])*np.cos(phi33+np.deg2rad(240))
    v = np.abs(data[:,5])*np.sin(phi33+np.deg2rad(240))
    qvr=pl.quiver(x,y,u,v,width=0.003,color='r',headwidth=4)
    qk = pl.quiverkey(qvr, -150,-240,np.max(np.sqrt(u**2+v**2)),str(round(np.max(np.sqrt(u**2+v**2)),3))+' pix^3',coordinates='data',color='blue')
    pl.plot(x,y,'b,')
    pl.xlim(-250,250)
    pl.ylim(-250,250)
    pl.grid(color='g')
    pl.xlabel('X [mm] (WEST)')
    pl.ylabel('Y [mm] (NORTH)')
    pl.title('M33')
    pl.subplot(2,2,4)
    m20sqr = np.sqrt(data[:,2].real)
    x = data[:,0].real
    y = data[:,1].real
    m20sqr_med = np.median(m20sqr)
    m20sqr_diff = m20sqr - m20sqr_med
    m20sqr_diff_absmed = np.median(np.abs(m20sqr_diff))
    plotScale = 1./m20sqr_diff_absmed*100
    pos = m20sqr_diff >=0
    neg = m20sqr_diff < 0
    pl.scatter(x[pos],y[pos],s=m20sqr_diff[pos]*plotScale,c='r',alpha=0.5)
    pl.scatter(x[neg],y[neg],s=-m20sqr_diff[neg]*plotScale,c='b',alpha=0.5)
    pl.scatter(-230,-210,s=m20sqr_diff_absmed*plotScale,c='b',alpha=0.5)
    pl.text(-200,-215,'-'+str(round(m20sqr_diff_absmed,6))+' pix')
    pl.scatter(-230,-230,s=m20sqr_diff_absmed*plotScale,c='r',alpha=0.5)
    pl.text(-200,-235,str(round(m20sqr_diff_absmed,6))+' pix')
    pl.plot(x,y,'y,')
    pl.grid(color='g')
    pl.xlim(-250,250)
    pl.ylim(-250,250)
    pl.xlabel('X [mm] (WEST)')
    pl.ylabel('Y [mm] (NORTH)')
    pl.title('median '+r'$\sqrt{M20}$: '+str(round(scale*m20sqr_med,3))+' [arcsec]')
    return '---done!--'
예제 #48
0
def makeVectorField(f, xmin, xmax, ymin, ymax, step):
    X, Y = meshgrid(arange(xmin, xmax, step), arange(ymin, ymax, step))
    U, V = zip(*map(lambda xx: f(*xx), zip(X, Y)))
    Q = quiver(X, Y, U, V, units='width')
    quiverkey(Q, 0, 0, 4, '', coordinates='figure', labelpos='W')
예제 #49
0
파일: sph.py 프로젝트: migueldvb/pynbody
def velocity_image(sim, width="10 kpc", vector_color='black', edgecolor='black', quiverkey_bg_color=None,
                   vector_resolution=40, scale=None, mode='quiver', key_x=0.3, key_y=0.9,
                   key_color='white', key_length="100 km s**-1", quiverkey=True, density=1.0, **kwargs):
    """

    Make an SPH image of the given simulation with velocity vectors overlaid on top.

    For a description of additional keyword arguments see :func:`~pynbody.plot.sph.image`,
    or see the `tutorial <http://pynbody.github.io/pynbody/tutorials/pictures.html#velocity-vectors>`_.

    **Keyword arguments:**

    *vector_color* (black): The color for the velocity vectors

    *edgecolor* (black): edge color used for the lines - using a color
     other than black for the *vector_color* and a black *edgecolor*
     can result in poor readability in pdfs

    *vector_resolution* (40): How many vectors in each dimension (default is 40x40)

    *quiverkey_bg_color* (none): The color for the legend (scale) background

    *scale* (None): The length of a vector that would result in a displayed length of the
    figure width/height.

    *mode* ('quiver'): make a 'quiver' or 'stream' plot

    *key_x* (0.3): Display x (width) position for the vector key (quiver mode only)

    *key_y* (0.9): Display y (height) position for the vector key (quiver mode only)

    *key_color* (white): Color for the vector key (quiver mode only)

    *key_length* (100 km/s): Velocity to use for the vector key (quiver mode only)

    *density* (1.0): Density of stream lines (stream mode only)

    *quiverkey* (True): Whether or not to inset the key

    """

    subplot = kwargs.get('subplot', False)
    av_z = kwargs.get('av_z',None)
    if subplot:
        p = subplot
    else:
        import matplotlib.pylab as p

    vx = image(sim, qty='vx', width=width, log=False,
               resolution=vector_resolution, noplot=True,av_z=av_z)
    vy = image(sim, qty='vy', width=width, log=False,
               resolution=vector_resolution, noplot=True,av_z=av_z)
    key_unit = _units.Unit(key_length)

    if isinstance(width, str) or issubclass(width.__class__, _units.UnitBase):
        if isinstance(width, str):
            width = _units.Unit(width)
        width = width.in_units(sim['pos'].units, **sim.conversion_context())

    width = float(width)

    X, Y = np.meshgrid(np.arange(-width / 2, width / 2, width / vector_resolution),
                       np.arange(-width / 2, width / 2, width / vector_resolution))

    im = image(sim, width=width, **kwargs)

    if mode == 'quiver':
        if scale is None:
            Q = p.quiver(X, Y, vx, vy, color=vector_color, edgecolor=edgecolor)
        else:
            Q = p.quiver(X, Y, vx, vy, scale=_units.Unit(scale).in_units(
                sim['vel'].units), color=vector_color, edgecolor=edgecolor)
        if quiverkey:
        	qk = p.quiverkey(Q, key_x, key_y, key_unit.in_units(sim['vel'].units, **sim.conversion_context()),
                    r"$\mathbf{" + key_unit.latex() + "}$", labelcolor=key_color, color=key_color, fontproperties={'size': 24})
        if  quiverkey_bg_color is not None:
            qk.text.set_backgroundcolor(quiverkey_bg_color)
    elif mode == 'stream' :
        Q = p.streamplot(X, Y, vx, vy, color=vector_color, density=density)

    return im
예제 #50
0
def plot_comparison(tableSuffix,
                    posLim=0.15,
                    magLimits=[-13, -1],
                    errLim=0.04,
                    quiverScale=2):
    """
    Load up starlists produced by matchup_ks2_pass1() and plot some parameters
    of interest. Just pass in the filter suffix (e.g. "_f0"). Plots include:

    delta-x vs. m
    delta-y vs. m
    delta-m vs. m
    uncertainties vs. m for both lists
    me vs. m for stars in ks2 vs. stars not in ks2
    """
    stars = atpy.Table('stars_ks2_pass1%s.fits' % tableSuffix)
    other = atpy.Table('stars_pass1_only%s.fits' % tableSuffix)

    print '%6d stars in ks2' % len(stars)
    print '%6d stars not found in ks2' % len(other)

    #####
    # Plot delta-x vs. m
    #####
    dx = stars.x_ks2 - stars.x_pass1
    dxe = stars.xe_ks2

    #py.close('all')

    py.figure(1)
    py.clf()
    ax1 = py.subplot(2, 1, 1)
    py.plot(stars.m_pass1, dx, 'k.', ms=2)
    py.ylabel('dx (pix)')
    py.ylim(-posLim, posLim)
    py.axhline(y=0, color='r', linewidth=2)
    py.title('KS2 - One Pass')

    ax2 = py.subplot(2, 1, 2, sharex=ax1)
    py.plot(stars.m_pass1, dx / dxe, 'k.', ms=2)
    py.ylabel('dx/dxe (sigma)')
    py.ylim(-3, 3)
    py.axhline(y=0, color='r', linewidth=2)
    py.xlabel('Magnitude')
    py.xlim(magLimits[0], magLimits[1])
    py.savefig('plot_dx_m%s.png' % tableSuffix)

    #####
    # Plot delta-y vs. m
    #####
    dy = stars.y_ks2 - stars.y_pass1
    dye = stars.ye_ks2

    py.figure(2)
    py.clf()
    ax1 = py.subplot(2, 1, 1)
    py.plot(stars.m_pass1, dy, 'k.', ms=2)
    py.ylabel('dy (pix)')
    py.ylim(-posLim, posLim)
    py.axhline(y=0, color='r', linewidth=2)
    py.title('KS2 - One Pass')

    ax2 = py.subplot(2, 1, 2, sharex=ax1)
    py.plot(stars.m_pass1, dy / dye, 'k.', ms=2)
    py.ylabel('dy/dye (sigma)')
    py.ylim(-3, 3)
    py.axhline(y=0, color='r', linewidth=2)
    py.xlabel('Magnitude')
    py.xlim(magLimits[0], magLimits[1])

    py.savefig('plot_dy_m%s.png' % tableSuffix)

    #####
    # Plot delta-m vs. m
    #####
    dm = stars.m_ks2 - stars.m_pass1
    dme = stars.me_ks2

    py.figure(3)
    py.clf()
    ax1 = py.subplot(2, 1, 1)
    py.plot(stars.m_pass1, dm, 'k.', ms=2)
    py.ylabel('dm (mag)')
    py.ylim(-0.1, 0.1)
    py.axhline(y=0, color='r', linewidth=2)
    py.title('KS2 - One Pass')

    ax2 = py.subplot(2, 1, 2, sharex=ax1)
    py.plot(stars.m_pass1, dm / dme, 'k.', ms=2)
    py.ylabel('dm/dme (sigma)')
    py.ylim(-3, 3)
    py.axhline(y=0, color='r', linewidth=2)
    py.xlabel('Magnitude')
    py.xlim(magLimits[0], magLimits[1])

    py.savefig('plot_dm_m%s.png' % tableSuffix)

    #####
    # Plot differences in errors vs. m
    #####
    dxerr = stars.xe_ks2 - stars.xe_pass1
    dyerr = stars.ye_ks2 - stars.ye_pass1
    dmerr = stars.me_ks2 - stars.me_pass1

    py.close(4)
    py.figure(4, figsize=(9, 12))
    py.clf()
    py.subplots_adjust(left=0.12, bottom=0.07, top=0.95)
    ax1 = py.subplot(3, 1, 1)
    py.plot(stars.m_ks2, dxerr, 'k.', ms=2)
    py.ylabel('xe diff')
    py.ylim(-0.05, 0.05)
    py.axhline(y=0, color='r', linewidth=2)
    py.title('KS2 - One Pass')

    ax2 = py.subplot(3, 1, 2, sharex=ax1)
    py.plot(stars.m_ks2, dyerr, 'k.', ms=2)
    py.ylabel('ye diff')
    py.ylim(-0.05, 0.05)
    py.axhline(y=0, color='r', linewidth=2)

    ax3 = py.subplot(3, 1, 3, sharex=ax1)
    py.plot(stars.m_ks2, dmerr, 'k.', ms=2)
    py.ylabel('me diff')
    py.ylim(-0.05, 0.05)
    py.axhline(y=0, color='r', linewidth=2)

    py.xlabel('Magnitude')
    py.xlim(magLimits[0], magLimits[1])

    py.savefig('plot_compare_errors%s.png' % tableSuffix)

    #####
    # Plot stars that are NOT in KS2 vs. those that are.
    #####
    py.figure(5)
    py.clf()

    py.semilogy(stars.m_pass1, stars.me_pass1, 'k.', label='In KS2', ms=2)
    py.semilogy(other.m, other.me, 'r.', label='Not In KS2', ms=3)
    py.legend(numpoints=1, loc='upper left')
    py.xlabel('Magnitude')
    py.xlim(-23, -1)
    py.ylabel('Magnitude Error')
    py.ylim(0.004, 0.1)
    py.savefig('plot_m_me_others%s.png' % tableSuffix)

    #####
    # Plot vector point diagram of positional differences
    #####
    idx = np.where((stars.m_ks2 < -5) & (np.abs(dx) < posLim)
                   & (np.abs(dy) < posLim) & (stars.xe_pass1 < errLim)
                   & (stars.ye_pass1 < errLim))[0]

    py.figure(6)
    py.clf()

    py.plot(dx[idx], dy[idx], 'k.', ms=2)
    py.xlabel('X KS2 - One Pass')
    py.ylabel('Y KS2 - One Pass')
    py.axis([-posLim, posLim, -posLim, posLim])
    py.savefig('plot_dxdy_vpd%s.png' % tableSuffix)

    #####
    # Plot vector field of positional differences
    #####
    py.figure(7)
    py.clf()

    q = py.quiver(stars.x_pass1[idx],
                  stars.y_pass1[idx],
                  dx[idx],
                  dy[idx],
                  scale=quiverScale)
    py.quiverkey(q, 0.5, 0.95, 0.05, '0.05 pix', color='red')
    py.title('KS2 - One Pass')
    py.xlabel('X (pixels)')
    py.xlabel('Y (pixels)')
    py.savefig('plot_dxdy_quiver%s.png' % tableSuffix)

    #####
    # Print out some statistics
    #####
    idx = np.where(stars.m_ks2 < -5)[0]
    print 'Mean dx = %7.3f +/- %7.3f (pix)' % \
        (statsIter.mean(dx[idx], lsigma=4, hsigma=4, iter=5),
         statsIter.std(dx[idx], lsigma=4, hsigma=4, iter=5))
    print 'Mean dy = %7.3f +/- %7.3f (pix)' % \
        (statsIter.mean(dy[idx], lsigma=4, hsigma=4, iter=5),
         statsIter.std(dy[idx], lsigma=4, hsigma=4, iter=5))
    print 'Mean dxerr = %7.3f +/- %7.3f (pix)' % \
        (statsIter.mean(dxerr[idx], lsigma=4, hsigma=4, iter=5),
         statsIter.std(dxerr[idx], lsigma=4, hsigma=4, iter=5))
    print 'Mean dyerr = %7.3f +/- %7.3f (pix)' % \
        (statsIter.mean(dyerr[idx], lsigma=4, hsigma=4, iter=5),
         statsIter.std(dyerr[idx], lsigma=4, hsigma=4, iter=5))
        pylab.ylabel("Y")
        pylab.xlim(x0 - 100, x1 + 100)
        pylab.ylim(x0 - 100, x1 + 100)
        ax2.yaxis.set_minor_locator(MultipleLocator(xtmin_vec))
        ax2.yaxis.set_major_locator(MultipleLocator(xtmax_vec))
        ax2.xaxis.set_minor_locator(MultipleLocator(xtmin_vec))
        ax2.xaxis.set_major_locator(MultipleLocator(xtmax_vec))
        pylab.title(
            filtname
            + " XY Residuals in UDF ("
            + pref
            + ").  RMS(X)={:1.2f}".format(xrms)
            + "  RMS(Y)={:1.2f}".format(yrms)
            + "  # objects="
            + str(len(xs)),
            size="small",
        )
        qk = pylab.quiverkey(
            Q,
            0.915,
            0.937,
            0.05,
            "0.05 pix",
            labelpos="N",
            coordinates="axes",
            fontproperties={"weight": "bold"},
            color="black",
        )
        pylab.show()
        pylab.savefig(pref + "_tweakreg_xyvector.pdf")
예제 #52
0
파일: op_plot.py 프로젝트: martalmeida/OOFe
 def add_currkey(handle):
   pos=Data['kcurrpos'][ifig]
   if pos:
     pl.quiverkey(handle, pos[0], pos[1], lcurr, '%s m/s' % str(lcurr),labelpos='S',
                                               coordinates='axes')
def plot_vpd_across_field(nside=4, interact=False):
    """
    Plot the VPD at different field positions so we can see if there are
    systematic discrepancies due to residual distortions.
    """
    # Read in matched and aligned star lists from the *.ref5 analysis.
    # Recall these data sets are in the F814W reference frame with a 50 mas plate scale.
    t2005 = starlists.read_matchup(workDir + '02.PMA/MATCHUP.XYMEEE.F814W.ref5')
    t2010 = starlists.read_matchup(workDir + '02.PMA/MATCHUP.XYMEEE.F125W.ref5')

    scale = 50.0 # mas per pixel
    

    # Trim down to only those stars that are detected in both epochs.
    # Also make cuts on astrometric/photometric errors, etc.
    # We only want the well measured stars in this analysis.
    perrLim814 = 1.0 / scale
    perrLim125 = 4.0 / scale
    merrLim814 = 0.05
    merrLim125 = 0.1
    
    cond = ((t2005.m != 0) & (t2010.m != 0) &
            (t2005.xe < perrLim814) & (t2005.ye < perrLim814) &
            (t2010.xe < perrLim125) & (t2010.ye < perrLim125) &
            (t2005.me < merrLim814) & (t2010.me < merrLim125))

    t2005 = t2005.where(cond)
    t2010 = t2010.where(cond)

    # Calculate proper motions
    dt = years['2010_F125W'] - years['2005_F814W']
    dx = t2010.x - t2005.x
    dy = t2010.y - t2005.y
    pmx = dx * scale / dt
    pmy = dy * scale / dt
    pm = np.hypot(pmx, pmy)

    t2005.add_column('pmx', pmx)
    t2005.add_column('pmy', pmy)
    t2005.add_column('pm', pm)


    # Divide up the region into N x N boxes and plot up the VPD for each.
    xlo = math.floor(t2005.x.min())
    xhi = math.ceil(t2005.x.max())
    ylo = math.floor(t2005.y.min())
    yhi = math.ceil(t2005.y.max())
    xboxsize = round((xhi - xlo) / nside)
    yboxsize = round((yhi - ylo) / nside)

    # Setup colors
    jet = py.get_cmap('jet')
    cNorm = colors.Normalize(vmin=0, vmax=nside**2)
    colorMap = py.cm.ScalarMappable(norm=cNorm, cmap=jet)

    # Save the average proper motions in each box
    pmx = np.zeros((nside, nside), dtype=float)
    pmy = np.zeros((nside, nside), dtype=float)
    pmxe = np.zeros((nside, nside), dtype=float)
    pmye = np.zeros((nside, nside), dtype=float)
    xcen = np.zeros((nside, nside), dtype=float)
    ycen = np.zeros((nside, nside), dtype=float)

    pmCut = 1.0

    # Calculate the global mean proper motion
    # Start by trimming down to a 1 mas/yr radius
    idx2 = np.where(pm < pmCut)[0]
    pmx_all = np.median( t2005.pmx[idx2] )
    pmy_all = np.median( t2005.pmy[idx2] )
    
    out = 'All X:{0:5.0f}-{1:5.0f}  Y:{2:5.0f}-{3:5.0f}  '
    out += 'PMX:{4:5.2f} +/- {5:5.2f} PMY:{6:5.2f} +/- {7:5.2f}  '
    out += 'N:{8:5d}'
    print((out.format(xlo, xhi, ylo, yhi, pmx_all, 0.0, pmy_all, 0.0, len(idx2))))

    # Make a global proper motion diagram of star with a proper motion within
    # 1 mas/yr. This is mainly to see systematic flows due to residual distortion.
    pmTot = np.hypot(t2005.pmx, t2005.pmy)
    clust = np.where(pmTot < pmCut)[0]
    py.clf()
    q = py.quiver(t2005.x[clust], t2005.y[clust], t2005.pmx[clust], t2005.pmy[clust],
                  scale=18)
    py.quiverkey(q, 0.5, 0.98, 1, '1 mas/yr', color='red', labelcolor='red')
    py.xlabel('X Position (pixels)')
    py.ylabel('Y Position (pixels)')
    py.xlim(xlo, xhi)
    py.ylim(ylo, yhi)
    out = '{0}/plots/vec_proper_motion_all.png'
    py.savefig(out.format(workDir))
    
    py.clf()
    for xx in range(nside):
        for yy in range(nside):
            xlo_box = xlo + xx * xboxsize
            ylo_box = ylo + yy * yboxsize
            xhi_box = xlo + (1+xx) * xboxsize
            yhi_box = ylo + (1+yy) * yboxsize

            idx = np.where((t2005.x > xlo_box) & (t2005.x <= xhi_box) &
                           (t2005.y > ylo_box) & (t2005.y <= yhi_box))[0]


            if interact:
                color = colorMap.to_rgba(yy + xx * nside)
                lim = 5

                py.plot(t2005.pmx[idx], t2005.pmy[idx], 'k.', ms=2, color=color)
                py.axis([-lim, lim, -lim, lim])

                py.xlabel('X Proper Motion (mas/yr)')
                py.ylabel('Y Proper Motion (mas/yr)')

            # Lets get the mean and std-dev (iterative) for the box.
            # Start by trimming down to a 1 mas/yr circle.
            idx2 = np.where(t2005.pm[idx] < pmCut)[0]
            xmean = np.median( t2005.pmx[idx][idx2] )
            ymean = np.median( t2005.pmy[idx][idx2] )
            xstd = t2005.pmx[idx][idx2].std()
            ystd = t2005.pmy[idx][idx2].std()
            xmean_err = xstd / np.sqrt(len(idx2))
            ymean_err = ystd / np.sqrt(len(idx2))

            xcen[xx, yy] = xlo_box + (xboxsize / 2.0)
            ycen[xx, yy] = ylo_box + (yboxsize / 2.0)
            pmx[xx, yy] = xmean - pmx_all
            pmy[xx, yy] = ymean - pmx_all
            pmxe[xx, yy] = xmean_err
            pmye[xx, yy] = ymean_err

            out = 'Box X:{0:5.0f}-{1:5.0f}  Y:{2:5.0f}-{3:5.0f}  '
            out += 'PMX:{4:5.2f} +/- {5:5.2f} PMY:{6:5.2f} +/- {7:5.2f}  '
            out += 'N:{8:5d}  '

            if interact:
                out += 'Continue?'
                input(out.format(xlo_box, xhi_box, ylo_box, yhi_box,
                                     xmean, xmean_err, ymean, ymean_err, len(idx2)))
            else:
                print((out.format(xlo_box, xhi_box, ylo_box, yhi_box,
                                 xmean, xmean_err, ymean, ymean_err, len(idx2))))


    if interact:
        out = '{0}/plots/vpd_grid_nside{1}.png'
        py.savefig(out.format(workDir, nside))

    py.clf()
    q = py.quiver(xcen, ycen, pmx, pmy)
    py.quiverkey(q, 0.5, 0.98, 0.1, '0.1 mas/yr', color='red', labelcolor='red')
    py.xlabel('X Position (pixels)')
    py.ylabel('Y Position (pixels)')
    py.xlim(xlo, xhi)
    py.ylim(ylo, yhi)
    for xx in range(nside+1):
        py.axvline(xlo + xx * xboxsize, linestyle='--', color='grey')
    for yy in range(nside+1):
        py.axhline(ylo + yy * yboxsize, linestyle='--', color='grey')
    out = '{0}/plots/vec_proper_motion_grid_nside{1}.png'
    py.savefig(out.format(workDir, nside))

    py.clf()
    q = py.quiver(xcen, ycen, pmx/pmxe, pmy/pmye)
    py.quiverkey(q, 0.5, 0.98, 3, '3 sigma', color='red', labelcolor='red')
    py.xlabel('X Position (pixels)')
    py.ylabel('Y Position (pixels)')
    py.xlim(xlo, xhi)
    py.ylim(ylo, yhi)
    for xx in range(nside+1):
        py.axvline(xlo + xx * xboxsize, linestyle='--', color='grey')
    for yy in range(nside+1):
        py.axhline(ylo + yy * yboxsize, linestyle='--', color='grey')
    out = '{0}/plots/vec_proper_motion_grid_sig_nside{1}.png'
    py.savefig(out.format(workDir, nside))
예제 #54
0
파일: op_plot.py 프로젝트: martalmeida/OOFe
 def add_currkey(handle):
   Data,err = opt.get_plconf(plconf,'HSLICES')
   pos=Data['kcurrpos'][ifig]
   if pos:
     pl.quiverkey(handle, pos[0], pos[1], lcurr, '%s m/s' % str(lcurr),labelpos='S',
                                             coordinates='axes')
예제 #55
0
def plot_quiver_one_pass(reread=False):
    """
    Plot a quiver vector plot between F814W in 2005 and F160W in 2010 and 2013.
    This is just to check that we don't hae any gross flows between the two cameras.
    """
    if reread:
        t2005 = starlists.read_matchup('MATCHUP.XYMEEE.F814W.2005.ref5')
        t2010 = starlists.read_matchup('MATCHUP.XYMEEE.F160W.2010.ref5')
        t2013 = starlists.read_matchup('MATCHUP.XYMEEE.F160W.2013.ref5')

        t2005.write('MATCHUP.XYMEEE.F814W.2005.ref5.fits')
        t2010.write('MATCHUP.XYMEEE.F160W.2010.ref5.fits')
        t2013.write('MATCHUP.XYMEEE.F160W.2013.ref5.fits')
    else:
        t2005 = Table.read('MATCHUP.XYMEEE.F814W.2005.ref5.fits')
        t2010 = Table.read('MATCHUP.XYMEEE.F160W.2010.ref5.fits')
        t2013 = Table.read('MATCHUP.XYMEEE.F160W.2013.ref5.fits')

    good = np.where((t2005['m'] < -8) & (t2010['m'] < -8) & (t2013['m'] < -8) &
                    (t2005['xe'] < 0.05) & (t2010['xe'] < 0.05) & (t2013['xe'] < 0.05) & 
                    (t2005['ye'] < 0.05) & (t2010['ye'] < 0.05) & (t2013['ye'] < 0.05) & 
                    (t2005['me'] < 0.05) & (t2010['me'] < 0.05) & (t2013['me'] < 0.05))[0]

    g2005 = t2005[good]
    g2010 = t2010[good]
    g2013 = t2013[good]

    dx_05_10 = (g2010['x'] - g2005['x']) * ast.scale['WFC'] * 1e3
    dy_05_10 = (g2010['y'] - g2005['y']) * ast.scale['WFC'] * 1e3

    dx_05_13 = (g2013['x'] - g2005['x']) * ast.scale['WFC'] * 1e3
    dy_05_13 = (g2013['y'] - g2005['y']) * ast.scale['WFC'] * 1e3

    dx_10_13 = (g2013['x'] - g2010['x']) * ast.scale['WFC'] * 1e3
    dy_10_13 = (g2013['y'] - g2010['y']) * ast.scale['WFC'] * 1e3

    small = np.where((np.abs(dx_05_10) < 20) & (np.abs(dy_05_10) < 20) & 
                     (np.abs(dx_05_13) < 20) & (np.abs(dy_05_13) < 20) & 
                     (np.abs(dx_10_13) < 20) & (np.abs(dy_10_13) < 20))[0]

    print(len(g2005), len(small), len(dx_05_10))
    g2005 = g2005[small]
    g2010 = g2010[small]
    g2013 = g2013[small]
    dx_05_10 = dx_05_10[small]
    dx_05_13 = dx_05_13[small]
    dx_10_13 = dx_10_13[small]
    dy_05_10 = dy_05_10[small]
    dy_05_13 = dy_05_13[small]
    dy_10_13 = dy_10_13[small]
    print(len(g2005), len(small), len(dx_05_10))
    
    py.clf()
    q = py.quiver(g2005['x'], g2005['y'], dx_05_10, dy_05_10, scale=2e2)
    py.quiverkey(q, 0.95, 0.95, 5, '5 mas', color='red', labelcolor='red')
    py.title('2010 - 2005')
    py.savefig('vec_diff_ref5_05_10.png')

    py.clf()
    q = py.quiver(g2005['x'], g2005['y'], dx_05_13, dy_05_13, scale=2e2)
    py.quiverkey(q, 0.95, 0.95, 5, '5 mas', color='red', labelcolor='red')
    py.title('2013 - 2005')
    py.savefig('vec_diff_ref5_05_13.png')

    py.clf()
    q = py.quiver(g2005['x'], g2005['y'], dx_10_13, dy_10_13, scale=1e2)
    py.quiverkey(q, 0.95, 0.95, 5, '5 mas', color='red', labelcolor='red')
    py.title('2013 - 2010')
    py.savefig('vec_diff_ref5_10_13.png')

    py.clf()
    py.plot(dx_05_10, dy_05_10, 'k.', ms=2)
    lim = 10
    py.axis([-lim, lim, -lim, lim])
    py.xlabel('X Proper Motion (mas)')
    py.ylabel('Y Proper Motion (mas)')
    py.title('2010 - 2005')
    py.savefig('pm_diff_ref5_05_10.png')

    py.clf()
    py.plot(dx_05_13, dy_05_13, 'k.', ms=2)
    py.axis([-lim, lim, -lim, lim])
    py.xlabel('X Proper Motion (mas)')
    py.ylabel('Y Proper Motion (mas)')
    py.title('2013 - 2005')
    py.savefig('pm_diff_ref5_05_13.png')

    py.clf()
    py.plot(dx_10_13, dy_10_13, 'k.', ms=2)
    py.axis([-lim, lim, -lim, lim])
    py.xlabel('X Proper Motion (mas)')
    py.ylabel('Y Proper Motion (mas)')
    py.title('2013 - 2010')
    py.savefig('pm_diff_ref5_10_13.png')

    print('2010 - 2005')
    print('   dx = {dx:6.2f} +/- {dxe:6.2f} mas'.format(dx=dx_05_10.mean(), dxe=dx_05_10.std()))
    print('   dy = {dy:6.2f} +/- {dye:6.2f} mas'.format(dy=dy_05_10.mean(), dye=dy_05_10.std()))

    print('2013 - 2005')
    print('   dx = {dx:6.2f} +/- {dxe:6.2f} mas'.format(dx=dx_05_13.mean(), dxe=dx_05_13.std()))
    print('   dy = {dy:6.2f} +/- {dye:6.2f} mas'.format(dy=dy_05_13.mean(), dye=dy_05_13.std()))

    print('2013 - 2010')
    print('   dx = {dx:6.2f} +/- {dxe:6.2f} mas'.format(dx=dx_10_13.mean(), dxe=dx_10_13.std()))
    print('   dy = {dy:6.2f} +/- {dye:6.2f} mas'.format(dy=dy_10_13.mean(), dye=dy_10_13.std()))
예제 #56
0
def plot_comparison(tableSuffix, posLim=0.15, magLimits=[-13,-1], errLim=0.04,
                    quiverScale=2):
    """
    Load up starlists produced by matchup_ks2_pass1() and plot some parameters
    of interest. Just pass in the filter suffix (e.g. "_f0"). Plots include:

    delta-x vs. m
    delta-y vs. m
    delta-m vs. m
    uncertainties vs. m for both lists
    me vs. m for stars in ks2 vs. stars not in ks2
    """
    stars = atpy.Table('stars_ks2_pass1%s.fits' % tableSuffix)
    other = atpy.Table('stars_pass1_only%s.fits' % tableSuffix)

    print '%6d stars in ks2' % len(stars)
    print '%6d stars not found in ks2' % len(other)

    #####
    # Plot delta-x vs. m
    #####
    dx = stars.x_ks2 - stars.x_pass1
    dxe = stars.xe_ks2

    #py.close('all')

    py.figure(1)
    py.clf()
    ax1 = py.subplot(2, 1, 1)
    py.plot(stars.m_pass1, dx, 'k.', ms=2)
    py.ylabel('dx (pix)')
    py.ylim(-posLim, posLim)
    py.axhline(y=0, color='r', linewidth=2)
    py.title('KS2 - One Pass')

    ax2 = py.subplot(2, 1, 2, sharex=ax1)
    py.plot(stars.m_pass1, dx/dxe, 'k.', ms=2)
    py.ylabel('dx/dxe (sigma)')
    py.ylim(-3, 3)
    py.axhline(y=0, color='r', linewidth=2)
    py.xlabel('Magnitude')
    py.xlim(magLimits[0], magLimits[1])
    py.savefig('plot_dx_m%s.png' % tableSuffix)

    
    #####
    # Plot delta-y vs. m
    #####
    dy = stars.y_ks2 - stars.y_pass1
    dye = stars.ye_ks2

    py.figure(2)
    py.clf()
    ax1 = py.subplot(2, 1, 1)
    py.plot(stars.m_pass1, dy, 'k.', ms=2)
    py.ylabel('dy (pix)')
    py.ylim(-posLim, posLim)
    py.axhline(y=0, color='r', linewidth=2)
    py.title('KS2 - One Pass')

    ax2 = py.subplot(2, 1, 2, sharex=ax1)
    py.plot(stars.m_pass1, dy/dye, 'k.', ms=2)
    py.ylabel('dy/dye (sigma)')
    py.ylim(-3, 3)
    py.axhline(y=0, color='r', linewidth=2)
    py.xlabel('Magnitude')
    py.xlim(magLimits[0], magLimits[1])

    py.savefig('plot_dy_m%s.png' % tableSuffix)
    
    #####
    # Plot delta-m vs. m
    #####
    dm = stars.m_ks2 - stars.m_pass1
    dme = stars.me_ks2

    py.figure(3)
    py.clf()
    ax1 = py.subplot(2, 1, 1)
    py.plot(stars.m_pass1, dm, 'k.', ms=2)
    py.ylabel('dm (mag)')
    py.ylim(-0.1, 0.1)
    py.axhline(y=0, color='r', linewidth=2)
    py.title('KS2 - One Pass')

    ax2 = py.subplot(2, 1, 2, sharex=ax1)
    py.plot(stars.m_pass1, dm/dme, 'k.', ms=2)
    py.ylabel('dm/dme (sigma)')
    py.ylim(-3, 3)
    py.axhline(y=0, color='r', linewidth=2)
    py.xlabel('Magnitude')
    py.xlim(magLimits[0], magLimits[1])

    py.savefig('plot_dm_m%s.png' % tableSuffix)


    #####
    # Plot differences in errors vs. m
    #####
    dxerr = stars.xe_ks2 - stars.xe_pass1
    dyerr = stars.ye_ks2 - stars.ye_pass1
    dmerr = stars.me_ks2 - stars.me_pass1
    
    py.close(4)
    py.figure(4, figsize=(9,12))
    py.clf()
    py.subplots_adjust(left=0.12, bottom=0.07, top=0.95)
    ax1 = py.subplot(3, 1, 1)
    py.plot(stars.m_ks2, dxerr, 'k.', ms=2)
    py.ylabel('xe diff')
    py.ylim(-0.05, 0.05)
    py.axhline(y=0, color='r', linewidth=2)
    py.title('KS2 - One Pass')

    ax2 = py.subplot(3, 1, 2, sharex=ax1)
    py.plot(stars.m_ks2, dyerr, 'k.', ms=2)
    py.ylabel('ye diff')
    py.ylim(-0.05, 0.05)
    py.axhline(y=0, color='r', linewidth=2)

    ax3 = py.subplot(3, 1, 3, sharex=ax1)
    py.plot(stars.m_ks2, dmerr, 'k.', ms=2)
    py.ylabel('me diff')
    py.ylim(-0.05, 0.05)
    py.axhline(y=0, color='r', linewidth=2)

    py.xlabel('Magnitude')
    py.xlim(magLimits[0], magLimits[1])

    py.savefig('plot_compare_errors%s.png' % tableSuffix)
    
    #####
    # Plot stars that are NOT in KS2 vs. those that are.
    #####
    py.figure(5)
    py.clf()

    py.semilogy(stars.m_pass1, stars.me_pass1, 'k.', label='In KS2', ms=2)
    py.semilogy(other.m, other.me, 'r.', label='Not In KS2', ms=3)
    py.legend(numpoints=1, loc='upper left')
    py.xlabel('Magnitude')
    py.xlim(-23, -1)
    py.ylabel('Magnitude Error')
    py.ylim(0.004, 0.1)
    py.savefig('plot_m_me_others%s.png' % tableSuffix)


    #####
    # Plot vector point diagram of positional differences
    #####
    idx = np.where((stars.m_ks2 < -5) & (np.abs(dx) < posLim) & (np.abs(dy) < posLim) &
                   (stars.xe_pass1 < errLim) & (stars.ye_pass1 < errLim))[0]

    py.figure(6)
    py.clf()

    py.plot(dx[idx], dy[idx], 'k.', ms=2)
    py.xlabel('X KS2 - One Pass')
    py.xlabel('Y KS2 - One Pass')
    py.axis([-posLim, posLim, -posLim, posLim])
    py.savefig('plot_dxdy_vpd%s.png' % tableSuffix)


    #####
    # Plot vector field of positional differences
    #####
    py.figure(7)
    py.clf()

    q = py.quiver(stars.x_pass1[idx], stars.y_pass1[idx], dx[idx], dy[idx], scale=quiverScale)
    py.quiverkey(q, 0.5, 0.95, 0.05, '0.05 pix', color='red')
    py.title('KS2 - One Pass')
    py.xlabel('X (pixels)')
    py.xlabel('Y (pixels)')
    py.savefig('plot_dxdy_quiver%s.png' % tableSuffix)

    #####
    # Print out some statistics
    #####
    idx = np.where(stars.m_ks2 < -5)[0]
    print 'Mean dx = %7.3f +/- %7.3f (pix)' % \
        (statsIter.mean(dx[idx], lsigma=4, hsigma=4, iter=5),
         statsIter.std(dx[idx], lsigma=4, hsigma=4, iter=5))
    print 'Mean dy = %7.3f +/- %7.3f (pix)' % \
        (statsIter.mean(dy[idx], lsigma=4, hsigma=4, iter=5),
         statsIter.std(dy[idx], lsigma=4, hsigma=4, iter=5))
    print 'Mean dxerr = %7.3f +/- %7.3f (pix)' % \
        (statsIter.mean(dxerr[idx], lsigma=4, hsigma=4, iter=5),
         statsIter.std(dxerr[idx], lsigma=4, hsigma=4, iter=5))
    print 'Mean dyerr = %7.3f +/- %7.3f (pix)' % \
        (statsIter.mean(dyerr[idx], lsigma=4, hsigma=4, iter=5),
         statsIter.std(dyerr[idx], lsigma=4, hsigma=4, iter=5))
def makeVectorField(f, xmin, xmax, ymin, ymax, step):
    X, Y = meshgrid(arange(xmin, xmax, step), arange(ymin, ymax, step))
    U, V = zip(*map(lambda xx: f(*xx), zip(X, Y)))
    Q = quiver(X, Y, U, V, units='width')
    quiverkey(Q, 0, 0, 4, '', coordinates='figure', labelpos='W')
def plot_vector_diff(undersample):
    """
    Make a vector plot of the differences between the input positions
    and the output positions after running starfinder.
    """
    # Dimensions of new grid
    npsf_side = get_npsf_side(undersample)
    suffix = '%d_%d' % (npsf_side, npsf_side)

    s = starset.StarSet('grid_' + suffix + '/align_' + suffix)

    cnt = s.getArray('velCnt')
    mag = s.getArray('mag')
    idx = np.where((cnt == 2) & (mag < 15))[0]
    print 'Using {0} stars out of {1}'.format(len(idx), len(cnt))

    newStars = [s.stars[ii] for ii in idx]
    s.stars = newStars

    x0 = s.getArrayFromEpoch(0, 'xorig')
    y0 = s.getArrayFromEpoch(0, 'yorig')
    x1 = s.getArrayFromEpoch(1, 'xorig')
    y1 = s.getArrayFromEpoch(1, 'yorig')

    dx = x1 - x0
    dy = y1 - y0
    dr = np.hypot(dx, dy)

    # Boundaries
    t = atpy.Table('svpar_' + suffix + '.txt', type='ascii')
    lx = t.col1
    ux = t.col2
    ly = t.col3
    uy = t.col4
    xedges = np.unique(np.append(lx, ux))
    yedges = np.unique(np.append(ly, uy))

    py.clf()
    q = py.quiver(x0, y0, dx, dy, scale=0.2)
    py.xlim(0, 1200)
    py.ylim(0, 1200)
    py.quiverkey(q,
                 0.5,
                 0.97,
                 0.02,
                 '0.02 pixel (0.2 mas)',
                 color='red',
                 coordinates='axes')

    for xx in xedges:
        py.axvline(xx, linestyle='--')
    for yy in yedges:
        py.axhline(yy, linestyle='--')

    py.savefig('plots/vec_diff_' + suffix + '.png')

    xmean = statsIter.mean(dx, hsigma=5, lsigma=5, iter=5)
    ymean = statsIter.mean(dy, hsigma=5, lsigma=5, iter=5)
    rmean = statsIter.mean(dr, hsigma=5, lsigma=5, iter=5)
    xstd = statsIter.std(dx, hsigma=5, lsigma=5, iter=5)
    ystd = statsIter.std(dy, hsigma=5, lsigma=5, iter=5)
    rstd = statsIter.std(dr, hsigma=5, lsigma=5, iter=5)
    print('Mean Delta-X: {0:9.5f} +/- {1:9.5f} pixels'.format(xmean, xstd))
    print('Mean Delta-Y: {0:9.5f} +/- {1:9.5f} pixels'.format(ymean, ystd))
    print('Mean Delta-R: {0:9.5f} +/- {1:9.5f} pixels'.format(rmean, rstd))
    f_name = 'diff_stats_' + suffix + '.txt'
    f_stat = open(f_name, 'w')
    hdr = '#{0:>5s} {1:>10s} {2:>10s} {3:>10s} {4:>10s} {5:>10s} {6:>10s}\n'
    fmt = '{0:6d} {1:10.5f} {2:10.5f} {3:10.5f} {4:10.5f} {5:10.5f} {6:10.5f}\n'
    f_stat.write(
        hdr.format('Npsf', 'Xmean', 'Ymean', 'Rmean', 'Xstd', 'Ystd', 'Rstd'))
    f_stat.write(fmt.format(npsf_side, xmean, ymean, rmean, xstd, ystd, rstd))
    f_stat.close()

    return f_name