Esempio n. 1
0
def hillshade(data,scale=10.0,azdeg=165.0,altdeg=45.0):
  ''' 
    This code thanks to Ran Novitsky Nof
  http://rnovitsky.blogspot.co.uk/2010/04/using-hillshade-image-as-intensity.html
  Repeated here to make my cyclopean uk_map code prettier.

  convert data to hillshade based on matplotlib.colors.LightSource class.
    input:
         data - a 2-d array of data
         scale - scaling value of the data. higher number = lower gradient
         azdeg - where the light comes from: 0 south ; 90 east ; 180 north ;
                      270 west
         altdeg - where the light comes from: 0 horison ; 90 zenith
    output: a 2-d array of normalized hilshade
  '''
  
  from pylab import pi, gradient, arctan, hypot, arctan2, sin, cos
  # convert alt, az to radians
  az = azdeg*pi/180.0
  alt = altdeg*pi/180.0
  # gradient in x and y directions
  dx, dy = gradient(data/float(scale))
  slope = 0.5*pi - arctan(hypot(dx, dy))
  aspect = arctan2(dx, dy)
  intensity = sin(alt)*sin(slope) + cos(alt)*cos(slope)*cos(-az - aspect - 0.5*pi)
  intensity = (intensity - intensity.min())/(intensity.max() - intensity.min())
  return intensity
Esempio n. 2
0
def hillshade(data, scale=10.0, azdeg=165.0, altdeg=45.0):
    '''
    Convert data to hillshade based on matplotlib.colors.LightSource class.

    Args:
        data - a 2-d array of data
        scale - scaling value of the data. higher number = lower gradient
        azdeg - where the light comes from: 0 south ; 90 east ; 180 north ;
                        270 west
        altdeg - where the light comes from: 0 horison ; 90 zenith

    Returns:
        a 2-d array of normalized hilshade
    '''
    # convert alt, az to radians
    az = azdeg*pi/180.0
    alt = altdeg*pi/180.0
    # gradient in x and y directions
    dx, dy = gradient(data/float(scale))
    slope = 0.5*pi - arctan(hypot(dx, dy))
    aspect = arctan2(dx, dy)
    az = -az - aspect - 0.5*pi
    intensity = sin(alt)*sin(slope) + cos(alt)*cos(slope)*cos(az)
    mi, ma = intensity.min(), intensity.max()
    intensity = (intensity - mi)/(ma - mi)
    return intensity
Esempio n. 3
0
def compareVelocity(rootDir='./', align = 'align/align_d_rms1000t',
                    poly='polyfit_d/fit', points='points_d/'):
    """
    Compare velocities from the 2D and 3D polynomial fits.

    rootDir -- An align root directory such as '06_14_02/' (def='./')
    align -- Align root name (def = 'align/align_all1000_t')
    poly -- Polyfit root name (def = 'polyfit/fit')
    points -- Points directory (def = 'points/')
    """
    
    s = starset.StarSet(rootDir + align)
    s.loadPolyfit(rootDir + poly, accel=0, arcsec=1)
    s.loadPolyfit(rootDir + poly, accel=1, arcsec=1)

    names = s.getArray('name')
    x = s.getArray('x')
    y = s.getArray('y')
    r = hypot(x, y)

    vx_vel = s.getArray('fitXv.v')
    vy_vel = s.getArray('fitYv.v')
    vxe_vel = s.getArray('fitXv.verr')
    vye_vel = s.getArray('fitYv.verr')

    vx_acc = s.getArray('fitXa.v')
    vy_acc = s.getArray('fitYa.v')
    vxe_acc = s.getArray('fitXa.verr')
    vye_acc = s.getArray('fitYa.verr')
    
    # Calculate the residuals
    diffx = vx_vel - vx_acc
    diffxErr = np.sqrt(vxe_vel**2 + vxe_acc**2)
    
    diffy = vy_vel - vy_acc
    diffyErr = np.sqrt(vye_vel**2 + vye_acc**2)
    
    diff = py.hypot(diffx, diffy)
    diffErr = np.sqrt((diffx*diffxErr)**2 + (diffy*diffyErr)**2) / diff

    yngNames = young.youngStarNames()
    
    idx = (np.where((r > 0.8) & ((diff/diffErr) > 2.0)))[0]

    print '** Stars with large velocity discrepencies: **'
    print '%15s  %5s  %5s  %5s  %3s' % ('Name', 'Sigma', 'X', 'Y', 'YNG?')
    for i in idx:
        try:
            foo = yngNames.index(names[i])
            yngString = 'yng'
        except ValueError, e:
            yngString = ''
            
        print '%15s  %5.1f  %5.2f  %5.2f  %3s' % \
              (names[i], diff[i]/diffErr[i], x[i], y[i], yngString)
    def exportTrajectoriesFigToPNG(self, filename):
        # values = linspace(0.3, 0.9, 5)  # position of X0 between X_f0 and X_f1
        # vcolors = p.cm.autumn_r(linspace(0.3, 1., len(values)))  # colors for each trajectory

        f2 = p.figure()
        # -------------------------------------------------------
        # plot trajectories
        #for v, col in zip(values, vcolors):
        X0 = self.X_f1  # starting point
        X = odeint(self.dX_dt, self.initialCondition,
                   self.time)  # we don't need infodict here
        p.plot(X[:, 0],
               X[:, 1],
               lw=3.5,
               label='X0=(%.f, %.f)' %
               (self.initialCondition[0], self.initialCondition[1]))
        p.plot(X0[0], X0[1], 'b.')
        p.plot(self.X_f1[0], self.X_f1[1], 'r.')

        # -------------------------------------------------------
        # define a grid and compute direction at each point
        ymax = p.ylim(ymin=0)[1]  # get axis limits
        xmax = p.xlim(xmin=0)[1]
        nb_points = 30

        x = np.linspace(0, xmax, nb_points)
        y = np.linspace(0, ymax, nb_points)

        X1, Y1 = p.meshgrid(x, y)  # create a grid
        DX1, DY1 = self.dX_dt([X1, Y1])  # compute growth rate on the gridt
        M = (p.hypot(DX1, DY1))  # Norm of the growth rate
        M[M == 0] = 1.  # Avoid zero division errors
        DX1 /= M  # Normalize each arrows
        DY1 /= M

        p.title('Trajectories and direction fields')
        p.quiver(X1, Y1, DX1, DY1, M, pivot='mid')
        p.xlabel('Number of rabbits')
        p.ylabel('Number of foxes')
        p.legend()
        p.grid()
        p.xlim(0, xmax)
        p.ylim(0, ymax)
        f2.savefig(filename)
Esempio n. 5
0
File: fh-n.py Progetto: aivuk/var
def intPlot(v0, w0, i):
    pl.figure()
    x0 = np.array([v0, w0])

    ps = integrate(diff, x0, 0, 1000, 0.1, i)

    pl.plot(ps[:,0], ps[:,1], 'm', linewidth=3)

    x = pl.linspace(-2.5, 2.5, 30)
    y = pl.linspace(-2.5, 2.5, 30)

    x1,y1 = pl.meshgrid(x,y)
    dx1, dy1 = diff(0, [x1,y1], i)
    m = (pl.hypot(dx1, dy1))
    m[m == 0] = 1.
    dx1 /= m
    dy1 /= m

    v0 = x - (x**3)/3.0 + i
    w0 = (x + 0.7)/0.8

    # Desenha grade e vetores de velocidade
    pl.grid()
    pl.quiver(x1, y1, dx1, dy1, m, pivot='mid', cmap=pl.cm.jet)
    pl.rcParams['figure.figsize'] = 13,9

    bd = 0.8
    pl.ylim(ymax=max(ps[:,1]) + bd, ymin=min(ps[:,1]) - bd)
    pl.xlim(xmax=max(ps[:,0]) + bd, xmin=min(ps[:,0]) - bd)

    pl.colorbar()

    pl.plot(x, w0, 'g--', linewidth=3)
    pl.plot(x, v0, 'r--', linewidth=3)

    pl.ylabel("W")
    pl.xlabel("V")

    pl.savefig('/usr/share/nginx/www/neuron/graph.png')
Esempio n. 6
0
    def exportTrajectoriesFigToPNG(self, filename: str):
        f2 = p.figure()

        X0 = self.X_f1
        X = odeint(self.dX_dt, self.initialCondition, self.time)
        p.plot(X[:, 0],
               X[:, 1],
               lw=3.5,
               label='X0=(%.f, %.f)' %
               (self.initialCondition[0], self.initialCondition[1]))
        p.plot(X0[0], X0[1], 'b.')
        p.plot(self.X_f1[0], self.X_f1[1], 'r.')

        ymax = p.ylim(ymin=0)[1]
        xmax = p.xlim(xmin=0)[1]
        nb_points = 30

        x = np.linspace(0, xmax, nb_points)
        y = np.linspace(0, ymax, nb_points)

        X1, Y1 = p.meshgrid(x, y)
        DX1, DY1 = self.dX_dt([X1, Y1])
        M = (p.hypot(DX1, DY1))
        M[M == 0] = 1.
        DX1 /= M
        DY1 /= M

        p.title('Trajectories and direction fields')
        p.quiver(X1, Y1, DX1, DY1, M, pivot='mid')
        p.xlabel('Number of rabbits')
        p.ylabel('Number of foxes')
        p.legend()
        p.grid()
        p.xlim(0, xmax)
        p.ylim(0, ymax)
        f2.savefig(filename)
Esempio n. 7
0
def plotcomp(compdict, showplot=True, wantdict=False, symb=',',
             include0amp=False, include0bl=False, blunit='', bl0flux=0.0):

    """
    Given a dict including
    
    {'clist': component list,
     'objname': objname,
     'epoch': epoch,
     'shape': component shape dict, including direction.
     'freqs (GHz)': pl.array of frequencies,
     'antennalist': An array configuration file as used by simdata,
     'savedfig': False or, if specified, the filename to save the plot to,
     'standard': setjy fluxstandard type},

    and symb: One of matplotlib's codes for plot symbols: .:,o^v<>s+xDd234hH|_
          default: ',':  The smallest points I could find,

    make a plot of visibility amplitude vs. baseline length for clist at epoch.

    If antennalist is not found as is, it will look for antennalist in
    os.getenv('CASAPATH').split(' ')[0] + '/data/alma/simmos/'.
    
    showplot: Whether or not to show the plot on screen.

    If wantdict is True, it returns a dictionary with the amplitudes and
    baselines on success.  Otherwise, it returns True or False as its estimated
    success value.

    include0amp: Force the lower limit of the amplitude axis to 0.
    include0bl: Force the lower limit of the baseline length axis to 0.
    blunit: unit of the baseline length (='' used the unit in the data or klambda)
    bl0flux: Zero baseline flux
    """
    def failval():
        """
        Returns an appropriate failure value.
        Note that mydict.update(plotcomp(wantdict=True, ...)) would give a
        confusing error message if plotcomp returned False.
        """
        retval = False
        if wantdict:
            retval = {}
        return retval
    retval = failval()  # Default
    try:
        clist = compdict['clist']
        objname = compdict['objname']
        epoch = compdict['epoch']
        epstr = mepoch_to_str(epoch)
        antennalist = compdict['antennalist']

        # Read the configuration info.
        if not antennalist:
            print "compdict['antennalist'] must be set!"
            print "Try something in", os.getenv("CASAPATH").split(' ')[0] + "/data/alma/simmos/"
            return failval()
        # Try repodir if raw antennalist doesn't work.
        if not os.path.exists(antennalist):
            repodir = os.getenv("CASAPATH").split(' ')[0] + "/data/alma/simmos/"
            antennalist = repodir + antennalist

        su = simutil("")
        stnx, stny, stnz, diam, padnames, telescopename, obsmeas = su.readantenna(antennalist)
        #print "telescopename:", telescopename

        # Check that the source is up.
        myme = metool()
        posobs = myme.observatory(telescopename)
        #print "posobs:", posobs
        myme.doframe(epoch)
        myme.doframe(posobs)
        azel = myme.measure(compdict['shape']['direction'], 'azel')
        azeldegs = tuple([qa.convert(azel[m], 'deg')['value'] for m in ('m0', 'm1')])
        casalog.post("(az, el): (%.2f, %.2f) degrees" % azeldegs)
        # riseset blabs to the logger, so introduce it now.
        casalog.post('Rise and set times of ' + objname + " from " + telescopename + ':')
        approx = ''
        if 'JPL' in compdict.get('standard', 'JPL'):
            # The object is in the Solar System or not known to be extragalactic.
            approx = "APPROXIMATE.  The times do not account for the apparent motion of "\
                     + objname + "."
            casalog.post("  (" + approx + ")")
        riset = myme.riseset(compdict['shape']['direction'])
        msg = ''
        if riset['rise'] == 'above':
            msg = objname + " is circumpolar"
        elif riset['rise'] == 'below':
            msg = objname + ' is not visible from ' + telescopename
        if msg:
            if approx:
                msg += ' around ' + mepoch_to_str(epoch)
            casalog.post(msg)
        else:
            for t in riset:
                riset[t]['str'] = mepoch_to_str(riset[t]['utc'])
            casalog.post(objname + " rises at %s and sets at %s." % (riset['rise']['str'],
                                                                     riset['set']['str']))
            tmeridian=(riset['rise']['utc']['m0']['value']+riset['set']['utc']['m0']['value'])/2.
            casalog.post(objname + ': meridian passage at ' + qa.time(str(tmeridian)+'d')[0])

        if approx:
            riset['NOTE'] = approx
        if not azel['m1']['value'] > 0.0:
            casalog.post(objname + " is not visible from " + telescopename + " at " + epstr,
                         'SEVERE')
            if wantdict:
                return riset
            else:
                return False

        # Start a temp MS.
        workingdir = os.path.abspath(os.path.dirname(clist.rstrip('/')))
        tempms = tempfile.mkdtemp(prefix=objname, dir=workingdir)

        mysm = smtool()
        mysm.open(tempms)

        su.setcfg(mysm, telescopename, stnx, stny, stnz, diam,
                  padnames, posobs)

        #print "cfg set"

        # Only 1 polarization is wanted for now.
        stokes, feeds = su.polsettings(telescopename, 'RR')
        
        casalog.post("stokes, feeds: %s, %s" % (stokes, feeds))
        fband = su.bandname(compdict['freqs (GHz)'][0])
        chaninc = 1.0
        nchan = len(compdict['freqs (GHz)'])
        if nchan > 1:
            chaninc = (compdict['freqs (GHz)'][-1] - compdict['freqs (GHz)'][0]) / (nchan - 1)
        mysm.setspwindow(spwname=fband,
                         freq=str(compdict['freqs (GHz)'][0]) + 'GHz', 
                         deltafreq=str(chaninc) + 'GHz', 
                         freqresolution='1Hz', 
                         nchannels=nchan, refcode="LSRK",
                         stokes=stokes)
        mysm.setfeed(mode=feeds, pol=[''])
        mysm.setlimits(shadowlimit=0.01, elevationlimit='10deg')
        mysm.setauto(0.0)
        mysm.setfield(sourcename=objname,
                      sourcedirection=compdict['shape']['direction'],
                      calcode="OBJ", distance='0m')
        mysm.settimes(integrationtime="1s", usehourangle=False,
                      referencetime=epoch)
        
        # this only creates blank uv entries
        mysm.observe(sourcename=objname, spwname=fband,
                   starttime="-0.5s", stoptime="0.5s", project=objname)

        mysm.setdata(fieldid=[0])
        mysm.setvp()
        casalog.post("done setting up simulation parameters")

        mysm.predict(complist=clist)        # do actual calculation of visibilities:

        mysm.close()
        casalog.post("Simulation finished.")

        mytb = tbtool()
        mytb.open(tempms)
        data = mytb.getcol('DATA')[0]       # Again, only 1 polarization for now. 
        data = abs(data)
        baselines = mytb.getcol('UVW')[:2,:]  # Drop w.
        datablunit = mytb.getcolkeywords('UVW')['QuantumUnits']
        mytb.close()
        #print "Got the data and baselines"
        shutil.rmtree(tempms)

        if datablunit[1] != datablunit[0]:
            casalog.post('The baseline units are mismatched!: %s' % datablunit,
                         'SEVERE')
            return failval()
        datablunit = datablunit[0]
        # uv dist unit in klambda or m
        if datablunit == 'm' and blunit=='klambda':
            kl = qa.constants('C')['value']/(compdict['freqs (GHz)'][0]*1e6)
            blunit = 'k$\lambda$'
        else:
            blunit = datablunit
            kl = 1.0
        pl.ioff()
        #baselines = pl.hypot(baselines[0]/kl, baselines[1]/kl)
        baselines = pl.hypot(baselines[0], baselines[1])

        #if not showplot:
        #    casalog.post('Sorry, not showing the plot is not yet implemented',
        #                 'WARN')

        if showplot: 
          pl.ion()
        pl.clf()
        pl.ioff() 
        nfreqs = len(compdict['freqs (GHz)'])
        for freqnum in xrange(nfreqs):
            freq = compdict['freqs (GHz)'][freqnum]
            casalog.post("Plotting " + str(freq) + " GHz.")
            pl.plot(baselines/kl, data[freqnum], symb, label="%.3g GHz" % freq)
            #pl.plot(baselines, data[freqnum], symb, label="%.3g GHz" % freq)
        pl.xlabel("Baseline length (" + blunit + ")")
        pl.ylabel("Visibility amplitude (Jy)")
        if include0amp:
            pl.ylim(ymin=0.0)
        if include0bl:
            pl.xlim(xmin=0.0)
        pl.suptitle(objname + " (predicted by %s)" % compdict['standard'], fontsize=14)
        #pl.suptitle(objname + " (predicted)", fontsize=14)

        # Unlike compdict['antennalist'], antennalist might have had repodir
        # prefixed to it.
        pl.title('at ' + epstr + ' for ' + os.path.basename(compdict['antennalist']), fontsize=10)
        titletxt='($%.0f^\circ$ az, $%.0f^\circ$ el)' % azeldegs
        # for comparison of old and new models - omit azeldegs as all in az~0
        if bl0flux > 0.0:
            if len(compdict['freqs (GHz)']) == 1:
                titletxt+='\n bl0 flux:%.3f Jy' % bl0flux
            else:
                titletxt+='\n bl0 flux:%.3f Jy @ %s GHz' % (bl0flux, compdict['freqs (GHz)'][0]) 
        pl.legend(loc='best', title=titletxt)
        #pl.legend(loc='best', title='($%.0f^\circ$ az, $%.0f^\circ$ el)' % azeldegs)
        y_formatter=matplotlib.ticker.ScalarFormatter(useOffset=False)
        pl.axes().yaxis.set_major_formatter(y_formatter) 
        if showplot:
          pl.ion()
          pl.draw()
        if compdict.get('savedfig'):
            pl.savefig(compdict.get('savedfig'))
            casalog.post("Saved plot to " + str(compdict.get('savedfig')))

        if wantdict:
            retval = {'amps': data,
                      'antennalist': antennalist,  # Absolute path, now.
                      'azel': azel,
                      'baselines': baselines,
                      'blunit': blunit,
                      'riseset': riset,
                      'savedfig': compdict.get('savedfig')}
        else:
            retval = True
    except Exception, instance:
        casalog.post(str(instance), 'SEVERE')
        if os.path.isdir(tempms):
            shutil.rmtree(tempms)
Esempio n. 8
0
def nonPhysical(rootDir='./', align='align/align_d_rms_1000_abs_t',
                poly='polyfit_d/fit', points='points_d/', sigma=5,
                plotChiSq=False, plotPrefix=''):
    """
    Print out a list of stars that have non-physical accelerations.

    Return: returns a list of star names that are unphysical 
    """
    # Load GC constants
    cc = objects.Constants()

    # Load up positional information from align. 
    s = starset.StarSet(rootDir + align)
    s.loadPolyfit(rootDir + poly, arcsec=1)
    s.loadPolyfit(rootDir + poly, arcsec=1, accel=1)

    names = s.getArray('name')
    mag = s.getArray('mag')*1.0
    print len(mag)
    print '%7.4f mag' % mag[0]
    # In mas/yr^2
    x = s.getArray('x')
    y = s.getArray('y')


#    pdb.set_trace()
    vx = s.getArray('fitXa.v')
    vy = s.getArray('fitYa.v')
    ax = s.getArray('fitXa.a') * 1000.0
    ay = s.getArray('fitYa.a') * 1000.0
    axe = s.getArray('fitXa.aerr') * 1000.0
    aye = s.getArray('fitYa.aerr') * 1000.0
    r2d = s.getArray('r2d')
    cnt = s.getArray('velCnt')

#    chi2x = s.getArray('fitXa.chi2red')
#    chi2y = s.getArray('fitYa.chi2red')

    chi2x = s.getArray('fitXa.chi2')
    chi2y = s.getArray('fitYa.chi2')

    chi2xv = s.getArray('fitXv.chi2')
    chi2yv = s.getArray('fitYv.chi2')
    
    nEpochs = s.getArray('velCnt')
    
    # T0 for each of the acceleration fits
    epoch = s.getArray('fitXa.t0')

    # All epochs
    allEpochs = np.array(s.stars[0].years)
    
    # Lets do radial/tangential
    r = np.sqrt(x**2 + y**2)
    if ('Radial' in poly):
        at = ax
        ar = ay
        ate = axe
        are = aye
    else:
        ar = ((ax*x) + (ay*y)) / r
        at = ((ax*y) - (ay*x)) / r
        are = np.sqrt((axe*x)**2 + (aye*y)**2) / r
        ate = np.sqrt((axe*y)**2 + (aye*x)**2) / r

    # Total acceleration
    atot = py.hypot(ax, ay)
    atoterr = np.sqrt((ax*axe)**2 + (ay*aye)**2) / atot

    # Calculate the acceleration limit set by the projected radius
    # Convert into cm
    r2d = r * cc.dist * cc.cm_in_au
    rarc =np.arange(0.01,10.0,0.01)
    rsim = rarc * cc.dist * cc.cm_in_au
    
    # acc1 in cm/s^2
    a2d = -cc.G * cc.mass * cc.msun / r2d**2
    a2dsim = -cc.G * cc.mass * cc.msun / rsim**2
    # acc1 in km/s/yr
    
    a2d *= cc.sec_in_yr / 1.0e5
    a2d *= 1000.0 / cc.asy_to_kms

    a2dsim *= cc.sec_in_yr / 1.0e5
    a2dsim *= 1000.0 / cc.asy_to_kms

    ##########
    #
    # Non-physical accelerations.
    #
    ##########

    # 1. Look for signficant non-zero tangential accelerations.
    bad1 = (np.where( abs(at/ate) > sigma))[0]
    print 'Found %d stars with tangential accelerations > %4.1f sigma' % \
          (len(bad1), sigma)

    # 2. Look for significant positive radial accelerations
    bad2 = (np.where( ((ar - (sigma*are)) > 0) ))[0]
    print 'Found %d stars with positive radial accelerations > %4.1f sigma' % \
          (len(bad2), sigma)


    # 3. Look for negative radial accelerations that are higher
    # than physically allowed.
    bad3 = (np.where( ar + (sigma*are) < a2d))[0]
    print 'Found %d stars with too large negative radial accelerations' % \
          (len(bad3))

    bad = np.unique( np.concatenate((bad1, bad2, bad3)) )

    # chose only bright stars
    nbad = len(bad)
    bright = (np.where(mag[bad] < 16.0))[0]

    bad = bad[bright]
    
#    bad = bad2
    # Sort
    rdx = r2d[bad].argsort()
    bad = bad[rdx]

    ######### look for physical accelerations
    goodAccel = np.where(ar + sigma*are < 0)[0]

    
    # loop through the bad points and look at the closest stars
    nearestStar = np.zeros(len(x))
    nearestStarBad = np.zeros(len(x))

    # look for the minium distance between all stars according to the fit
    for ii in arange(0,len(x)):
        distances = sqrt((x[ii] - x)**2 + (y[ii] - y)**2)
        srt = distances.argsort()
        distances = distances[srt]
        #nearestStar[ii] = distances[1]

        #loop over the 5 closest sources to see which one is closest
        #print names[ii]
        fitMin = np.zeros(5)
        for rr in arange(1,6):
            #print names[srt[rr]]
            xfit1 = [x[ii],vx[ii],ax[ii]/1000.0]
            xfit2 = [x[srt[rr]],vx[srt[rr]],ax[srt[rr]]/1000.0]
            yfit1 = [y[ii],vy[ii],ay[ii]/1000.0]
            yfit2 = [y[srt[rr]],vy[srt[rr]],ay[srt[rr]]/1000.0]
            fitMin[rr-1] = minDistance(xfit1,yfit1,xfit2,yfit2,epoch[ii],[np.amin(allEpochs),np.amax(allEpochs)])
            #print 'fitMin: %f' % fitMin[rr-1]
##         if np.amin(fitMin) < 0.1:
##             indMin = np.argmin(fitMin)
##             print names[ii] +'  ' +names[srt[indMin+1]]+ ' minDist: %f fitMin: %f' % (distances[1], np.amin(fitMin))
#            pdb.set_trace()
        nearestStar[ii] = np.amin(fitMin)

    # check only the unphysical accelerations
    for jj in bad:
        distances = sqrt((x[jj] - x)**2 + (y[jj] - y)**2)
        srt = distances.argsort()
        distances = distances[srt]
        nearestStarBad[jj] = distances[1]

        fitMin = np.zeros(5)
        for rr in arange(1,6):
            #print names[srt[rr]]
            xfit1 = [x[jj],vx[jj],ax[jj]/1000.0]
            xfit2 = [x[srt[rr]],vx[srt[rr]],ax[srt[rr]]/1000.0]
            yfit1 = [y[jj],vy[jj],ay[jj]/1000.0]
            yfit2 = [y[srt[rr]],vy[srt[rr]],ay[srt[rr]]/1000.0]

##             if names[jj] == 'S1-10':
##                 print names[srt[rr]]
##                 pause = 1
##             else:
##                 pause = 0
##             fitMin[rr-1] = minDistance(xfit1,yfit1,xfit2,yfit2,epoch[jj],[np.amin(allEpochs),np.amax(allEpochs)], pause = pause)
            fitMin[rr-1] = minDistance(xfit1,yfit1,xfit2,yfit2,epoch[jj],[np.amin(allEpochs),np.amax(allEpochs)])
            #print 'fitMin: %f' % fitMin[rr-1]
        if np.amin(fitMin) < 0.1:
            indMin = np.argmin(fitMin)
            print names[jj] +'  ' +names[srt[indMin+1]]+ ' minDist: %f fitMin: %f' % (distances[1], np.amin(fitMin))
#            pdb.set_trace()
        nearestStar[jj] = np.amin(fitMin)


    print '%d faint stars with non-physical accelerations' % (nbad - len(bright))
    print '*** Found %d stars with non-physical accelerations ***' % len(bad)
    
    returnNames = []
    print chi2x
#    print 'Name     Mag     x      y    chi2x     chi2y      ar     are     at    ate     nearest'
    print '|Name     |Mag     |x      |y    |chi2x     |chi2y      |ar     |are     |at    |ate     |nearest|'
    for bb in bad:
        returnNames = np.concatenate([returnNames,[names[bb]]])

#        print '%6s %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f' % (names[bb], mag[bb], x[bb], y[bb],chi2x[bb],chi2y[bb],ar[bb]*cc.asy_to_kms/1000.0,are[bb]*cc.asy_to_kms/1000.0,at[bb]*cc.asy_to_kms/1000.0,ate[bb]*cc.asy_to_kms/1000.0,nearestStar[bb])
        print '|%6s |%7.3f |%7.3f |%7.3f |%7.3f |%7.3f |%7.3f |%7.3f |%7.3f |%7.3f |%7.3f|' % (names[bb], mag[bb], x[bb], y[bb],chi2x[bb],chi2y[bb],ar[bb]*cc.asy_to_kms/1000.0,are[bb]*cc.asy_to_kms/1000.0,at[bb]*cc.asy_to_kms/1000.0,ate[bb]*cc.asy_to_kms/1000.0,nearestStar[bb])

    if plotChiSq:
        # plot some chi-square info
        clf()
        subplot(231)
        # look at the distribution of chi-squares for stars brighter than 16 magnitude and have maximum degree of freedom
        maxEpoch = np.amax(nEpochs)
        dof = maxEpoch - 3
        good = np.where((mag < 16.0) & (nEpochs == maxEpoch))[0]

        # filter out the accelerations that do not have the max number of epochs measured
        print shape(good)
        print shape(bad)
        bad = np.intersect1d(good, bad)
        goodAccel = np.intersect1d(goodAccel, good)
        
        # use mean degree of freedom:
        #dof = np.floor(np.mean(nEpochs)-3)

        print 'Degree of freedom %f' % dof
        maxChi=30
        n, bins, patches1 = hist(chi2x[good], bins = np.arange(0, maxChi, 0.5),normed=1,label='x',alpha=0.6,color='blue')
        n, bins, patches2 = hist(chi2y[good], bins = bins, normed=1, label='y',alpha=0.6,color='green')
        xlabel('Chi-Sq Acc')
        title('All stars')
        chiInd = np.arange(0.01,100,0.01)
        chi2Theory = stats.chi2.pdf(chiInd,dof)
        plot(chiInd, chi2Theory)
    
        legend()
        subplot(232)
        n, bins, patches1 = hist(chi2x[bad], bins = np.arange(0,maxChi,0.5), normed=1,label='x',alpha=0.6)
        n, bins, patches2 = hist(chi2y[bad], bins = bins,normed=1,label='y',alpha=0.6)
        title('Non-physical Accelerations')
        xlabel('Chi-Sq Acc')
        plot(chiInd, chi2Theory)

        legend()

        # chi-sq distribution of physical accelerations
        subplot(233)
        n, bins, patches1 = hist(chi2x[goodAccel], bins = np.arange(0,maxChi,0.5), normed=1,label='x',alpha=0.6)
        n, bins, patches2 = hist(chi2y[goodAccel], bins = bins,normed=1,label='y',alpha=0.6)
        title('Physical Accelerations')
        xlabel('Chi-Sq Acc')
        plot(chiInd, chi2Theory)

        legend()

        #savefig('./chiSq_dist_accel.png')
        
        #clf()
        # plot the velocities
        velDof = dof + 1
        subplot(234)
        n, bins, patches1 = hist(chi2xv[good], bins = np.arange(0, maxChi, 0.5),normed=1,label='x',alpha=0.6,color='blue')
        n, bins, patches2 = hist(chi2yv[good], bins = bins, normed=1, label='y',alpha=0.6,color='green')
        xlabel('Chi-Sq Vel')
        title('All stars')
        chiInd = np.arange(0.01,100,0.01)
        chi2Theory = stats.chi2.pdf(chiInd,velDof)
        plot(chiInd, chi2Theory)
    
        legend()
        subplot(235)
        n, bins, patches1 = hist(chi2xv[bad], bins = np.arange(0,maxChi,0.5), normed=1,label='x',alpha=0.6)
        n, bins, patches2 = hist(chi2yv[bad], bins = bins,normed=1,label='y',alpha=0.6)
        title('Non-physical Accelerations')
        xlabel('Chi-Sq Vel')
        plot(chiInd, chi2Theory)

        legend()

        subplot(236)
        n, bins, patches1 = hist(chi2xv[goodAccel], bins = np.arange(0,maxChi,0.5), normed=1,label='x',alpha=0.6)
        n, bins, patches2 = hist(chi2yv[goodAccel], bins = bins,normed=1,label='y',alpha=0.6)
        title('Physical Accelerations')
        xlabel('Chi-Sq Vel')
        plot(chiInd, chi2Theory)

        legend()

        savefig(plotPrefix+'chiSq_dist_accel_vel.pdf')

        clf()
        subplot(131)
        loglog(chi2xv[good]/(dof+1.0),chi2x[good]/dof,'bo',label='X',alpha=0.6)
        plot(chi2yv[good]/(dof+1.0),chi2y[good]/dof,'go',label='Y',alpha=0.6)
        plot([0.001,100],[0.001,100])
        xlim(0.01,maxChi)
        ylim(0.01,maxChi)
        xlabel('Vel. Fit Reduced Chi-Sq')
        ylabel('Acc. Fit Reduced Chi-Sq')
        title('All Stars')
        legend(loc=2)
        
        subplot(132)
        loglog(chi2xv[bad]/(nEpochs[bad]-2.0),chi2x[bad]/(nEpochs[bad]-3.0),'bo',label='X',alpha=0.6)
        plot(chi2yv[bad]/(nEpochs[bad]-2.0),chi2y[bad]/(nEpochs[bad]-3.0),'go',label='Y',alpha=0.6)
        plot([0.001,100],[0.001,100])
        xlim(0.01,maxChi)
        ylim(0.01,maxChi)
        xlabel('Vel. Fit Reduced Chi-Sq')
        ylabel('Acc. Fit Reduced Chi-Sq')
        title('Non-physical Accelerations')
        legend(loc=2)

        subplot(133)
        loglog(chi2xv[goodAccel]/(nEpochs[goodAccel]-2.0),chi2x[goodAccel]/(nEpochs[goodAccel]-3.0),'bo',label='X',alpha=0.6)
        plot(chi2yv[goodAccel]/(nEpochs[goodAccel]-2.0),chi2y[goodAccel]/(nEpochs[goodAccel]-3.0),'go',label='Y',alpha=0.6)
        plot([0.001,100],[0.001,100])
        xlim(0.01,maxChi)
        ylim(0.01,maxChi)
        xlabel('Vel. Fit Reduced Chi-Sq')
        ylabel('Acc. Fit Reduced Chi-Sq')
        title('Physical Accelerations')
        legend(loc=2)

        savefig(plotPrefix+'chi2_vel_vs_accel.pdf')

        # plot chi-sq as a function of magnitude
        clf()
        subplot(231)
        semilogy(mag[good],chi2x[good]/(nEpochs[good]-3.0),'bo',label='X',alpha=0.6)
        plot(mag[good],chi2y[good]/(nEpochs[good]-3.0),'go',label='Y',alpha=0.6)
        ylim(0.01,maxChi)
        xlabel('K mag')
        ylabel('Accel. Fit Chi-Sq')
        title('All Stars')
        legend(loc=3)

        subplot(232)
        semilogy(mag[bad],chi2x[bad]/(nEpochs[bad]-3.0),'bo',label='X',alpha=0.6)
        plot(mag[bad],chi2y[bad]/(nEpochs[bad]-3.0),'go',label='Y',alpha=0.6)
        ylim(0.01,maxChi)
        xlabel('K mag')
        ylabel('Accel. Fit Chi-Sq')
        title('Non-physical Accelerations')
        legend(loc=3)

        subplot(233)
        semilogy(mag[goodAccel],chi2x[goodAccel]/(nEpochs[goodAccel]-3.0),'bo',label='X',alpha=0.6)
        plot(mag[goodAccel],chi2y[goodAccel]/(nEpochs[goodAccel]-3.0),'go',label='Y',alpha=0.6)
        ylim(0.01,maxChi)
        xlabel('K mag')
        ylabel('Accel. Fit Chi-Sq')
        title('Physical Accelerations')
        legend(loc=3)

        subplot(234)
        semilogy(mag[good],chi2xv[good]/(nEpochs[good]-2.0),'bo',label='X',alpha=0.6)
        plot(mag[good],chi2yv[good]/(nEpochs[good]-2.0),'go',label='Y',alpha=0.6)
        ylim(0.01,maxChi)
        xlabel('K mag')
        ylabel('Vel. Fit Chi-Sq')
        title('All Stars')
        legend(loc=3)

        subplot(235)
        semilogy(mag[bad],chi2xv[bad]/(nEpochs[bad]-2.0),'bo',label='X',alpha=0.6)
        plot(mag[bad],chi2yv[bad]/(nEpochs[bad]-2.0),'go',label='Y',alpha=0.6)
        ylim(0.01,maxChi)
        xlabel('K mag')
        ylabel('Vel. Fit Chi-Sq')
        title('Non-physical Accelerations')
        legend(loc=3)

        subplot(236)
        semilogy(mag[goodAccel],chi2xv[goodAccel]/(nEpochs[goodAccel]-2.0),'bo',label='X',alpha=0.6)
        plot(mag[goodAccel],chi2yv[goodAccel]/(nEpochs[goodAccel]-2.0),'go',label='Y',alpha=0.6)
        ylim(0.01,maxChi)
        xlabel('K mag')
        ylabel('Vel. Fit Chi-Sq')
        title('Physical Acceleration')
        legend(loc=3)

        savefig(plotPrefix+'mag_vs_chi2.pdf')
    else:
        # plot the histogram
        clf()
        subplot(221)
        nAll, allbins, patches = hist(nearestStar,bins=50)
    #nBad, badbins, patches2 = hist(nearestStarBad[bad],bins=allbins)
        nBad, badbins, patches2 = hist(nearestStarBad[bad],bins=10)
        setp(patches2, 'facecolor','r')
        xlabel('Nearest Neighbor (arcsec)')
        ylabel('N Stars')
    
        # do a ks test of the two distributions
        print 'len(allbins) %f' % len(allbins)
        print 'len(badbins) %f' % len(badbins)
        print nAll
        print nBad
        ksTest = stats.ks_2samp(nAll, nBad)
        print ksTest
        
        subplot(222)
        plot(rarc,a2dsim)
        plot([0,10],[0,0],hold=True)
          
        #    plot(r[bad],ar[bad],are[bb],'o')
        py.errorbar(r[bad],ar[bad],are[bad],fmt='o')
        xlim(0,5)
        ylim(2,-2)
        xlabel('Distance from Sgr A* (arcsec)')
        ylabel('Acceleration (km/s/yr)')
    
    
        subplot(223)
        # look at the distribution of chi-squares for stars brighter than 16 magnitude
        good = np.where(mag < 16.0)

        # use mean degree of freedom:
        dof = np.floor(np.mean(nEpochs)-3)

        print 'Mean degree of freedom %f' % dof
    
        n, bins, patches1 = hist(chi2x[good], bins = np.arange(0, 20, 0.1),normed=1,label='x',alpha=0.6,color='blue')
        n, bins, patches2 = hist(chi2y[good], bins = bins, normed=1, label='y',alpha=0.6,color='green')
        xlabel('Reduced Chi^2')
        
        chiInd = np.arange(0.01,100,0.01)
        chi2Theory = stats.chi2.pdf(chiInd,dof)
        plot(chiInd, chi2Theory)
    
        legend()
        subplot(224)
        n, bins, patches1 = hist(chi2x[bad], bins = np.arange(0,20,0.5), normed=1,label='x',alpha=0.6)
        n, bins, patches2 = hist(chi2y[bad], bins = bins,normed=1,label='y',alpha=0.6)
        xlabel('Reduced Chi^2')
        plot(chiInd, chi2Theory)

        legend()
        savefig('./unphysicalAccel_stats.png')
    return returnNames
Esempio n. 9
0
def plotLimits(rootDir='./', align='align/align_d_rms1000_t',
               poly='polyfit_d_points/fit', points='points_d/',
               youngOnly=False, sigma=3):
    """
    Find the 4 sigma radial acceleration limits for each star.
    """
    # Load GC constants
    cc = objects.Constants()

    # Load up positional information from align. 
    s = starset.StarSet(rootDir + align)
    s.loadPolyfit(rootDir + poly, arcsec=1)
    s.loadPolyfit(rootDir + poly, arcsec=1, accel=1)

    names = s.getArray('name')

    # In mas/yr^2
    x = s.getArray('x')
    y = s.getArray('y')
    vx = s.getArray('fitXa.v')
    vy = s.getArray('fitYa.v')
    ax = s.getArray('fitXa.a') * 1000.0
    ay = s.getArray('fitYa.a') * 1000.0
    axe = s.getArray('fitXa.aerr') * 1000.0
    aye = s.getArray('fitYa.aerr') * 1000.0
    r2d = s.getArray('r2d')
    cnt = s.getArray('velCnt')

    if (youngOnly == True):
        yngNames = young.youngStarNames()

        idx = []

        for ii in range(len(names)):
            if (r2d[ii] > 0.8 and
                names[ii] in yngNames and
                cnt[ii] >= 24):
                idx.append(ii)

        names = [names[i] for i in idx]
        x = x[idx]
        y = y[idx]
        vx = vx[idx]
        vy = vy[idx]
        ax = ax[idx]
        ay = ay[idx]
        axe = axe[idx]
        aye = aye[idx]
        r2d = r2d[idx]
        print 'Found %d young stars' % len(names)

    # Lets do radial/tangential
    r = np.sqrt(x**2 + y**2)
    if ('Radial' in poly):
        at = ax
        ar = ay
        ate = axe
        are = aye
    else:
        ar = ((ax*x) + (ay*y)) / r
        at = ((ax*y) - (ay*x)) / r
        are = np.sqrt((axe*x)**2 + (aye*y)**2) / r
        ate = np.sqrt((axe*y)**2 + (aye*x)**2) / r

    # Total acceleration
    atot = py.hypot(ax, ay)
    atoterr = np.sqrt((ax*axe)**2 + (ay*aye)**2) / atot

    accLim = ar - (sigma * are)

    # Calculate the acceleration limit set by the projected radius
    # Convert into cm
    r2d = r * cc.dist * cc.cm_in_au
    # acc1 in cm/s^2
    a2d = -cc.G * cc.mass * cc.msun / r2d**2
    # acc1 in km/s/yr
    a2d *= cc.sec_in_yr / 1.0e5
    a2d *= 1000.0 / cc.asy_to_kms
    accLimR2d = a2d

    _f = open(rootDir + 'tables/accel_limits.txt', 'w')

    _f.write('###   Radial Acceleration Limits for Young Stars   ###\n')
    _f.write('%13s  %7s - (%d * %5s) =  %9s     %21s  Constrained?\n' % \
             ('Name', 'a_rad', sigma, 'aerr', 'a_obs_lim', 'a_proj_lim'))
    
    fmt = '%13s  %7.3f - (%d * %5.3f) =    %7.3f  '
    fmt += 'vs %10.3f (mas/yr^2)  %s'
    fmt2 = fmt + '\n'

    for i in range(len(ar)):
        constrained = ''
        if (accLim[i] > accLimR2d[i]):
            constrained = '**'
            
        print fmt % (names[i], ar[i], sigma, are[i], accLim[i],
                     accLimR2d[i], constrained)
        _f.write(fmt2 % (names[i], ar[i], sigma, are[i], accLim[i],
                         accLimR2d[i], constrained))

    _f.close()
Esempio n. 10
0
def plotLimitProps():
    """Make a table of the observed properties of those stars that
    have significant orbital acceleration limits.

    Currently hard coded to 06_02_14 and efit results.
    """
    # Load GC constants
    cc = objects.Constants()

    root = '/u/jlu/work/gc/proper_motion/align/06_02_14/'
    efitResults = root + 'efit/results/outer3'
    
    # Load up positional information from align. 
    s = starset.StarSet(root + 'align/align_all1000_t')
    s.loadPolyfit(root + 'polyfit/fit', arcsec=1)
    s.loadPolyfit(root + 'polyfit/fit', arcsec=1, accel=1)
    s.loadEfitResults(efitResults, trimStars=1)
    
    # Calculate acceleration limit from the 2D position
    x = s.getArray('fitXalign.p')
    y = s.getArray('fitYalign.p')
    xerr = s.getArray('fitXalign.perr')
    yerr = s.getArray('fitYalign.perr')
    r2d = py.hypot(x, y)

    # Convert into cm
    r2d *= cc.dist * cc.cm_in_au

    # acc1 in cm/s^2
    a2d = cc.G * cc.mass * cc.msun / r2d**2
    # acc1 in km/s/yr
    a2d *= cc.sec_in_yr / 1e5

    a1 = s.getArray('efit.at_lo')
    a2 = s.getArray('efit.at_hi')
    alim = [max(abs(a1[ii]), abs(a2[ii])) for ii in range(len(a1))]
    name = s.getArray('name')

    # The properties of interest
    cnt = s.getArray('velCnt')
    mag = s.getArray('mag')
    vx = s.getArray('fitXv.v') * 1000.0
    vxerr = s.getArray('fitXv.verr') * 1000.0
    vy = s.getArray('fitYv.v') * 1000.0
    vyerr = s.getArray('fitYv.verr') * 1000.0
    v2d = py.hypot(vx, vy)
    v2derr = np.sqrt((vx*vxerr)**2 + (vy*vyerr)**2) / v2d
    x = s.getArray('x')
    y = s.getArray('y')

    # Lets also read in definities only (no 05jullgs) as comparison
    root2 = root + '../06_02_14a/'
    s2 = starset.StarSet(root2 + 'align/align_d_rms_t')
    names2 = s2.getArray('name')

    idx = []
    stars2 = []
    for i in range(len(alim)):
        if (alim[i] < a2d[i]):
            idx.append(i)

        # Find this star in the new analysis
        new = names2.index(name[i])
        stars2.append(s2.stars[new])

    s2.stars = stars2
    cnt2 = s2.getArray('velCnt')
    mag2 = s2.getArray('mag')

        
    # Clear plot region
    py.figure(2, figsize=(7,6))
    py.clf()

    # Make a histogram of the number of epochs
    py.subplot(2, 2, 1)
    n, bins, patches1 = py.hist(cnt, bins=range(0, 32, 1))
    py.setp(patches1, 'facecolor', 'r')
    n, bins, patches2 = py.hist(cnt[idx], bins=range(0, 32, 1))
    py.setp(patches2, 'facecolor', 'b')
    py.legend((patches1[0], patches2[0]),
           ('All Young Stars', 'Young Stars With Acc. Limits'),
           loc='upper left', prop=FontProperties(size=8))
    py.xlabel('Number of Epochs')

    py.subplot(2, 2, 2)
    n, bins, patches = py.hist(mag, bins=range(8, 16, 1))
    py.setp(patches, 'facecolor', 'r')
    n, bins, patches = py.hist(mag[idx], bins=range(8, 16, 1))
    py.setp(patches, 'facecolor', 'b')
    py.xlabel('Magnitude')

    py.subplot(2, 2, 3)
    n, bins, patches1 = py.hist(v2d, bins=range(0,16,1))
    py.setp(patches1, 'facecolor', 'r')
    n, bins, patches2 = py.hist(v2d[idx], bins=range(0,16,1))
    py.setp(patches1, 'facecolor', 'r')
    py.xlabel('Velocity (mas/yr)')

    py.subplot(2, 2, 4)
    n, bins, patches1 = py.hist(v2derr, bins=np.arange(0,0.25,0.02))
    py.setp(patches1, 'facecolor', 'r')
    n, bins, patches2 = py.hist(v2derr[idx], bins=np.arange(0,0.25,0.02))
    py.setp(patches1, 'facecolor', 'r')
    py.xlabel('Velocity Error (mas/yr)')

    py.savefig(root + 'plots/acc_limits_properties.ps')

    py.clf()
    py.plot(x, y, 'k^')
    py.plot(x[idx], y[idx], 'r^')
    for i in range(len(x)):
        py.text(x[i], y[i], name[i])
    py.axis('equal')
    py.axis([4, -4, -4, 4])
Esempio n. 11
0
def isPhysical(x, y, ax, axe, ay, aye, arcsec = None, sigma = 3):
    """
    Return a True or False depending on whether the acceleration
    measurement is physical. Unphysical accelerations are defined as
    either: 1. Significant tangential acceleration 2. Significant
    positive radial acceleration 3. Negative acceleration greater than
    the maximum allowed at the 2D position.

    RETURN: status array where 1 is true [tangential, pos. radial, > max radial]
    """
    
    status = np.zeros(3)
    # Lets do radial/tangential
    r = np.sqrt(x**2 + y**2)
    ar = ((ax*x) + (ay*y)) / r
    at = ((ax*y) - (ay*x)) / r
    are = np.sqrt((axe*x)**2 + (aye*y)**2) / r
    ate = np.sqrt((axe*y)**2 + (aye*x)**2) / r

    # Total acceleration
    atot = py.hypot(ax, ay)
    atoterr = np.sqrt((ax*axe)**2 + (ay*aye)**2) / atot

    # Calculate the acceleration limit set by the projected radius

    if arcsec:
        #convert to mks
        cc = objects.Constants()
        
        # Convert into cm
        r2d = r * cc.dist * cc.cm_in_au

        rarc =np.arange(0.01,10.0,0.01)
        rsim = rarc * cc.dist * cc.cm_in_au
    
        # acc1 in cm/s^2
        a2d = -cc.G * cc.mass * cc.msun / r2d**2
        a2dsim = -cc.G * cc.mass * cc.msun / rsim**2
        
        # acc1 in km/s/yr
    
        a2d *= cc.sec_in_yr / 1.0e5

        #a2d *= 1000.0 / cc.asy_to_kms

        # convert between arcsec/yr^2 to km/s/yr
        ar *= cc.asy_to_kms
        are *= cc.asy_to_kms

        at *= cc.asy_to_kms
        ate *= cc.asy_to_kms

        a2dsim *= cc.sec_in_yr / 1.0e5
        #a2dsim *= 1000.0 / cc.asy_to_kms

    # tests to see if the accelerations are physical
    if (abs(at/ate) > sigma):
        #print 'significant tangential acceleration'
        status[0] = 1

    #print 'radial acceleration %f +- %f' % (ar, are)
    #print 'tangential acceleration %f +- %f' % (at, ate)
    if ((ar - (sigma*are)) > 0):
        #print 'positive radial acceleration'
        status[1] = 1

    if (ar + (sigma*are) < a2d):
        #print 'too large radial acceleration'
        status[2] = 1

    return status
Esempio n. 12
0
def histAccel(rootDir='./', align = 'align/align_d_rms_1000_abs_t',
              poly='polyfit_d/fit', points='points_d/',
              youngOnly=False):
    """
    Make a histogram of the accelerations in the radial/tangential,
    X/Y, and inline/perp. direction of motion. Also, the large outliers
    (> 3 sigma) are also printed out.

    Inputs:
    rootDir   = The root directory of an astrometry analysis
                (e.g. '07_05_18/' or './' if you are in the directory).
    align     = The align root file name (including the directory relative
                to rootDir). Make sure that polyfit was run on this align
		output.
    poly      = The polyfit root file name (including the directory relative
                to rootDir). This should be run on the same align as above.
    points    = The points directory.
    youngOnly = Only plot the known young stars. This does not include 
                the central arcsecond sources.

    Output:
    plots/polyfit_hist_accel.eps (and png)
    -- Contains the histograms of the accelerations.

    plots/polyfit_hist_accel_nepochs.eps (ang png)
    -- Contains a plot of number of stars vs. acceleration significance.
    """
    
    s = starset.StarSet(rootDir + align)
    s.loadPolyfit(rootDir + poly, accel=0, arcsec=1)
    s.loadPolyfit(rootDir + poly, accel=1, arcsec=1)

    names = s.getArray('name')

    # In mas/yr^2
    x0 = s.getArray('fitXa.p')
    y0 = s.getArray('fitYa.p')
    x0e = s.getArray('fitXa.perr')
    y0e = s.getArray('fitYa.perr')
    vx = s.getArray('fitXa.v')
    vy = s.getArray('fitYa.v')
    ax = s.getArray('fitXa.a')
    ay = s.getArray('fitYa.a')
    axe = s.getArray('fitXa.aerr')
    aye = s.getArray('fitYa.aerr')
    r2d = s.getArray('r2d')
    cnt = s.getArray('velCnt')

    if (youngOnly == True):
        yngNames = young.youngStarNames()

        idx = []

        for ii in range(len(names)):
            if (r2d[ii] > 0.8 and
                names[ii] in yngNames):# and
                #cnt[ii] >= 24):

                idx.append(ii)

        names = [names[i] for i in idx]
        x0 = x0[idx]
        y0 = y0[idx]
        x0e = x0e[idx]
        y0e = y0e[idx]
        vx = vx[idx]
        vy = vy[idx]
        ax = ax[idx]
        ay = ay[idx]
        axe = axe[idx]
        aye = aye[idx]
        r2d = r2d[idx]
        cnt = cnt[idx]
        print 'Found %d young stars' % len(names)

    pntcnt = np.zeros(len(names))
    for ii in range(len(names)):
        pntFileName = '%s%s.points' % (rootDir+points, names[ii])
        pntFile = open(pntFileName)
        data = pntFile.readlines()
        pntcnt[ii] = len(data)


    # Lets also do radial/tangential
    r = np.sqrt(x0**2 + y0**2)
    ar = ((ax*x0) + (ay*y0)) / r
    at = ((ax*y0) - (ay*x0)) / r
    are =  (axe*x0/r)**2 + (aye*y0/r)**2
    are += (y0*x0e*at/r**2)**2 + (x0*y0e*at/r**2)**2
    are =  np.sqrt(are)
    ate =  (axe*y0/r)**2 + (aye*x0/r)**2
    ate += (y0*x0e*ar/r**2)**2 + (x0*y0e*ar/r**2)**2
    ate =  np.sqrt(ate)

    # Lets also do parallael/perpendicular to velocity
    v = np.sqrt(vx**2 + vy**2)
    am = ((ax*vx) + (ay*vy)) / v
    an = ((ax*vy) - (ay*vx)) / v
    ame = np.sqrt((axe*vx)**2 + (aye*vy)**2) / v
    ane = np.sqrt((axe*vy)**2 + (aye*vx)**2) / v

    # Total acceleration
    atot = py.hypot(ax, ay)
    atoterr = np.sqrt((ax*axe)**2 + (ay*aye)**2) / atot

    def plotHist(val, pos, label):
        py.subplot(3, 2, pos)
        py.hist(val, bins=range(-8, 8, 1))
        py.axis([-8, 8, 0, (len(val)/3) + 2])
        #py.plot(r2d, val, 'k^')
        #for ii in range(len(r2d)):
        #   py.text(r2d[ii], val[ii], names[ii])
        #py.axis([0.5, 4.0, -7, 7])
        py.title(label)

        print 'Significant Values for %s' % (label)
        idx = (np.where(abs(val) > 3.0))[0]
        for i in idx:
            print '%15s   %5.2f sigma    %2d epochs' % \
                  (names[i], val[i], pntcnt[i])

    py.figure(3, figsize=(7.5,10))
    py.clf()
    plotHist(atot / atoterr, 1, 'Total')

    py.clf()

    # XY
    plotHist(ax / axe, 1, 'X')
    plotHist(ay / aye, 2, 'Y')
    
    # Radial/Tangential
    plotHist(ar / are, 3, 'Radial')
    plotHist(at / ate, 4, 'Tangential')

    # In line of Motion and out
    plotHist(an / ane, 5, 'Perpendic. to v')
    plotHist(am / ame, 6, 'Parallel to v')

    py.savefig('plots/polyfit_hist_accel.eps')
    py.savefig('plots/polyfit_hist_accel.png')


    # Analyze the non-central arcsec sources for Nepochs threshold
    idx = (np.where(r2d > 0.8))[0]

    py.figure(1)
    py.clf()
    py.subplot(2, 1, 1)
    py.plot(ar[idx] / are[idx], pntcnt[idx], 'k.')
    py.axis([-10, 10, 0, 30])
    py.xlabel('Radial Acc. Sig. (sigma)')
    py.ylabel('Number of Epochs Detected')

    py.subplot(2, 1, 2)
    py.plot(at[idx] / ate[idx], pntcnt[idx], 'k.')
    py.axis([-10, 10, 0, 30])
    py.xlabel('Tangent. Acc. Sig. (sigma)')
    py.ylabel('Number of Epochs Detected')

    py.savefig('plots/polyfit_hist_accel_nepochs.eps')
    py.savefig('plots/polyfit_hist_accel_nepochs.png')
Esempio n. 13
0
def plotcomp(compdict, showplot=True, wantdict=False, symb=',',
             include0amp=False, include0bl=False, blunit='', bl0flux=0.0):

    """
    Given a dict including
    
    {'clist': component list,
     'objname': objname,
     'epoch': epoch,
     'shape': component shape dict, including direction.
     'freqs (GHz)': pl.array of frequencies,
     'antennalist': An array configuration file as used by simdata,
     'savedfig': False or, if specified, the filename to save the plot to,
     'standard': setjy fluxstandard type},

    and symb: One of matplotlib's codes for plot symbols: .:,o^v<>s+xDd234hH|_
          default: ',':  The smallest points I could find,

    make a plot of visibility amplitude vs. baseline length for clist at epoch.

    If antennalist is not found as is, it will look for antennalist in
    os.getenv('CASAPATH').split(' ')[0] + '/data/alma/simmos/'.
    
    showplot: Whether or not to show the plot on screen.

    If wantdict is True, it returns a dictionary with the amplitudes and
    baselines on success.  Otherwise, it returns True or False as its estimated
    success value.

    include0amp: Force the lower limit of the amplitude axis to 0.
    include0bl: Force the lower limit of the baseline length axis to 0.
    blunit: unit of the baseline length (='' used the unit in the data or klambda)
    bl0flux: Zero baseline flux
    """
    def failval():
        """
        Returns an appropriate failure value.
        Note that mydict.update(plotcomp(wantdict=True, ...)) would give a
        confusing error message if plotcomp returned False.
        """
        retval = False
        if wantdict:
            retval = {}
        return retval
    retval = failval()  # Default
    try:
        clist = compdict['clist']
        objname = compdict['objname']
        epoch = compdict['epoch']
        epstr = mepoch_to_str(epoch)
        antennalist = compdict['antennalist']

        # Read the configuration info.
        if not antennalist:
            print "compdict['antennalist'] must be set!"
            print "Try something in", os.getenv("CASAPATH").split(' ')[0] + "/data/alma/simmos/"
            return failval()
        # Try repodir if raw antennalist doesn't work.
        if not os.path.exists(antennalist):
            repodir = os.getenv("CASAPATH").split(' ')[0] + "/data/alma/simmos/"
            antennalist = repodir + antennalist

        su = simutil("")
        stnx, stny, stnz, diam, padnames, nant, telescopename = su.readantenna(antennalist)
        #print "telescopename:", telescopename

        # Check that the source is up.
        myme = metool()
        posobs = myme.observatory(telescopename)
        #print "posobs:", posobs
        myme.doframe(epoch)
        myme.doframe(posobs)
        azel = myme.measure(compdict['shape']['direction'], 'azel')
        azeldegs = tuple([qa.convert(azel[m], 'deg')['value'] for m in ('m0', 'm1')])
        casalog.post("(az, el): (%.2f, %.2f) degrees" % azeldegs)
        # riseset blabs to the logger, so introduce it now.
        casalog.post('Rise and set times of ' + objname + " from " + telescopename + ':')
        approx = ''
        if 'JPL' in compdict.get('standard', 'JPL'):
            # The object is in the Solar System or not known to be extragalactic.
            approx = "APPROXIMATE.  The times do not account for the apparent motion of "\
                     + objname + "."
            casalog.post("  (" + approx + ")")
        riset = myme.riseset(compdict['shape']['direction'])
        msg = ''
        if riset['rise'] == 'above':
            msg = objname + " is circumpolar"
        elif riset['rise'] == 'below':
            msg = objname + ' is not visible from ' + telescopename
        if msg:
            if approx:
                msg += ' around ' + mepoch_to_str(epoch)
            casalog.post(msg)
        else:
            for t in riset:
                riset[t]['str'] = mepoch_to_str(riset[t]['utc'])
            casalog.post(objname + " rises at %s and sets at %s." % (riset['rise']['str'],
                                                                     riset['set']['str']))
            tmeridian=(riset['rise']['utc']['m0']['value']+riset['set']['utc']['m0']['value'])/2.
            casalog.post(objname + ': meridian passage at ' + qa.time(str(tmeridian)+'d')[0])

        if approx:
            riset['NOTE'] = approx
        if not azel['m1']['value'] > 0.0:
            casalog.post(objname + " is not visible from " + telescopename + " at " + epstr,
                         'SEVERE')
            if wantdict:
                return riset
            else:
                return False

        # Start a temp MS.
        workingdir = os.path.abspath(os.path.dirname(clist.rstrip('/')))
        tempms = tempfile.mkdtemp(prefix=objname, dir=workingdir)

        mysm = smtool()
        mysm.open(tempms)

        su.setcfg(mysm, telescopename, stnx, stny, stnz, diam,
                  padnames, posobs)

        #print "cfg set"

        # Only 1 polarization is wanted for now.
        stokes, feeds = su.polsettings(telescopename, 'RR')
        
        casalog.post("stokes, feeds: %s, %s" % (stokes, feeds))
        fband = su.bandname(compdict['freqs (GHz)'][0])
        chaninc = 1.0
        nchan = len(compdict['freqs (GHz)'])
        if nchan > 1:
            chaninc = (compdict['freqs (GHz)'][-1] - compdict['freqs (GHz)'][0]) / (nchan - 1)
        mysm.setspwindow(spwname=fband,
                         freq=str(compdict['freqs (GHz)'][0]) + 'GHz', 
                         deltafreq=str(chaninc) + 'GHz', 
                         freqresolution='1Hz', 
                         nchannels=nchan, refcode="LSRK",
                         stokes=stokes)
        mysm.setfeed(mode=feeds, pol=[''])
        mysm.setlimits(shadowlimit=0.01, elevationlimit='10deg')
        mysm.setauto(0.0)
        mysm.setfield(sourcename=objname,
                      sourcedirection=compdict['shape']['direction'],
                      calcode="OBJ", distance='0m')
        mysm.settimes(integrationtime="1s", usehourangle=False,
                      referencetime=epoch)
        
        # this only creates blank uv entries
        mysm.observe(sourcename=objname, spwname=fband,
                   starttime="-0.5s", stoptime="0.5s", project=objname)

        mysm.setdata(fieldid=[0])
        mysm.setvp()
        casalog.post("done setting up simulation parameters")

        mysm.predict(complist=clist)        # do actual calculation of visibilities:

        mysm.close()
        casalog.post("Simulation finished.")

        mytb = tbtool()
        mytb.open(tempms)
        data = mytb.getcol('DATA')[0]       # Again, only 1 polarization for now. 
        data = abs(data)
        baselines = mytb.getcol('UVW')[:2,:]  # Drop w.
        datablunit = mytb.getcolkeywords('UVW')['QuantumUnits']
        mytb.close()
        #print "Got the data and baselines"
        shutil.rmtree(tempms)

        if datablunit[1] != datablunit[0]:
            casalog.post('The baseline units are mismatched!: %s' % datablunit,
                         'SEVERE')
            return failval()
        datablunit = datablunit[0]
        # uv dist unit in klambda or m
        if datablunit == 'm' and blunit=='klambda':
            kl = qa.constants('C')['value']/(compdict['freqs (GHz)'][0]*1e6)
            blunit = 'k$\lambda$'
        else:
            blunit = datablunit
            kl = 1.0
        pl.ioff()
        #baselines = pl.hypot(baselines[0]/kl, baselines[1]/kl)
        baselines = pl.hypot(baselines[0], baselines[1])

        #if not showplot:
        #    casalog.post('Sorry, not showing the plot is not yet implemented',
        #                 'WARN')

        if showplot: 
          pl.ion()
        pl.clf()
        pl.ioff() 
        nfreqs = len(compdict['freqs (GHz)'])
        for freqnum in xrange(nfreqs):
            freq = compdict['freqs (GHz)'][freqnum]
            casalog.post("Plotting " + str(freq) + " GHz.")
            pl.plot(baselines/kl, data[freqnum], symb, label="%.3g GHz" % freq)
            #pl.plot(baselines, data[freqnum], symb, label="%.3g GHz" % freq)
        pl.xlabel("Baseline length (" + blunit + ")")
        pl.ylabel("Visibility amplitude (Jy)")
        if include0amp:
            pl.ylim(ymin=0.0)
        if include0bl:
            pl.xlim(xmin=0.0)
        pl.suptitle(objname + " (predicted by %s)" % compdict['standard'], fontsize=14)
        #pl.suptitle(objname + " (predicted)", fontsize=14)

        # Unlike compdict['antennalist'], antennalist might have had repodir
        # prefixed to it.
        pl.title('at ' + epstr + ' for ' + os.path.basename(compdict['antennalist']), fontsize=10)
        titletxt='($%.0f^\circ$ az, $%.0f^\circ$ el)' % azeldegs
        # for comparison of old and new models - omit azeldegs as all in az~0
        if bl0flux > 0.0:
            if len(compdict['freqs (GHz)']) == 1:
                titletxt+='\n bl0 flux:%.3f Jy' % bl0flux
            else:
                titletxt+='\n bl0 flux:%.3f Jy @ %s GHz' % (bl0flux, compdict['freqs (GHz)'][0]) 
        pl.legend(loc='best', title=titletxt)
        #pl.legend(loc='best', title='($%.0f^\circ$ az, $%.0f^\circ$ el)' % azeldegs)
        y_formatter=matplotlib.ticker.ScalarFormatter(useOffset=False)
        pl.axes().yaxis.set_major_formatter(y_formatter) 
        if showplot:
          pl.ion()
          pl.draw()
        if compdict.get('savedfig'):
            pl.savefig(compdict.get('savedfig'))
            casalog.post("Saved plot to " + str(compdict.get('savedfig')))

        if wantdict:
            retval = {'amps': data,
                      'antennalist': antennalist,  # Absolute path, now.
                      'azel': azel,
                      'baselines': baselines,
                      'blunit': blunit,
                      'riseset': riset,
                      'savedfig': compdict.get('savedfig')}
        else:
            retval = True
    except Exception, instance:
        casalog.post(str(instance), 'SEVERE')
        if os.path.isdir(tempms):
            shutil.rmtree(tempms)
Esempio n. 14
0
    def plot2D_fiber(self, cracking=1):

        #we will build line by line the "vector field" assiciated to the results file.

        if self.f.Lz > 1:
            print(
                "Lz != 0 impossible to plot 2d, you certainly want to plot a 3d network"
            )

        for j in range(0, self.f.Ly):
            if (j % 2 == 0):
                pair = 1
            else:
                pair = 0
            for k in range(0, self.f.Lz):
                for i in range(0, self.f.Lx):
                    self.X.append(
                        float(self.DataNode[i + j * self.f.Ly +
                                            k * self.f.Lz][0]))
                    self.Y.append(
                        float(self.DataNode[i + j * self.f.Ly +
                                            k * self.f.Lz][1]))
                    self.U.append(
                        float(self.DataFiber[i + j * self.f.Ly +
                                             k * self.f.Lz][0]))
                    self.V.append(
                        float(self.DataFiber[i + j * self.f.Ly +
                                             k * self.f.Lz][1]))
                    self.Rlength.append(self.Length[i + j * self.f.Ly, 0])

                    self.X.append(
                        float(self.DataNode[i + j * self.f.Ly +
                                            k * self.f.Lz][0]))
                    self.Y.append(
                        float(self.DataNode[i + j * self.f.Ly +
                                            k * self.f.Lz][1]))
                    self.U.append(
                        float(self.DataFiber[i + j * self.f.Ly +
                                             k * self.f.Lz][2]))
                    self.V.append(
                        float(self.DataFiber[i + j * self.f.Ly +
                                             k * self.f.Lz][3]))
                    self.Rlength.append(self.Length[i + j * self.f.Ly, 1])

                    self.X.append(
                        float(self.DataNode[i + j * self.f.Ly +
                                            k * self.f.Lz][0]))
                    self.Y.append(
                        float(self.DataNode[i + j * self.f.Ly +
                                            k * self.f.Lz][1]))
                    self.U.append(
                        float(self.DataFiber[i + j * self.f.Ly +
                                             k * self.f.Lz][4]))
                    self.V.append(
                        float(self.DataFiber[i + j * self.f.Ly +
                                             k * self.f.Lz][5]))
                    self.Rlength.append(self.Length[i + j * self.f.Ly, 2])

        Norm = (pylab.hypot(self.U, self.V) - self.Rlength)
        pylab.quiver(self.X,
                     self.Y,
                     self.U,
                     self.V,
                     Norm,
                     scale=1.0,
                     angles='xy',
                     scale_units='xy',
                     width=0.005,
                     minlength=0.,
                     headlength=0.,
                     headaxislength=0.,
                     headwidth=0.,
                     alpha=1,
                     edgecolor='k',
                     cmap=cm)
        #pylab.quiver(self.X,self.Y,self.U,self.V,Norm ,scale = 1.0,angles='xy',scale_units = 'xy',width = 0.005,minlength=0.,headlength=10,headaxislength=10,headwidth=10,alpha=1,edgecolor='k',cmap=cm)
        #pylab.quiver(self.X,self.Y,self.U,self.V ,scale = 1.0,angles='xy',scale_units = 'xy',width = 0.005,minlength=0.,headlength=0.,headaxislength=0.,headwidth=0.,alpha=1,edgecolor='k',cmap=cm)
        #pylab.clim(0.,0.5)

        #pylab.clim(-0.15,0.20)

        pylab.clim(-0.05, 0.05)