Exemplo n.º 1
0
tel, obs, longit, latit, height = subs.observatory(args.telescope)

# Load position and ephemeris data
peinfo = {}
count = 0
nline = 0
name = None
for line in args.stardata:
    nline += 1
    try:
        if not line.startswith('#') and not line.isspace():
            count += 1
            if count == 1:
                name = line.strip()
            elif count == 2:
                ra, dec, system = subs.str2radec(line.strip())
            elif count == 3:
                # Position-based key for RA-ordering later
                key = subs.d2hms(ra, dp=2) + ' ' + subs.d2hms(
                    dec, dp=1, sign=True)
                eph = observing.Ephemeris(line)
                peinfo[key] = {
                    'name': name,
                    'ephemeris': eph,
                    'ra': ra,
                    'dec': dec
                }
                count = 0
    except Exception, err:
        print err
        print 'Line number', nline
Exemplo n.º 2
0
def coordinates(command, data, group, cdata):
    """
    Adds astronomical position information to slots.

    Interactive usage:

    coordinates slots target position [rapm=0 decpm=0 epoch=2000.0 parallax=0 rv=0]

    Arguments:

    slots     -- slot, slot range or group which will be processed.
    target    -- target name
    position  -- RA, dec as in '12 34 45.56 -00 12 34.2' or decimal degrees '234.5645 -1.2'. Optionally
                 you can add any of 'ICRS', 'J2000' or 'B1950' at the end, but note that only 'ICRS' (the
                 default) is supported as of Aug 2008. See trm.subs.str2radec for full format info.
    epoch     -- Julian epoch of coordinates (only matters if there is proper motion and RV)
    pmra      -- proper motion in RA (arcsec/year)
    pmdec     -- proper motion in Dec (arcsec/year)
    parallax  -- parallax, (arcsec)
    rv        -- radial velocity, (km/s)

    Script usage:

    command  -- contains a string as used interactively
    data     -- a Data containing Dsets.
    group    -- a Group containing slot list groups

    Returns True/False according to whether it ran OK
    """

    # generate arguments
    inpt = inp.Input(DINT_ENV, DINT_DEF, inp.clist(command))

    # register parameters
    inpt.register('slots',     inp.Input.LOCAL,  inp.Input.PROMPT)
    inpt.register('target',    inp.Input.LOCAL,  inp.Input.PROMPT)
    inpt.register('position',  inp.Input.LOCAL,  inp.Input.PROMPT)
    inpt.register('epoch',     inp.Input.LOCAL,  inp.Input.HIDE)
    inpt.register('pmra',      inp.Input.LOCAL,  inp.Input.HIDE)
    inpt.register('pmdec',     inp.Input.LOCAL,  inp.Input.HIDE)
    inpt.register('parallax',  inp.Input.LOCAL,  inp.Input.HIDE)
    inpt.register('rv',        inp.Input.LOCAL,  inp.Input.HIDE)

    # get inputs
    slots    = inpt.get_value('slots', 'slots to mask', '1-1000')
    slist    = interp_slots(slots, True, data, group)
    target   = inpt.get_value('target',  'name of target', 'M31')
    position = inpt.get_value('position',  'celestial coordinates of target', '12 34 45.67 -00 11 23.4')
    ra,dec,system = subs.str2radec(position)

    inpt.set_default('epoch', 2000.0)
    epoch = inpt.get_value('epoch', 'Julian epoch of coordinates', 2000.0)
    inpt.set_default('pmra', 0.)
    pmra = inpt.get_value('pmra', 'proper motion in RA (arcsec/yr)', 0.)
    inpt.set_default('pmdec', 0.)
    pmdec = inpt.get_value('pmdec', 'proper motion in Dec (arcsec/yr)', 0.)
    inpt.set_default('parallax', 0.)
    parallax = inpt.get_value('parallax', 'parallax (arcsec)', 0.)
    inpt.set_default('rv', 0.)
    rv = inpt.get_value('rv', 'radial velocity (km/s)', 0.)

    for slot in slist:
        data[slot].setpos(target, ra, dec, system, pmra, pmdec, epoch, parallax, rv)
        if not cdata.mute:
            print('Added astronomical target data to slot ' + str(slot))
Exemplo n.º 3
0
# Load position and ephemeris data
peinfo = {}
count = 0
nline = 0
name  = None
for line in args.stardata:
    nline += 1
    try:
        if not line.startswith('#') and not line.isspace():
            count += 1
            if count == 1:
                arr  = line.split('|')
                name = arr[0].strip()
                lw   = 1 if len(arr) == 1 else int(arr[1])
            elif count == 2:
                ra,dec,system = subs.str2radec(line.strip())
            elif count == 3:
                try:
                    eph = observing.Ephemeris(line)
                    peinfo[name] = observing.Sdata(ra, dec, eph, lw)
                except:
                    print 'No valid ephemeris data found for',name
                    peinfo[name] = observing.Sdata(ra, dec, None, lw)
                count = 0
    except Exception, err:
        print err
        print 'Line number',nline
        print 'Line =',line.strip()
        if name:
            print 'Name = ' + name
        else:
Exemplo n.º 4
0
def make_eso_chart(fname, cname, target, info, pid, pi, pos, field, scale,
                   stype='sec', source=None, angle=None, mark=True, s1=0.04,
                   s2=0.1, plo=50.0, phi=99.8, sloc=-0.43, pwidth=6,
                   fsize=12, aspect=0.6, pm=None, obsdate=None, 
                   lhead=0.02):
    """Make a chart suitable for VLT. Arguments::

    fname   : (string)
            fits file from DSS, e.g. 'PG1018-047.fits'

    cname   : (string)
            chart name (e.g. "name.pdf". The type of file is deduced 
            from the suffix. Either .pdf or .jpg are recognised)

    target  : (string)
            target name, e.g. 'PG1018-047'

    info    : (string or list of strings)
            extra information, e.g. 'Slit angle: parallactic'. 
            A list of strings will be printed line by line

    pid     : (string)
            programme ID, e.g. '088.D-0041(A)'

    pi      : (string)
            PI name, e.g. 'Marsh'

    pos     : (string)
            position, e.g. '10 21 10.6 -04 56 19.6' (assumed 2000)

    field   : (float)
            field width to display, arcmin, e.g. 1.0

    scale   : (float)
            size of scale to indicate in arcsec, e.g. 30

    stype   : (string)
            'sec' or 'min' to indicate how to mark the scale

    source  : (string)
            source of fits file, e.g. 'DSS blue'. Ignore for automatic version.

    angle   : (float)
            indicator / slit angle to display, degrees. None to ignore.

    mark    : (bool)
            True to indicate object

    s1      : (float)
            fraction of field for start of slit and object markers
            (displaced from object)

    s2      : (float)
            fraction of field for end of slit and object markers
            (displaced from object)

    plo     : (float)
            Low image display level, percentile

    phi     : (float)
            High image display level, percentile

    sloc    : (float) 
            vertical location of scale bar in terms of 'field'

    pwidth  : (float)
            (approx) plot width in inches

    fsize   : (int)
            fontsize, pt

    aspect  : (float)
            aspect (vertical/horizontal) [should be < 1]

    pm      : (tuple)
            proper motion in RA, and dec, arcsec/year in both
            coords. This is used to correct the predicted position of the
            target in the image by finding the date on which the image was
            taken.

    obsdate : (string)
            if you set pm, then if you also set date, an arrow
            arrow will be drawn from target to its expected position at
            obsdate and the chart will be centred on the head of the
            arrow. obsdate should be in YYYY-MM-DD format. 

    lhead   : (float)
            length of arrow head as fraction of field. If this turns out
            to be longer than the entire arrow, no arrow is drawn.

    Returns (ilo,ihi) display levels used
    """

    # ra, dec in degrees
    ra,dec,sys = subs.str2radec(pos)
    ra *= 15

    # Read data
    hdulist   = fits.open(fname)
    data      = hdulist[0].data
    head      = hdulist[0].header
    hdulist.close()

    arrow = False
    if pm:
        # try to correct position to supplied date or
        # date of chart

        if 'DATE-OBS' in head:
            dobs    = head['DATE-OBS']
            year    = int(dobs[:4])
            month   = int(dobs[5:7])
            day     = int(dobs[8:10])
            deltat  = (sla.cldj(year,month,day) - sla.cldj(2000,1,1))/365.25
            dra     = pm[0]*deltat/np.cos(np.radians(dec))/3600.
            ddec    = pm[1]*deltat/3600.
            ra  += dra
            dec += ddec
            if obsdate:
                yearp,monthp,dayp = obsdate.split('-')
                deltat  = (sla.cldj(int(yearp),int(monthp),int(dayp)) - \
                               sla.cldj(year,month,day))/365.25
                dra     = pm[0]*deltat/np.cos(np.radians(dec))/3600.
                ddec    = pm[1]*deltat/3600.
                ra += dra
                dec += ddec
                arrow   = True
        else:
            print 'WARNING: Could not find DATE-OBS in header'

    # Read WCS info
    wcs = astWCS.WCS(fname)
    dx  = 60.*wcs.getXPixelSizeDeg()
    dy  = 60.*wcs.getYPixelSizeDeg()
    rot = wcs.getRotationDeg()
    if rot > 180.:
        rot -= 360.
    if not wcs.coordsAreInImage(ra,dec):
        print 'WARNING: coordinates not inside image'

    # pixel position corresponding to desired ra and dec
    x,y = wcs.wcs2pix(ra, dec)
    if arrow:
        if not wcs.coordsAreInImage(ra-dra,dec-ddec):
            print 'WARNING: End of proper motion arrow is not inside image'
        xa,ya = wcs.wcs2pix(ra-dra, dec-ddec)

    ny, nx = data.shape

    # plot limits
    limits = (dx*(-0.5-x),dx*(nx-0.5-x),dy*(-0.5-y),dy*(ny-0.5-y))

    if source is None:
        if 'SURVEY' in head:
            source = head['SURVEY']
            if source == 'POSSII-F':
                source = 'POSS-II red'
            elif source == 'POSSII-J':
                source = 'POSS-II blue'
            elif source == 'POSSII-N':
                source = 'POSS-II ir'
            elif source == 'POSSI-E':
                source = 'POSS-I red'
            elif source == 'POSSI-O':
                source = 'POSS-I blue'
            elif source == 'SERC-I':
                source = 'SERC ir'
            elif source == 'SERC-J':
                source = 'SERC blue'
            elif source == 'AAO-SES':
                source = 'AAO red'
            elif source == 'AAO-GR':
                source = 'AAO red'
        else:
            source = 'UNKNOWN'

    # Start plotting
    fig  = plt.figure(figsize=(pwidth,pwidth))
    axes = fig.add_subplot(111,aspect='equal')
    mpl.rc('font', size=fsize)

    # Derive the plot range
    ilo  = stats.scoreatpercentile(data.flat, plo)
    ihi  = stats.scoreatpercentile(data.flat, phi)

    # Plot
    plt.imshow(data, vmin=ilo, vmax=ihi, cmap=cm.binary, extent=limits,
               interpolation='nearest', origin='lower')
    axes.autoscale(False)

    # draw slit angle
    if angle is not None:
        ca = m.cos(m.radians(angle+rot))
        sa = m.sin(m.radians(angle+rot))
        t1 = s1*field
        t2 = s2*field
        plt.plot([-sa*t1,-sa*t2],[+ca*t1,+ca*t2],BLUE,lw=3)
        plt.plot([+sa*t1,+sa*t2],[-ca*t1,-ca*t2],BLUE,lw=3)

    # Mark object
    if mark:
        t1 = s1*field
        t2 = s2*field
        plt.plot([t1,t2],[0,0],RED,lw=3)
        plt.plot([0,0],[t1,t2],RED,lw=3)

    # draw arrow
    if arrow:
        # Slightly complicated because matplotlib
        # arrow stupidly starts drawing the head of the
        # arrow at the end point so we need to shrink the
        # arrow. If it becomes negative, don't draw at all,
        # just issue a warning
        delx, dely = dx*(x-xa), dy*(y-ya)
        length = m.sqrt(delx**2+dely**2)
        hl = field*lhead
        lnew = length-hl
        if lnew > 0:
            shrink = lnew/length
            plt.arrow(-delx, -dely, shrink*delx, shrink*dely,
                       head_width=0.5*hl, head_length=hl)
        else:
            print 'WARNING: arrow head too long; arrow not drawn'

    # Draw scale bar
    if stype == 'sec' or stype == 'min':
        if stype == 'sec':
            plt.text(0, (sloc-0.05)*field, str(scale) + ' arcsec',
                     horizontalalignment='center',color=RED)
        elif stype == 'min':
            plt.text(0, (sloc-0.05)*field, str(scale/60) + ' arcmin',
                     horizontalalignment='center',color=RED)

        scale /= 60.
        plt.plot([-0.5*scale,+0.5*scale],[sloc*field,sloc*field],RED,lw=3)
        plt.plot([+0.5*scale,+0.5*scale],[(sloc+0.02)*field,(sloc-0.02)*field],
                 RED,lw=3)
        plt.plot([-0.5*scale,-0.5*scale],[(sloc+0.02)*field,(sloc-0.02)*field],
                 RED,lw=3)

    # North-East indicator. ev, nv = East / North vectors
    xc, yc = 0.4*field, -0.4*field
    rot   = m.radians(rot)
    rmat  = np.matrix(((m.cos(rot),-m.sin(rot)),(m.sin(rot),m.cos(rot))))

    nv = np.array((0.,0.2*field))
    nv = nv.reshape((2,1))
    nv = rmat*nv
    nv = np.array(nv).flatten()

    ev = np.array((-0.2*field,0.))
    ev = ev.reshape((2,1))
    ev = rmat*ev
    ev = np.array(ev).flatten()

    plt.plot([xc,xc+nv[0]],[yc,yc+nv[1]],RED,lw=3)
    plt.text(xc+1.1*nv[0], yc+1.1*nv[1], 'N', horizontalalignment='center',
             color=RED)
    plt.plot([xc,xc+ev[0]],[yc,yc+ev[1]],RED,lw=3)
    plt.text(xc+1.15*ev[0], yc+1.1*ev[1], 'E', verticalalignment='center',
             color=RED)

    # finally the textual info with a helper function
    def ptext(x, y, field, tstr):
        """
        Converts relative (0-1) x,y limits into data coords and plots
        a string.
        """
        xd = -field/2.+field*x
        yd = -field/2.+field*y
        plt.text(xd, yd, tstr, horizontalalignment='left',color=BLUE)

    xoff = 0.02
    dely = 0.035
    yoff = 0.96

    if pid != '':
        ptext(xoff, yoff, field, pid)
        yoff -= dely

    if pi != '':
        ptext(xoff, yoff, field, 'PI: ' + pi)
        yoff -= 1.5*dely

    if target != '':
        ptext(xoff, yoff, field, 'Target: ' + target)
        yoff -= 1.5*dely

    rah,ram,ras,decd,decm,decs = pos.split()
    ptext(xoff, yoff, field, 'RA (2000) : ' + rah + ' ' + ram + ' ' + ras)

    yoff -= dely
    ptext(xoff, yoff, field, 'Dec (2000): ' + decd + ' ' + decm + ' ' + decs)

    yoff -= 1.5*dely
    ptext(xoff, yoff, field, "Field: " + str(field) + "' x " + str(field) + "'")

    if 'DATE-OBS' in head:
        yoff -= dely
        ptext(xoff, yoff, field, 'Date: ' + head['DATE-OBS'][:10])

    if source != '':
        yoff -= dely
        ptext(xoff, yoff, field, 'Survey: ' + source)

    yoff -= 2.*dely
    if info is not None:
        if isinstance(info, list):
            for line in info:
                ptext(xoff, yoff, field, line)
                yoff -= dely
        else:
            ptext(xoff, yoff,  field, info)

    plt.xlim(-field/2.,field/2.)
    plt.ylim(-field/2.,field/2.)
    plt.savefig(cname,bbox_inches='tight')
    return (ilo,ihi)
Exemplo n.º 5
0
    append = False

# Now try to interpret target. The ultimate aim is 
# to arrive at a position to search around.

target = ' '.join(args)

import re
import trm.subs as subs

if re.search('[a-zA-Z]', target):
    import trm.simbad as simbad
    results = simbad.Query(target).query()
    if len(results):
        print 'Simbad returned coordinates: ',results[0]['Position']
        (ra,dec,system) = subs.str2radec(results[0]['Position'])
else:
    (ra,dec,system) = subs.str2radec(target)

dist  = options.dist
wave  = options.wave

import trm.sla as sla

dre = re.compile('(\d\d\d\d)-(\d\d)-(\d\d)$')
 
m = re.match(dre, options.start) 
if m:
    year  = int(m.group(1))
    month = int(m.group(2))
    day   = int(m.group(3))
Exemplo n.º 6
0
 6) the rejection threshold for removing bad data.

There should be more good data than bad for the auto-rejection to work effectively.
"""

import numpy as np
import matplotlib.pyplot as plt
import pyfits
from scipy.optimize import leastsq, fmin
from trm import subs, sla

# Names of runs (names assumed to be of form 'run123.fits' -- you provide the numbers)
runs = (11, 12, 13, 15, 19)

# Star position
ra,dec,syst = subs.str2radec('06 30 32.79 +29 40 20.3')

# Observatory
tel,obs,longit,latit,height = subs.observatory('WHT')

# Target aperture to use
nap = 2

# Bin width in minutes
deltat = 1.

# Rejection threshold, RMS
thresh = 2.5

def linfit(p, x):
    return p[0]+p[1]*x
Exemplo n.º 7
0
                run = Ultra.Run(xml, nlog, times, targets, telescope, ndir,
                                rdir, sskip, True)

                # update targets to reduce simbad lookups
                if run.simbad:
                    if run.id in targets:
                        targets[run.id]['match'].append((run.target, True))
                    else:
                        targets[run.id] = {'ra' : subs.hms2d(run.ra), \
                                               'dec' : subs.hms2d(run.dec),
                                           'match' : [(run.target, True),]}
                elif run.id is None:
                    sskip.append(run.target)

                if run.ra is not None and run.dec is not None:
                    rah, decd, csys = subs.str2radec(run.ra + ' ' + run.dec)
                    entries.append(
                        {'ra' : rah, 'dec' : decd, 'run' : run.run,
                         'night' : run.night,
                         'num' : run.number, 'target' : run.target.strip(),
                         'id' : run.id.strip(),
                         'expose' : 0. if run.expose is None else \
                             float(run.expose)/60.,
                         'comment' : run.comment.strip()})

            except Exception, err:
                print 'XML error: ',err,'in',xml

print '\nFound',len(entries),'runs.'

with open('ultra.json','w') as fout: