Exemplo n.º 1
0
def movieFields(outfile,
                fields=None,
                target_fields=None,
                completed_fields=None,
                **kwargs):
    if os.path.splitext(outfile)[-1] not in ['.gif']:
        msg = "Only animated gif currently supported."
        raise Exception(msg)

    tmpdir = tempfile.mkdtemp()

    if fields is None:
        fields = completed_fields[-1]

    if isinstance(fields, np.core.records.record):
        tmp = FieldArray(1)
        tmp[0] = fields
        fields = tmp

    plt.ioff()
    for i, f in enumerate(fields):
        plotField(fields[i], target_fields, completed_fields, **kwargs)
        png = os.path.join(tmpdir, 'field_%08i.png' % i)
        plt.savefig(png, dpi=DPI)
        if completed_fields is None: completed_fields = FieldArray()
        completed_fields = completed_fields + fields[[i]]
    plt.ion()

    cmd = 'convert -delay 10 -loop 0 %s/*.png %s' % (tmpdir, outfile)
    logging.info(cmd)
    subprocess.call(cmd, shell=True)
    shutil.rmtree(tmpdir)
    return outfile
Exemplo n.º 2
0
def plotFields(fields=None,
               target_fields=None,
               completed_fields=None,
               options_basemap={},
               **kwargs):
    # ADW: Need to be careful about the size of the marker. It
    # does not change with the size of the frame so it is
    # really safest to scale to the size of the zenith circle
    # (see PlotPointings). That said, s=50 is probably roughly ok.
    if fields is None:
        fields = completed_fields[-1]

    if isinstance(fields, np.core.records.record):
        tmp = FieldArray(1)
        tmp[0] = fields
        fields = tmp

    for i, f in enumerate(fields):
        basemap = plotField(fields[i], target_fields, completed_fields,
                            options_basemap, **kwargs)
        if completed_fields is None: completed_fields = FieldArray()
        completed_fields = completed_fields + fields[[i]]
        plt.pause(0.001)

    return basemap
Exemplo n.º 3
0
    def create_wide_fields(self, data, plot=False):
        """ Create the wide field observations """
        logging.info("Creating DEEP fields...")
        BANDS = ['g','i']
        EXPTIME = [90,90]
        TILINGS = [4,4]
        TEFF_MIN = TEFF_MIN_WIDE

        nhexes = len(np.unique(data['TILEID']))
        nbands = len(BANDS)

        nfields = len(data)*nbands

        logging.info("  Number of hexes: %d"%nhexes)
        logging.info("  Filters: %s"%BANDS)
        logging.info("  Exposure time: %s"%EXPTIME)
        logging.info("  Tilings: %s"%TILINGS)

        fields = FieldArray(nfields)
        fields['PROGRAM'] = PROGRAM+'-wide'
        fields['HEX'] = np.repeat(data['TILEID'],nbands)
        fields['TILING'] = np.repeat(data['PASS'],nbands)
        fields['RA'] = np.repeat(data['RA'],nbands)
        fields['DEC'] = np.repeat(data['DEC'],nbands)

        fields['FILTER'] = np.tile(BANDS,len(data))
        fields['EXPTIME'] = np.tile(EXPTIME,len(data))
        fields['PRIORITY'] = fields['TILING']

        sel = self.footprintWIDE(fields['RA'],fields['DEC'])
        sel &= (~self.footprintMilkyWay(fields['RA'],fields['DEC']))
        sel &= (~self.footprintDES(fields['RA'],fields['DEC']))
        sel &= (~self.footprintSMASH(fields['RA'],fields['DEC'],angsep=0.75*DECAM))
        sel &= (~self.footprintMC(fields['RA'],fields['DEC']))
        # Avoid DEEP fields? No.
        #sel &= (~self.footprintDEEP(fields['RA'],fields['DEC']))

        fields = fields[sel]

        frac, depth = self.covered(fields)

        teffmin = pd.DataFrame(fields).merge(TEFF_MIN,on='FILTER').to_records()['TEFF']

        fields['PRIORITY'][depth > teffmin*fields['TILING']*fields['EXPTIME']] = DONE
        # Avoid MagLiteS-II for now
        #fields['PRIORITY'][self.footprintMaglites2(fields['RA'],fields['DEC'])] = DONE

        if plot: self.plot_depth(fields,depth,'delve-wide-%s-gt%i.png')

        logging.info("Number of target fields: %d"%len(fields))

        outfile = 'delve-wide-fields.fits.fz'
        logging.info("Writing %s..."%outfile)
        fields.write(outfile,clobber=True)

        return fields
Exemplo n.º 4
0
    def create_deep_fields2(self, data, plot=False):
        """ DEPRECATED: Create the deep field observations """

        logging.info("Creating DEEP fields...")
        BANDS = ['g','i']
        EXPTIME = [300,300]
        TILINGS = [15,10]

        d = data[data['PASS'] == 1]
        sel = self.footprintDEEP(d['RA'],d['DEC'])
        data = np.copy(d[sel])

        nhexes = len(np.unique(data['TILEID']))
        ntilings = np.sum(TILINGS)
        nbands = len(BANDS)

        nfields = np.sum( np.sum(sel) * np.array(TILINGS))

        logging.info("  Number of hexes: %d"%nhexes)
        logging.info("  Filters: %s"%BANDS)
        logging.info("  Exposure time: %s"%EXPTIME)
        logging.info("  Tilings: %s"%TILINGS)

        tilings = np.array(range(1,TILINGS[0]+1)+range(1,TILINGS[1]+1))
        filters = np.repeat(BANDS,TILINGS)
        exptimes = np.repeat(EXPTIME,TILINGS)

        fields = FieldArray(nfields)
        fields['PROGRAM'] = PROGRAM+'-deep'
        fields['HEX'] = np.repeat(data['TILEID'],ntilings)
        fields['RA'] = np.repeat(data['RA'],ntilings)
        fields['DEC'] = np.repeat(data['DEC'],ntilings)

        fields['EXPTIME'] = np.tile(exptimes,nhexes)
        fields['TILING'] = np.tile(tilings,nhexes)
        fields['FILTER'] = np.tile(filters,nhexes)
        fields['PRIORITY'] = fields['TILING']

        frac, depth = self.covered(fields)
        fields['PRIORITY'][depth > fields['TILING']*fields['EXPTIME']] = DONE

        if plot: self.plot_depth(fields,depth,'delve-deep-%s-gt%i.png')

        logging.info("Number of target fields: %d"%len(fields))

        outfile = 'delve-deep-fields.fits.fz'
        logging.info("Writing %s..."%outfile)
        fields.write(outfile,clobber=True)

        return fields
Exemplo n.º 5
0
def create_fields():
    nfields = 10
    fields = FieldArray(nfields)
    fields['RA'] = np.linspace(3, 359, nfields)
    fields['DEC'] = np.linspace(-89, 89, nfields)
    fields['TILING'] = np.array([1, 1, 1, 2, 2, 2, 3, 3, 4, 4])
    return fields
Exemplo n.º 6
0
def plot_bliss_coverage(fields, outfile=None, **kwargs):
    BANDS = ['g', 'r', 'i', 'z']
    filename = fileio.get_datafile('bliss-target-fields.csv')
    target = FieldArray.read(filename)
    target = target[~np.in1d(target.unique_id, fields.unique_id)]

    fig, ax = plt.subplots(2, 2, figsize=(16, 9))
    plt.subplots_adjust(wspace=0.01,
                        hspace=0.02,
                        left=0.01,
                        right=0.99,
                        bottom=0.01,
                        top=0.99)
    defaults = dict(edgecolor='none', s=12, alpha=0.2, vmin=-1, vmax=2)
    setdefaults(kwargs, defaults)

    for i, b in enumerate(BANDS):
        plt.sca(ax.flat[i])

        f = fields[fields['FILTER'] == b]
        t = target[target['FILTER'] == b]

        bmap = DECamMcBride()
        bmap.draw_des()
        bmap.draw_galaxy(10)

        proj = bmap.proj(t['RA'], t['DEC'])
        bmap.scatter(*proj, c='0.7', **kwargs)

        proj = bmap.proj(f['RA'], f['DEC'])
        bmap.scatter(*proj, c=f['TILING'], cmap=CMAPS[b], **kwargs)
        plt.gca().set_title('BLISS %s-band' % b)
Exemplo n.º 7
0
def plot_progress(outfile=None, **kwargs):
    defaults = dict(edgecolor='none', s=50, vmin=0, vmax=4, cmap='summer_r')
    for k, v in defaults.items():
        kwargs.setdefault(k, v)

    fields = FieldArray.load_database()

    nites = [get_nite(date) for date in fields['DATE']]
    nite = ephem.Date(np.max(nites))
    date = '%d/%02d/%d 00:00:00' % (nite.tuple()[:3])

    fig, basemap = makePlot(date=date,
                            moon=False,
                            airmass=False,
                            center=(0, -90),
                            smash=False)
    proj = basemap.proj(fields['RA'], fields['DEC'])
    basemap.scatter(*proj, c=fields['TILING'], **kwargs)
    colorbar = plt.colorbar()
    colorbar.set_label('Tiling')
    plt.title('Maglites Coverage (%d/%02d/%d)' % nite.tuple()[:3])

    if outfile is not None:
        plt.savefig(outfile, bbox_inches='tight')

    return fig, basemap
Exemplo n.º 8
0
def test_calculate_slew():
    tac = create_tactician()

    # Use a previously completed field
    completed_fields = FieldArray(1)
    completed_fields[0]['RA'] = 137
    completed_fields[0]['DEC'] = -43
    completed_fields[0]['DATE'] = datestring(tac.date)

    #test_slew = np.array([47., 66.6686451, 72.6195061, 103.43996017, 149.98635165, 122.82243022, 61.24007137, 38.8279613, 86.08700171, 122.10797116])
    test_slew = np.array([
        47.6988041, 51.8633918, 37.6586078, 18.1169301, 39.2690875, 78.3913867,
        118.9542319, 153.814957, 153.7471813, 133.7394395
    ])
    zero_slew = np.zeros(len(tac.fields))

    tac.set_completed_fields(completed_fields)
    np.testing.assert_almost_equal(tac.slew,
                                   test_slew,
                                   err_msg='slew from previous field')

    # Set previous field to be < 30 min before date
    completed_fields[0]['DATE'] = datestring(tac.date - 29 * ephem.minute)
    tac.set_completed_fields(completed_fields)
    np.testing.assert_almost_equal(
        tac.slew, test_slew, err_msg='slew not calculated for <30 min gap')

    # Set previous field to be > 30 min before date
    completed_fields[0]['DATE'] = datestring(tac.date - 31 * ephem.minute)
    tac.set_completed_fields(completed_fields)
    np.testing.assert_equal(tac.slew,
                            zero_slew,
                            err_msg='non-zero slew for >30 min gap')

    # Set previous field to None
    tac.set_completed_fields(None)
    np.testing.assert_equal(tac.slew,
                            zero_slew,
                            err_msg='non-zero slew without previous field')
Exemplo n.º 9
0
    def create_deep_fields(self, data, plot=False):
        logging.info("Creating DEEP fields...")
        BANDS = ['g','i']
        EXPTIME = [300,300]
        TILINGS = [15,10]

        dirname = '/Users/kadrlica/delve/observing/data'
        hexbase = 100000 # hex offset
        # target number and filename
        basenames = odict([
            ('SextansB', (000, 'sextansB_fields_v3.txt')),
            ('IC5152',   (100, 'ic5152_fields_v3.txt')),
            ('NGC300',   (200, 'ngc300_fields_v3.txt')),
            ('NGC55',    (300, 'ngc55_fields_v3.txt')),
        ])

        fields = FieldArray()
        for name,(num,basename) in basenames.items():
            filename = os.path.join(dirname,basename)
            target = np.genfromtxt(filename,names=True,dtype=None)
            f = FieldArray(len(target))

            filters = np.tile(BANDS,len(f))
            exptimes = np.tile(EXPTIME,len(f))

            f['RA']     = target['ra']
            f['DEC']    = target['dec']
            f['HEX']    = hexbase + num + target['field']
            f['TILING'] = target['tiling']
            #f['PRIORITY'] = num + target['priority']
            f['PRIORITY'] = target['priority']
            f['PROGRAM'] = PROGRAM+'-deep'

            # Group the fields by hex/tiling
            f = np.repeat(f,len(BANDS))
            f['FILTER'] = filters
            f['EXPTIME'] = exptimes

            for (b,t) in zip(BANDS, TILINGS):
                f = f[~((f['FILTER'] == b) & (f['TILING'] > t))]

            # Not doing these deep fields
            if num in [000,100,200]:
                f['PRIORITY'] *= DONE

            fields = fields + f

        exclude = [100001, 100002, 100003, 100004, 100007, 100008, 100012,
                   100013, 100016, 100017, 100018, 100019]

        fields = fields[~np.in1d(fields['HEX'],exclude)]

        nhexes = len(np.unique(fields['HEX']))
        logging.info("  Number of hexes: %d"%nhexes)
        logging.info("  Filters: %s"%BANDS)
        logging.info("  Exposure time: %s"%EXPTIME)

        if plot: self.plot_depth(fields,depth,'delve-deep-%s-gt%i.png')

        logging.info("Number of target fields: %d"%len(fields))

        outfile = 'delve-deep-fields.fits.fz'
        logging.info("Writing %s..."%outfile)
        fields.write(outfile,clobber=True)

        return fields
Exemplo n.º 10
0
    def prepare_fields(self,
                       infile=None,
                       outfile=None,
                       mode='smash_dither',
                       plot=True,
                       smcnod=False):
        """ Create the list of fields to be targeted by this survey.

        Parameters:
        -----------
        infile : File containing all possible field locations.
        outfile: Output file of selected fields
        mode   : Mode for dithering: 'smash_dither', 'smash_rotate', 'decam_dither', 'none'
        plot   : Create an output plot of selected fields.

        Returns:
        --------
        fields : A FieldArray of the selected fields.
        """
        # Import the dither function here...
        #def dither(ra,dec,dx,dy):
        #    return ra,dec

        if mode is None or mode.lower() == 'none':

            def dither(ra, dec, dx, dy):
                return ra, dec

            TILINGS = [(0, 0), (0, 0), (0, 0), (0, 0)]
        elif mode.lower() == 'smash_dither':
            TILINGS = [(0, 0), (1.0, 0.0), (-1.0, 0.0), (0.0, -0.75)]
            dither = self.smash_dither
        elif mode.lower() == 'smash_rotate':
            TILINGS = [(0, 0), (0.75, 0.75), (-0.75, 0.75), (0.0, -0.75)]
            dither = self.smash_rotate
        elif mode.lower() == 'decam_dither':
            TILINGS = [(0., 0.), (8 / 3. * CCD_X, -11 / 3. * CCD_Y),
                       (8 / 3. * CCD_X, 8 / 3. * CCD_Y), (-8 / 3. * CCD_X, 0.)]
            dither = self.decam_dither

        if infile is None:
            infile = os.path.join(fileio.get_datadir(),
                                  'smash_fields_alltiles.txt')
        data = np.recfromtxt(infile, names=True)

        # Apply footprint selection after tiling/dither
        #sel = obztak.utils.projector.footprint(data['RA'],data['DEC'])

        # This is currently a non-op
        smash_id = data['ID']
        ra = data['RA']
        dec = data['DEC']

        nhexes = len(data)
        #ntilings = len(DECAM_DITHERS)
        ntilings = len(TILINGS)
        nbands = len(BANDS)
        nfields = nhexes * nbands * ntilings

        logging.info("Number of hexes: %d" % nhexes)
        logging.info("Number of tilings: %d" % ntilings)
        logging.info("Number of filters: %d" % nbands)

        fields = FieldArray(nfields)
        fields['HEX'] = np.tile(np.repeat(smash_id, nbands), ntilings)
        fields['PRIORITY'].fill(1)
        fields['TILING'] = np.repeat(np.arange(1, ntilings + 1),
                                     nhexes * nbands)
        fields['FILTER'] = np.tile(BANDS, nhexes * ntilings)

        #for i in range(ntilings):
        for i, tiling in enumerate(TILINGS):
            idx0 = i * nhexes * nbands
            idx1 = idx0 + nhexes * nbands
            ra_dither, dec_dither = dither(ra, dec, tiling[0], tiling[1])
            fields['RA'][idx0:idx1] = np.repeat(ra_dither, nbands)
            fields['DEC'][idx0:idx1] = np.repeat(dec_dither, nbands)

        # Apply footprint selection after tiling/dither
        sel = self.footprint(fields['RA'], fields['DEC'])  # NORMAL OPERATION
        if smcnod:
            # Include SMC northern overdensity fields
            sel_smcnod = self.footprintSMCNOD(fields)  # SMCNOD OPERATION
            sel = sel | sel_smcnod
            #sel = sel_smcnod
            fields['PRIORITY'][sel_smcnod] = 99
        #if True:
        #    # Include 'bridge' region between Magellanic Clouds
        #    sel_bridge = self.footprintBridge(fields['RA'],fields['DEC'])
        #    sel = sel | sel_bridge
        sel = sel & (fields['DEC'] > constants.SOUTHERN_REACH)
        fields = fields[sel]

        logging.info("Number of target fields: %d" % len(fields))

        if plot:
            import pylab as plt
            import obztak.utils.ortho

            plt.ion()

            fig, basemap = obztak.utils.ortho.makePlot('2016/2/11 03:00',
                                                       center=(0, -90),
                                                       airmass=False,
                                                       moon=False)

            proj = obztak.utils.ortho.safeProj(basemap, fields['RA'],
                                               fields['DEC'])
            basemap.scatter(*proj,
                            c=fields['TILING'],
                            edgecolor='none',
                            s=50,
                            cmap='Spectral',
                            vmin=0,
                            vmax=len(TILINGS))
            colorbar = plt.colorbar(label='Tiling')

            if outfile:
                outfig = os.path.splitext(outfile)[0] + '.png'
                fig.savefig(outfig, bbox_inches='tight')
            if not sys.flags.interactive:
                plt.show(block=True)

        if outfile: fields.write(outfile)

        return fields
Exemplo n.º 11
0
    def prepare_fields(self,
                       infile=None,
                       outfile=None,
                       mode='bliss_rotate',
                       plot=True,
                       smcnod=False):
        """Create the list of fields to be targeted by the BLISS survey.

        Selection starts with 3 regions:
        - P9 - Planet 9 region above DES footprint (priority 1)
        - LIGO - Region targeted based on LIGO sensitivity maps (and good for MW)
        - Alfredo - Overlap with Alfredo's eRosita companion survey.

        Fields that have been previously covered by DECam are removed
        from the LIGO and Alfredo fooptrint regions.

        Parameters:
        -----------
        infile : File containing all possible field locations.
        outfile: Output file of selected fields
        mode   : Mode for dithering. default: 'bliss_rotate'
        plot   : Create an output plot of selected fields.

        Returns:
        --------
        fields : A FieldArray of the selected fields.
        """
        # Import the dither function here...
        #def dither(ra,dec,dx,dy):
        #    return ra,dec

        if mode is None or mode.lower() == 'none':

            def dither(ra, dec, dx, dy):
                return ra, dec

            OFFSETS = TILINGS * [(0, 0)]
        elif mode.lower() == 'smash_dither':
            OFFSETS = [(0, 0), (1.0, 0.0), (-1.0, 0.0), (0.0, -0.75)][:TILINGS]
            dither = self.smash_dither
        elif mode.lower() == 'smash_rotate':
            OFFSETS = [(0, 0), (0.75, 0.75), (-0.75, 0.75),
                       (0.0, -0.75)][:TILINGS]
            dither = self.smash_rotate
        elif mode.lower() == 'decam_dither':
            OFFSETS = [(0., 0.), (8 / 3. * CCD_X, -11 / 3. * CCD_Y),
                       (8 / 3. * CCD_X, 8 / 3. * CCD_Y),
                       (-8 / 3. * CCD_X, 0.)][:TILINGS]
            dither = self.decam_dither
        elif mode.lower() == 'coord_rotate':
            OFFSETS = [(0, 0), (153.0, -17.0), (-1.0, 1.0),
                       (0.0, -1.0)][:TILINGS]
            dither = self.coord_rotate
        elif mode.lower() == 'decals_rotate':
            OFFSETS = [(0, 0), (-0.2917, 0.0833), (-0.5861, 0.1333),
                       (-0.8805, 0.1833)][:TILINGS]
            dither = self.decals_rotate
        elif mode.lower() == 'bliss_rotate':
            OFFSETS = [(0, 0), (8 / 3. * CCD_X, -11 / 3. * CCD_Y),
                       (8 / 3. * CCD_X, 8 / 3. * CCD_Y),
                       (-8 / 3. * CCD_X, 0.)][:TILINGS]
            dither = self.decals_rotate
        else:
            msg = "Unrecognized dither mode: %s" % mode
            raise ValueError(msg)
        logging.info("Dither mode: %s" % mode.lower())

        if infile is None:
            #infile = os.path.join(fileio.get_datadir(),'smash_fields_alltiles.txt')
            #infile = os.path.join(fileio.get_datadir(),'ctr-healpy-32-13131.txt')
            infile = os.path.join(fileio.get_datadir(),
                                  'decam-tiles_obstatus.fits')
        #data = np.recfromtxt(infile, names=True)
        raw_data = fitsio.read(infile)
        data = raw_data[(raw_data['PASS'] == 1)]

        # Apply footprint selection after tiling/dither
        #sel = obztak.utils.projector.footprint(data['RA'],data['DEC'])

        # This is currently a non-op
        decals_id = data['TILEID']
        ra = data['RA']
        dec = data['DEC']

        nhexes = len(data)
        #ntilings = len(DECAM_DITHERS)
        ntilings = TILINGS
        nbands = len(BANDS)
        nfields = nhexes * nbands * ntilings

        logging.info("Number of hexes: %d" % nhexes)
        logging.info("Number of tilings: %d" % ntilings)
        logging.info("Number of filters: %d" % nbands)

        fields = FieldArray(nfields)
        fields['HEX'] = np.tile(np.repeat(decals_id, nbands), ntilings)
        fields['PRIORITY'].fill(1)
        fields['TILING'] = np.repeat(np.arange(1, ntilings + 1),
                                     nhexes * nbands)
        fields['FILTER'] = np.tile(BANDS, nhexes * ntilings)

        #for i in range(ntilings):
        for i, offset in enumerate(OFFSETS):
            idx0 = i * nhexes * nbands
            idx1 = idx0 + nhexes * nbands
            ra_dither, dec_dither = dither(ra, dec, offset[0], offset[1])
            #ra_dither = raw_data[raw_data['PASS'] == i+1]['RA']
            #dec_dither = raw_data[raw_data['PASS'] == i+1]['DEC']
            fields['RA'][idx0:idx1] = np.repeat(ra_dither, nbands)
            fields['DEC'][idx0:idx1] = np.repeat(dec_dither, nbands)

        # Apply footprint selection after tiling/dither
        #sel = self.footprint(fields['RA'],fields['DEC']) # NORMAL OPERATION

        # Apply footprint selection after tiling/dither
        p9 = self.planet9(fields['RA'], fields['DEC'])
        ligo = self.ligo_mw(fields['RA'], fields['DEC'])
        alfredo = self.alfredo(fields['RA'], fields['DEC'])
        p9v2 = self.planet9v2(fields['RA'], fields['DEC'])

        fields['PRIORITY'][p9] = 1
        fields['PRIORITY'][ligo] = 2
        fields['PRIORITY'][alfredo] = 3

        #sel = (p9 | ligo | alfredo)
        sel = (p9 | ligo | alfredo | p9v2)

        # Apply telescope constraints
        sel &= (fields['DEC'] > constants.SOUTHERN_REACH)

        # Apply covered fields
        #sel &= self.uncovered(fields['RA'],fields['DEC'],fields['FILTER'])[0]
        # Apply covered fields (but take everything in P9 region)
        uncovered = self.uncovered(fields['RA'], fields['DEC'],
                                   fields['FILTER'])[0]
        sel &= ((p9v2) | (p9 & (fields['RA'] > 180)) | uncovered)

        fields = fields[sel]

        logging.info("Number of target fields: %d" % len(fields))
        logging.debug("Unique priorities: ", np.unique(fields['PRIORITY']))

        if plot:
            import pylab as plt
            from obztak.utils.ortho import makePlot
            from obztak.utils.ortho import DECamOrtho, DECamMcBride

            kwargs = dict(edgecolor='none',
                          cmap='viridis_r',
                          vmin=0,
                          vmax=ntilings)

            fig, ax = plt.subplots(2, 2, figsize=(16, 9))
            plt.subplots_adjust(wspace=0.01,
                                hspace=0.02,
                                left=0.01,
                                right=0.99,
                                bottom=0.01,
                                top=0.99)
            for i, b in enumerate(BANDS):
                plt.sca(ax.flat[i])
                bmap = DECamMcBride()
                bmap.draw_galaxy()
                bmap.draw_des()
                f = fields[fields['FILTER'] == b]
                bmap.scatter(*bmap.proj(f['RA'], f['DEC']),
                             c=COLORS[b],
                             s=15,
                             **kwargs)

            if outfile:
                outfig = os.path.splitext(outfile)[0] + '_mbt.png'
                plt.savefig(outfig, bbox_inches='tight')

            fig, ax = plt.subplots(2, 2, figsize=(10, 10))
            plt.subplots_adjust(wspace=0.05,
                                hspace=0.05,
                                left=0.05,
                                right=0.95,
                                bottom=0.05,
                                top=0.95)
            for i, b in enumerate(BANDS):
                plt.sca(ax.flat[i])
                bmap = DECamOrtho(date='2017/06/02 03:00')
                bmap.draw_galaxy()
                bmap.draw_des()
                f = fields[fields['FILTER'] == b]
                bmap.scatter(*bmap.proj(f['RA'], f['DEC']),
                             c=COLORS[b],
                             s=50,
                             **kwargs)

            if outfile:
                outfig = os.path.splitext(outfile)[0] + '_ortho.png'
                plt.savefig(outfig, bbox_inches='tight')

            if not sys.flags.interactive:
                plt.show(block=True)

        # Just 3rd tiling
        #fields = fields[fields['TILING'] == 3]

        if outfile: fields.write(outfile)

        return fields
Exemplo n.º 12
0
def plotField(field,
              target_fields=None,
              completed_fields=None,
              options_basemap={},
              **kwargs):
    """
    Plot a specific target field.

    Parameters:
    -----------
    field            : The specific field of interest.
    target_fields    : The fields that will be observed
    completed_fields : The fields that have been observed
    options_basemap  : Keyword arguments to the basemap constructor
    kwargs           : Keyword arguments to the matplotlib.scatter function

    Returns:
    --------
    basemap : The basemap object
    """
    if isinstance(field, np.core.records.record):
        tmp = FieldArray(1)
        tmp[0] = field
        field = tmp
    band = field[0]['FILTER']
    cmap = matplotlib.cm.get_cmap(CMAPS[band])
    defaults = dict(marker='H',
                    s=100,
                    edgecolor='',
                    vmin=-1,
                    vmax=4,
                    cmap=cmap)
    #defaults = dict(edgecolor='none', s=50, vmin=0, vmax=4, cmap='summer_r')
    #defaults = dict(edgecolor='none', s=50, vmin=0, vmax=4, cmap='gray_r')
    setdefaults(kwargs, defaults)

    msg = "%s: id=%10s, " % (datestring(field['DATE'][0], 0), field['ID'][0])
    msg += "ra=%(RA)-6.2f, dec=%(DEC)-6.2f, secz=%(AIRMASS)-4.2f" % field[0]
    logging.info(msg)

    defaults = dict(date=field['DATE'][0], name='ortho')
    options_basemap = dict(options_basemap)
    setdefaults(options_basemap, defaults)
    fig, basemap = makePlot(**options_basemap)
    plt.subplots_adjust(left=0.03, right=0.97, bottom=0.03, top=0.97)

    # Plot target fields
    if target_fields is not None and len(target_fields):
        sel = target_fields['FILTER'] == band
        x, y = basemap.proj(target_fields['RA'], target_fields['DEC'])
        kw = dict(kwargs, c='w', edgecolor='0.6', s=0.8 * kwargs['s'])
        basemap.scatter(x[sel], y[sel], **kw)
        kw = dict(kwargs, c='w', edgecolor='0.8', s=0.8 * kwargs['s'])
        basemap.scatter(x[~sel], y[~sel], **kw)

    # Plot completed fields
    if completed_fields is not None and len(completed_fields):
        sel = completed_fields['FILTER'] == band
        x, y = basemap.proj(completed_fields['RA'], completed_fields['DEC'])
        kw = dict(kwargs)
        basemap.scatter(x[~sel], y[~sel], c='0.6', **kw)
        basemap.scatter(x[sel],
                        y[sel],
                        c=completed_fields['TILING'][sel],
                        **kw)

    # Try to draw the colorbar
    try:
        if len(fig.axes) == 2:
            # Draw colorbar in existing axis
            colorbar = plt.colorbar(cax=fig.axes[-1])
        else:
            colorbar = plt.colorbar()
        colorbar.set_label('Tiling (%s-band)' % band)
    except TypeError:
        pass
    plt.sca(fig.axes[0])

    # Show the selected field
    x, y = basemap.proj(field['RA'], field['DEC'])
    kw = dict(kwargs, edgecolor='k')
    basemap.scatter(x, y, c=COLORS[band], **kw)

    return basemap
Exemplo n.º 13
0
    def prepare_fields(self, infile=None, outfile=None, plot=True, **kwargs):
        """ Create the list of fields to be targeted by this survey.

        Parameters:
        -----------
        infile : File containing all possible field locations.
        outfile: Output file of selected fields
        plot   : Create an output plot of selected fields.

        Returns:
        --------
        fields : A FieldArray of the selected fields.
        """

        if infile is None:
            infile = fileio.get_datafile('decam-tiles-bliss.fits.gz')

        # For decals input file
        #data['TILEID'] = np.tile(data['TILEID'][data['PASS'] == 1],len(TILINGS))

        data = fitsio.read(infile)

        # Only take tilings of interest
        data = data[np.in1d(data['PASS'], TILINGS)]

        # Number of unique tiles
        nhexes = len(np.unique(data['TILEID']))
        ntilings = len(TILINGS)
        nbands = len(BANDS)
        nfields = nhexes * nbands * ntilings

        assert nfields == len(data) * nbands

        logging.info("Number of hexes: %d" % nhexes)
        logging.info("Number of tilings: %d" % ntilings)
        logging.info("Number of filters: %d" % nbands)

        fields = FieldArray(nfields)
        fields['HEX'] = np.repeat(data['TILEID'], nbands)
        fields['TILING'] = np.repeat(data['PASS'], nbands)

        fields['FILTER'] = np.tile(BANDS, nhexes * ntilings)
        fields['RA'] = np.repeat(data['RA'], nbands)
        fields['DEC'] = np.repeat(data['DEC'], nbands)

        # Apply footprint selection after tiling/dither
        sel = self.footprint(fields['RA'], fields['DEC'])  # NORMAL OPERATION
        sel = sel & (fields['DEC'] > constants.SOUTHERN_REACH)
        fields = fields[sel]

        # Prioritize fields at high declination
        fields['PRIORITY'][fields['TILING'] == 2] = 2
        fields['PRIORITY'][fields['TILING'] == 3] = 3
        fields['PRIORITY'][fields['TILING'] == 1] = 4
        fields['PRIORITY'][fields['TILING'] == 4] = 5
        #fields['PRIORITY'] = fields['TILING'] + 1
        fields['PRIORITY'][(fields['DEC'] < -70)
                           & np.in1d(fields['TILING'], [2, 3])] -= 1

        logging.info("Number of target fields: %d" % len(fields))

        if plot:
            import pylab as plt
            import obztak.utils.ortho

            plt.ion()

            fig, basemap = obztak.utils.ortho.makePlot('2016/2/11 03:00',
                                                       center=(0, -90),
                                                       airmass=False,
                                                       moon=False)

            proj = basemap.proj(fields['RA'], fields['DEC'])
            basemap.scatter(*proj,
                            c=fields['TILING'],
                            edgecolor='none',
                            s=50,
                            cmap='Spectral',
                            vmin=0,
                            vmax=ntilings)
            colorbar = plt.colorbar(label='Tiling')

            if outfile:
                outfig = os.path.splitext(outfile)[0] + '.png'
                fig.savefig(outfig, bbox_inches='tight')
            if not sys.flags.interactive:
                plt.show(block=True)

        if outfile:
            logging.info("Writing %s..." % outfile)
            fields.write(outfile)

        return fields