Esempio n. 1
0
    def _mouse_move_cb(self, viewer, button, data_x, data_y):
        """
        Callback to display position in RA/DEC deg.
        """
        if self.cursor is None:  # no-op
            return

        image = viewer.get_image()
        if image is not None:
            ix = int(data_x + 0.5)
            iy = int(data_y + 0.5)
            try:
                imval = viewer.get_data(ix, iy)
                imval = '{:8.3f}'.format(imval)
            except Exception:
                imval = 'N/A'

            val = 'X: {:.2f}, Y: {:.2f}'.format(data_x + self._pixel_offset,
                                                data_y + self._pixel_offset)
            if image.wcs.wcs is not None:
                try:
                    ra, dec = image.pixtoradec(data_x, data_y)
                    val += ' (RA: {}, DEC: {})'.format(raDegToString(ra),
                                                       decDegToString(dec))
                except Exception:
                    val += ' (RA, DEC: WCS error)'

            val += ', value: {}'.format(imval)
            self._jup_coord.value = val
Esempio n. 2
0
File: dp.py Progetto: rajul/ginga
def recycle_image(image, ra_deg, dec_deg, fov_deg, px_scale, rot_deg,
                  cdbase=[1, 1], logger=None, pfx='dp'):

    # ra and dec in traditional format
    ra_txt = wcs.raDegToString(ra_deg, format='%02d:%02d:%06.3f')
    dec_txt = wcs.decDegToString(dec_deg, format='%s%02d:%02d:%05.2f')

    header = image.get_header()
    pointing = OrderedDict((('RA', ra_txt),
                            ('DEC', dec_txt),
                            ))
    header.update(pointing)

    # Update WCS keywords and internal wcs objects
    wd, ht = image.get_size()
    crpix1 = wd // 2
    crpix2 = ht // 2
    wcshdr = wcs.simple_wcs(crpix1, crpix2, ra_deg, dec_deg, px_scale,
                            rot_deg, cdbase=cdbase)
    header.update(wcshdr)
    # this should update the wcs
    image.update_keywords(header)

    # zero out data array
    data = image.get_data()
    data.fill(0)

    ## # Create new image container sharing same data
    ## new_image = AstroImage.AstroImage(data, logger=logger)
    ## new_image.update_keywords(header)
    ## # give the image a name
    ## get_image_name(new_image, pfx=pfx)
    new_image = image

    return new_image
Esempio n. 3
0
def create_blank_image(ra_deg,
                       dec_deg,
                       fov_deg,
                       px_scale,
                       rot_deg,
                       cdbase=[1, 1],
                       dtype=None,
                       logger=None,
                       pfx='dp'):

    # ra and dec in traditional format
    ra_txt = wcs.raDegToString(ra_deg, format='%02d:%02d:%06.3f')
    dec_txt = wcs.decDegToString(dec_deg, format='%s%02d:%02d:%05.2f')

    # Create an empty image
    imagesize = int(round(fov_deg / px_scale))
    # round to an even size
    if imagesize % 2 != 0:
        imagesize += 1
    ## # round to an odd size
    ## if imagesize % 2 == 0:
    ##     imagesize += 1
    width = height = imagesize

    if dtype is None:
        dtype = numpy.float32
    data = numpy.zeros((height, width), dtype=dtype)

    crpix = float(imagesize // 2)
    header = OrderedDict((
        ('SIMPLE', True),
        ('BITPIX', -32),
        ('EXTEND', True),
        ('NAXIS', 2),
        ('NAXIS1', imagesize),
        ('NAXIS2', imagesize),
        ('RA', ra_txt),
        ('DEC', dec_txt),
        ('EQUINOX', 2000.0),
        ('OBJECT', 'MOSAIC'),
        ('LONPOLE', 180.0),
    ))

    # Add basic WCS keywords
    wcshdr = wcs.simple_wcs(crpix,
                            crpix,
                            ra_deg,
                            dec_deg,
                            px_scale,
                            rot_deg,
                            cdbase=cdbase)
    header.update(wcshdr)

    # Create image container
    image = AstroImage.AstroImage(data, logger=logger)
    image.update_keywords(header)
    # give the image a name
    get_image_name(image, pfx=pfx)

    return image
Esempio n. 4
0
def normalize_radec_str(ra_str, dec_str):
    if ra_str is None or ra_str == '':
        ra = ra_str
    else:
        ra = wcs.raDegToString(wcs.hmsStrToDeg(ra_str))
    if dec_str is None or dec_str == '':
        dec = dec_str
    else:
        dec = wcs.decDegToString(wcs.dmsStrToDeg(dec_str))
    return (ra, dec)
Esempio n. 5
0
def normalize_radec_str(ra_str, dec_str):
    if ra_str is None or ra_str == '':
        ra = ra_str
    else:
        ra = wcs.raDegToString(wcs.hmsStrToDeg(ra_str))
    if dec_str is None or dec_str == '':
        dec = dec_str
    else:
        dec = wcs.decDegToString(wcs.dmsStrToDeg(dec_str))
    return (ra, dec)
Esempio n. 6
0
    def _calc_axes(self, viewer, image, rot_deg, swapxy):
        self._cur_image = image
        self._cur_rot = rot_deg
        self._cur_swap = swapxy

        if not isinstance(image, AstroImage) or not image.has_valid_wcs():
            self.logger.debug(
                'WCSAxes can only be displayed for AstroImage with valid WCS')
            return []

        min_imsize = min(image.width, image.height)
        if min_imsize <= 0:
            self.logger.debug('Cannot draw WCSAxes on image with 0 dim')
            return []

        # Approximate bounding box in RA/DEC space
        xmax = image.width - 1
        ymax = image.height - 1
        try:
            radec = image.wcs.datapt_to_system(
                [[0, 0], [0, ymax], [xmax, 0], [xmax, ymax]],
                naxispath=image.naxispath)
        except Exception as e:
            self.logger.warning('WCSAxes failed: {}'.format(str(e)))
            return []
        ra_min, dec_min = radec.ra.min().deg, radec.dec.min().deg
        ra_max, dec_max = radec.ra.max().deg, radec.dec.max().deg
        ra_size = ra_max - ra_min
        dec_size = dec_max - dec_min

        # Calculate positions of RA/DEC lines
        d_ra = ra_size / (self.num_ra + 1)
        d_dec = dec_size / (self.num_dec + 1)
        ra_arr = np.arange(ra_min + d_ra, ra_max - d_ra * 0.5, d_ra)
        dec_arr = np.arange(dec_min + d_dec, dec_max - d_ra * 0.5, d_dec)

        # RA/DEC step size for each vector
        d_ra_step = ra_size * self._pix_res / min_imsize
        d_dec_step = dec_size * self._pix_res / min_imsize

        # Create Path objects
        objs = []

        for cur_ra in ra_arr:
            crds = [[cur_ra, cur_dec] for cur_dec in
                    np.arange(dec_min, dec_max + d_dec_step, d_dec_step)]
            lbl = raDegToString(cur_ra)
            objs += self._get_path(viewer, image, crds, lbl, 1)
        for cur_dec in dec_arr:
            crds = [[cur_ra, cur_dec] for cur_ra in
                    np.arange(ra_min, ra_max + d_ra_step, d_ra_step)]
            lbl = decDegToString(cur_dec)
            objs += self._get_path(viewer, image, crds, lbl, 0)

        return objs
Esempio n. 7
0
    def get_ruler_distances(self, viewer):
        mode = self.units.lower()
        points = self.get_data_points()
        x1, y1 = points[0]
        x2, y2 = points[1]

        text = Bunch.Bunch(dict().fromkeys(['x', 'y', 'h', 'b', 'e'],
                                           'BAD WCS'))
        try:
            image = viewer.get_image()
            res = wcs.get_ruler_distances(image, points[0], points[1])
            text.res = res

            if mode == 'arcmin':
                text.h = self.get_arcmin(res.dh_deg)
                text.x = self.get_arcmin(res.dx_deg)
                text.y = self.get_arcmin(res.dy_deg)
                text.b = ("%s, %s" % (wcs.raDegToString(res.ra_org),
                                      wcs.decDegToString(res.dec_org)))
                text.e = ("%s, %s" % (wcs.raDegToString(res.ra_dst),
                                      wcs.decDegToString(res.dec_dst)))

            elif mode == 'degrees':
                text.h = ("%.8f" % res.dh_deg)
                text.x = ("%.8f" % res.dx_deg)
                text.y = ("%.8f" % res.dy_deg)
                text.b = ("%.3f, %.3f" % (res.ra_org, res.dec_org))
                text.e = ("%.3f, %.3f" % (res.ra_dst, res.dec_dst))

            else:
                text.x = ("%.3f" % abs(res.dx_pix))
                text.y = ("%.3f" % abs(res.dy_pix))
                text.h = ("%.3f" % res.dh_pix)
                text.b = ("%.3f, %.3f" % (res.x1, res.y1))
                text.e = ("%.3f, %.3f" % (res.x2, res.y2))

        except Exception as e:
            print(str(e))
            pass

        return text
Esempio n. 8
0
    def _calc_axes(self, viewer, image, rot_deg, swapxy):
        self._cur_image = image
        self._cur_rot = rot_deg
        self._cur_swap = swapxy

        if not isinstance(image, AstroImage) or not image.has_valid_wcs():
            return []

        # Approximate bounding box in RA/DEC space
        xmax = image.width - 1
        ymax = image.height - 1
        try:
            radec = image.wcs.datapt_to_system(
                [[0, 0], [0, ymax], [xmax, 0], [xmax, ymax]],
                naxispath=image.naxispath)
        except Exception:
            return []
        ra_min, dec_min = radec.ra.min().deg, radec.dec.min().deg
        ra_max, dec_max = radec.ra.max().deg, radec.dec.max().deg
        ra_size = ra_max - ra_min
        dec_size = dec_max - dec_min

        # Calculate positions of RA/DEC lines
        d_ra = ra_size / (self.num_ra + 1)
        d_dec = dec_size / (self.num_dec + 1)
        ra_arr = np.arange(ra_min + d_ra, ra_max - d_ra * 0.5, d_ra)
        dec_arr = np.arange(dec_min + d_dec, dec_max - d_ra * 0.5, d_dec)

        # RA/DEC step size for each vector
        min_imsize = min(image.width, image.height)
        d_ra_step = ra_size * self._pix_res / min_imsize
        d_dec_step = dec_size * self._pix_res / min_imsize

        # Create Path objects
        objs = []

        for cur_ra in ra_arr:
            crds = [[cur_ra, cur_dec]
                    for cur_dec in np.arange(dec_min, dec_max +
                                             d_dec_step, d_dec_step)]
            lbl = raDegToString(cur_ra)
            objs += self._get_path(viewer, image, crds, lbl, 1)
        for cur_dec in dec_arr:
            crds = [[cur_ra, cur_dec]
                    for cur_ra in np.arange(ra_min, ra_max +
                                            d_ra_step, d_ra_step)]
            lbl = decDegToString(cur_dec)
            objs += self._get_path(viewer, image, crds, lbl, 0)

        return objs
Esempio n. 9
0
    def _get_dss_image(self):
        try:
            fov_deg = float(self.w.fov.get_text())

            # width and height are specified in arcmin
            sgn, deg, mn, sec = wcs.degToDms(fov_deg)
            wd = deg * 60.0 + float(mn) + sec / 60.0
            sgn, deg, mn, sec = wcs.degToDms(fov_deg)
            ht = deg * 60.0 + float(mn) + sec / 60.0

            # coordinates
            ra_txt = wcs.raDegToString(self.ctr_ra_deg)
            dec_txt = wcs.decDegToString(self.ctr_dec_deg)

            # these are the params to DSS
            params = dict(ra=ra_txt, dec=dec_txt, width=wd, height=ht)

            # Query the server and download file
            srvbank = self.fv.get_ServerBank()
            filename = "sky-" + str(self.dsscnt) + ".fits"
            self.dsscnt = (self.dsscnt + 1) % 5
            filepath = os.path.join(self.tmpdir, filename)
            try:
                os.remove(filepath)
            except Exception as e:
                self.logger.warn("failed to remove tmp file '%s': %s" % (filepath, str(e)))
            try:
                dstpath = srvbank.getImage(self.servername, filepath, **params)

            except Exception as e:
                errmsg = "Failed to download sky image: %s" % (str(e))
                self.fv.gui_do(self.fv.show_error, errmsg)
                return

            try:
                image = self.fv.load_image(dstpath)

            except Exception as e:
                errmsg = "Failed to load downloaded sky image: %s" % (str(e))
                self.fv.gui_do(self.fv.show_error, errmsg)
                return

            image.set(nothumb=True)
            self.fv.gui_do(self.fitsimage.set_image, image)

        finally:
            self.fv.gui_do(self.fitsimage.onscreen_message_off)
Esempio n. 10
0
File: dp.py Progetto: hdfeos/ginga
def create_blank_image(ra_deg, dec_deg, fov_deg, px_scale, rot_deg,
                       cdbase=[1, 1], dtype=None, logger=None, pfx='dp'):

    # ra and dec in traditional format
    ra_txt = wcs.raDegToString(ra_deg, format='%02d:%02d:%06.3f')
    dec_txt = wcs.decDegToString(dec_deg, format='%s%02d:%02d:%05.2f')

    # Create an empty image
    imagesize = int(round(fov_deg / px_scale))
    # round to an even size
    if imagesize % 2 != 0:
        imagesize += 1
    ## # round to an odd size
    ## if imagesize % 2 == 0:
    ##     imagesize += 1
    width = height = imagesize

    if dtype is None:
        dtype = numpy.float32
    data = numpy.zeros((height, width), dtype=dtype)

    crpix = float(imagesize // 2)
    header = OrderedDict((('SIMPLE', True),
                          ('BITPIX', -32),
                          ('EXTEND', True),
                          ('NAXIS', 2),
                          ('NAXIS1', imagesize),
                          ('NAXIS2', imagesize),
                          ('RA', ra_txt),
                          ('DEC', dec_txt),
                          ('EQUINOX', 2000.0),
                          ('OBJECT', 'MOSAIC'),
                          ('LONPOLE', 180.0),
                          ))

    # Add basic WCS keywords
    wcshdr = wcs.simple_wcs(crpix, crpix, ra_deg, dec_deg, px_scale,
                            rot_deg, cdbase=cdbase)
    header.update(wcshdr)

    # Create image container
    image = AstroImage.AstroImage(data, logger=logger)
    image.update_keywords(header)
    # give the image a name
    get_image_name(image, pfx=pfx)

    return image
Esempio n. 11
0
    def toStar(self, data, ext, magfield):
        try:
            mag = float(data[magfield])
        except:
            mag = 0.0

        # Make sure we have at least these Ginga standard fields defined
        d = { 'name':         data[ext['id']],
              'ra_deg':       float(data[ext['ra']]),
              'dec_deg':      float(data[ext['dec']]),
              'mag':          mag,
              'preference':   0.0,
              'priority':     0,
              'description':  'fake magnitude' }
        data.update(d)
        data['ra'] = wcs.raDegToString(data['ra_deg'])
        data['dec'] = wcs.decDegToString(data['dec_deg'])
        return Star(**data)
Esempio n. 12
0
    def _update_pan_coords(self):
        pan_coord = self.t_.get('pan_coord', 'data')
        pan_x, pan_y = self.fitsimage.get_pan(coord=pan_coord)
        #self.logger.debug("updating pan coords (%s) %f %f" % (pan_coord, pan_x, pan_y))
        if pan_coord == 'wcs':
            use_sex = self.w.wcs_sexagesimal.get_state()
            if use_sex:
                pan_x = wcs.raDegToString(pan_x, format='%02d:%02d:%010.7f')
                pan_y = wcs.decDegToString(pan_y, format='%s%02d:%02d:%09.7f')
        else:
            coord_offset = self.fv.settings.get('pixel_coords_offset', 0.0)
            pan_x += coord_offset
            pan_y += coord_offset

        self.w.pan_x.set_text(str(pan_x))
        self.w.pan_y.set_text(str(pan_y))

        index = self.pancoord_options.index(pan_coord)
        self.w.pan_coord.set_index(index)
Esempio n. 13
0
    def _update_pan_coords(self):
        pan_coord = self.t_.get('pan_coord', 'data')
        pan_x, pan_y = self.fitsimage.get_pan(coord=pan_coord)
        #print("updating pan coords (%s) %f %f" % (pan_coord, pan_x, pan_y))
        if pan_coord == 'wcs':
            use_sex = self.w.wcs_sexagesimal.get_state()
            if use_sex:
                pan_x = wcs.raDegToString(pan_x, format='%02d:%02d:%010.7f')
                pan_y = wcs.decDegToString(pan_y, format='%s%02d:%02d:%09.7f')
        else:
            coord_offset = self.fv.settings.get('pixel_coords_offset', 0.0)
            pan_x += coord_offset
            pan_y += coord_offset

        self.w.pan_x.set_text(str(pan_x))
        self.w.pan_y.set_text(str(pan_y))

        index = self.pancoord_options.index(pan_coord)
        self.w.pan_coord.set_index(index)
Esempio n. 14
0
    def toStar(self, data, ext, magfield):
        try:
            mag = float(data[magfield])
        except:
            mag = 0.0

        # Make sure we have at least these Ginga standard fields defined
        d = {
            "name": data[ext["id"]],
            "ra_deg": float(data[ext["ra"]]),
            "dec_deg": float(data[ext["dec"]]),
            "mag": mag,
            "preference": 0.0,
            "priority": 0,
            "description": "fake magnitude",
        }
        data.update(d)
        data["ra"] = wcs.raDegToString(data["ra_deg"])
        data["dec"] = wcs.decDegToString(data["dec_deg"])
        return Star(**data)
Esempio n. 15
0
    def toStar(self, data, ext, magfield):
        try:
            mag = float(data[magfield])
        except Exception:
            mag = 0.0

        # Make sure we have at least these Ginga standard fields defined
        d = {
            'name': data[ext['id']],
            'ra_deg': float(data[ext['ra']]),
            'dec_deg': float(data[ext['dec']]),
            'mag': mag,
            'preference': 0.0,
            'priority': 0,
            'description': 'fake magnitude'
        }
        data.update(d)
        data['ra'] = wcs.raDegToString(data['ra_deg'])
        data['dec'] = wcs.decDegToString(data['dec_deg'])
        return Star(**data)
Esempio n. 16
0
    def _mouse_move_cb(self, viewer, button, data_x, data_y):
        """
        Callback to display position in RA/DEC deg.
        """
        if self.cursor is None:  # no-op
            return

        image = viewer.get_image()
        if image is not None:
            ix = int(data_x + 0.5)
            iy = int(data_y + 0.5)
            try:
                imval = viewer.get_data(ix, iy)
            except Exception:
                imval = 'N/A'

            # Same as setting pixel_coords_offset=1 in general.cfg
            val = 'X: {:.2f}, Y:{:.2f}'.format(data_x + 1, data_y + 1)
            if image.wcs.wcs is not None:
                ra, dec = image.pixtoradec(data_x, data_y)
                val += ' (RA: {}, DEC: {})'.format(raDegToString(ra),
                                                   decDegToString(dec))
            val += ', value: {}'.format(imval)
            self._jup_coord.value = val
Esempio n. 17
0
    def search(self, **params):
        self.logger.debug("search params=%s" % (str(params)))
        url = self.base_url % params

        data = self.fetch(url, filepath=None)
        data = data.decode("utf8")

        lines = data.split("\n")
        offset = 0
        while offset < len(lines):
            line = lines[offset].strip()
            print(line)
            offset += 1
            if line.startswith("-"):
                break
        self.logger.debug("offset=%d" % (offset))

        results = []
        table = [lines[offset - 2]]

        for line in lines[offset:]:
            line = line.strip()
            # print ">>>", line
            if (len(line) == 0) or line.startswith("#"):
                continue
            elts = line.split()
            if len(elts) < 3:
                continue
            table.append(line)

            try:
                name = elts[self.index["name"]]
                ra = elts[self.index["ra"]]
                dec = elts[self.index["dec"]]
                mag = float(elts[self.index["mag"]])
                # print name

                if (self.format == "deg") or not (":" in ra):
                    # Assume RA and DEC are in degrees
                    ra_deg = float(ra)
                    dec_deg = float(dec)
                else:
                    # Assume RA and DEC are in standard string notation
                    ra_deg = wcs.hmsStrToDeg(ra)
                    dec_deg = wcs.dmsStrToDeg(dec)

                # convert ra/dec via EQUINOX change if catalog EQUINOX is
                # not the same as our default one (2000)
                if cmp(self.equinox, 2000.0) != 0:
                    ra_deg, dec_deg = wcs.eqToEq2000(ra_deg, dec_deg, self.equinox)

                ra_txt = wcs.raDegToString(ra_deg, format="%02d:%02d:%06.3f")
                dec_txt = wcs.decDegToString(dec_deg, format="%s%02d:%02d:%05.2f")
                self.logger.debug("STAR %s AT ra=%s dec=%s mag=%f" % (name, ra_txt, dec_txt, mag))

                results.append(
                    Star(
                        name=name,
                        ra_deg=ra_deg,
                        dec_deg=dec_deg,
                        ra=ra_txt,
                        dec=dec_txt,
                        mag=mag,
                        preference=0.0,
                        priority=0,
                        description="",
                    )
                )

            except Exception as e:
                print(str(e))
                self.logger.error("Error parsing catalog query results: %s" % (str(e)))

        # metadata about the list
        columns = [
            ("Name", "name"),
            ("RA", "ra"),
            ("DEC", "dec"),
            ("Mag", "mag"),
            ("Preference", "preference"),
            ("Priority", "priority"),
            ("Description", "description"),
        ]
        info = Bunch.Bunch(columns=columns, color="Mag")

        return (results, info)
Esempio n. 18
0
def create_blank_image(ra_deg, dec_deg, fov_deg, px_scale, rot_deg,
                       cdbase=[1, 1], dtype=None, logger=None, pfx='dp',
                       mmap_path=None, mmap_mode='w+'):

    # ra and dec in traditional format
    ra_txt = wcs.raDegToString(ra_deg, format='%02d:%02d:%06.3f')
    dec_txt = wcs.decDegToString(dec_deg, format='%s%02d:%02d:%05.2f')

    if np.isscalar(px_scale):
        px_wd_scale, px_ht_scale = (px_scale, px_scale)
    else:
        px_wd_scale, px_ht_scale = px_scale

    # Create an empty image
    if np.isscalar(fov_deg):
        fov_wd_deg, fov_ht_deg = (fov_deg, fov_deg)
    else:
        fov_wd_deg, fov_ht_deg = fov_deg

    width = int(round(fov_wd_deg / px_wd_scale))
    height = int(round(fov_ht_deg / px_ht_scale))
    # round to an even size
    if width % 2 != 0:
        width += 1
    if height % 2 != 0:
        height += 1

    if dtype is None:
        dtype = np.float32
    if mmap_path is None:
        data = np.zeros((height, width), dtype=dtype)

    else:
        data = np.memmap(mmap_path, dtype=dtype, mode=mmap_mode,
                         shape=(height, width))

    crpix1 = float(width // 2)
    crpix2 = float(height // 2)
    header = OrderedDict((('SIMPLE', True),
                          ('BITPIX', -32),
                          ('EXTEND', True),
                          ('NAXIS', 2),
                          ('NAXIS1', width),
                          ('NAXIS2', height),
                          ('RA', ra_txt),
                          ('DEC', dec_txt),
                          ('EQUINOX', 2000.0),
                          ('OBJECT', 'MOSAIC'),
                          ('LONPOLE', 180.0),
                          ))

    # Add basic WCS keywords
    wcshdr = wcs.simple_wcs(crpix1, crpix2, ra_deg, dec_deg,
                            (px_wd_scale, px_ht_scale),
                            rot_deg, cdbase=cdbase)
    header.update(wcshdr)

    # Create image container
    image = AstroImage.AstroImage(data, logger=logger)
    image.update_keywords(header)
    # give the image a name
    get_image_name(image, pfx=pfx)

    return image
Esempio n. 19
0
    def search(self, **params):
        self.logger.debug("search params=%s" % (str(params)))
        url = self.base_url % params

        data = self.fetch(url, filepath=None)
        data = data.decode("utf8")

        lines = data.split('\n')
        offset = 0
        while offset < len(lines):
            line = lines[offset].strip()
            #print(line)
            offset += 1
            if line.startswith('-'):
                break
        self.logger.debug("offset=%d" % (offset))

        results = []
        table = [lines[offset-2]]

        for line in lines[offset:]:
            line = line.strip()
            #print(line)
            if (len(line) == 0) or line.startswith('#'):
                continue
            elts = line.split()
            if (len(elts) < 3):
                continue
            table.append(line)

            try:
                name = elts[self.index['name']]
                ra = elts[self.index['ra']]
                dec = elts[self.index['dec']]
                mag = float(elts[self.index['mag']])
                #print name

                if (self.format == 'deg') or not (':' in ra):
                    # Assume RA and DEC are in degrees
                    ra_deg = float(ra)
                    dec_deg = float(dec)
                else:
                    # Assume RA and DEC are in standard string notation
                    ra_deg = wcs.hmsStrToDeg(ra)
                    dec_deg = wcs.dmsStrToDeg(dec)

                # convert ra/dec via EQUINOX change if catalog EQUINOX is
                # not the same as our default one (2000)
                if cmp(self.equinox, 2000.0) != 0:
                    ra_deg, dec_deg = wcs.eqToEq2000(ra_deg, dec_deg,
                                                     self.equinox)

                ra_txt = wcs.raDegToString(ra_deg, format='%02d:%02d:%06.3f')
                dec_txt = wcs.decDegToString(dec_deg,
                                               format='%s%02d:%02d:%05.2f')
                self.logger.debug("STAR %s AT ra=%s dec=%s mag=%f" % (
                    name, ra_txt, dec_txt, mag))

                results.append(Star(name=name, ra_deg=ra_deg, dec_deg=dec_deg,
                                    ra=ra_txt, dec=dec_txt, mag=mag,
                                    preference=0.0, priority=0,
                                    description=''))

            except Exception as e:
                self.logger.error("Error parsing catalog query results: %s" % (
                    str(e)))

        # metadata about the list
        columns = [('Name', 'name'),
                   ('RA', 'ra'),
                   ('DEC', 'dec'),
                   ('Mag', 'mag'),
                   ('Preference', 'preference'),
                   ('Priority', 'priority'),
                   ('Description', 'description'),
                   ]
        info = Bunch.Bunch(columns=columns, color='Mag')

        return (results, info)
Esempio n. 20
0
def create_blank_image(ra_deg,
                       dec_deg,
                       fov_deg,
                       px_scale,
                       rot_deg,
                       cdbase=[1, 1],
                       dtype=None,
                       logger=None,
                       pfx='dp',
                       mmap_path=None,
                       mmap_mode='w+'):

    # ra and dec in traditional format
    ra_txt = wcs.raDegToString(ra_deg, format='%02d:%02d:%06.3f')
    dec_txt = wcs.decDegToString(dec_deg, format='%s%02d:%02d:%05.2f')

    if np.isscalar(px_scale):
        px_wd_scale, px_ht_scale = (px_scale, px_scale)
    else:
        px_wd_scale, px_ht_scale = px_scale

    # Create an empty image
    if np.isscalar(fov_deg):
        fov_wd_deg, fov_ht_deg = (fov_deg, fov_deg)
    else:
        fov_wd_deg, fov_ht_deg = fov_deg

    width = int(round(fov_wd_deg / px_wd_scale))
    height = int(round(fov_ht_deg / px_ht_scale))
    # round to an even size
    if width % 2 != 0:
        width += 1
    if height % 2 != 0:
        height += 1

    if dtype is None:
        dtype = np.float32
    if mmap_path is None:
        data = np.zeros((height, width), dtype=dtype)

    else:
        data = np.memmap(mmap_path,
                         dtype=dtype,
                         mode=mmap_mode,
                         shape=(height, width))

    crpix1 = float(width // 2)
    crpix2 = float(height // 2)
    header = OrderedDict((
        ('SIMPLE', True),
        ('BITPIX', -32),
        ('EXTEND', True),
        ('NAXIS', 2),
        ('NAXIS1', width),
        ('NAXIS2', height),
        ('RA', ra_txt),
        ('DEC', dec_txt),
        ('EQUINOX', 2000.0),
        ('OBJECT', 'MOSAIC'),
        ('LONPOLE', 180.0),
    ))

    # Add basic WCS keywords
    wcshdr = wcs.simple_wcs(crpix1,
                            crpix2,
                            ra_deg,
                            dec_deg, (px_wd_scale, px_ht_scale),
                            rot_deg,
                            cdbase=cdbase)
    header.update(wcshdr)

    # Create image container
    image = AstroImage.AstroImage(data, logger=logger)
    image.update_keywords(header)
    # give the image a name
    get_image_name(image, pfx=pfx)

    return image
Esempio n. 21
0
 def _set_radec(self, ra_deg, dec_deg):
     ra_txt = wcs.raDegToString(ra_deg)
     self.w.ra.set_text(ra_txt)
     dec_txt = wcs.decDegToString(dec_deg)
     self.w.dec.set_text(dec_txt)
     return ra_txt, dec_txt
Esempio n. 22
0
    def search(self, **params):
        self.logger.debug("search params=%s" % (str(params)))
        url = self.base_url % params

        data = self.fetch(url, filepath=None)
        data = data.decode("utf8")

        lines = data.split('\n')
        offset = 0
        while offset < len(lines):
            line = lines[offset].strip()
            # print(line)
            offset += 1
            if line.startswith('-'):
                break
        self.logger.debug("offset=%d" % (offset))

        results = []
        table = [lines[offset - 2]]

        for line in lines[offset:]:
            line = line.strip()
            # print(line)
            if (len(line) == 0) or line.startswith('#'):
                continue
            elts = line.split()
            if (len(elts) < 3):
                continue
            table.append(line)

            try:
                name = elts[self.index['name']]
                ra = elts[self.index['ra']]
                dec = elts[self.index['dec']]
                mag = float(elts[self.index['mag']])
                # print(name)

                if (self.format == 'deg') or not (':' in ra):
                    # Assume RA and DEC are in degrees
                    ra_deg = float(ra)
                    dec_deg = float(dec)
                else:
                    # Assume RA and DEC are in standard string notation
                    ra_deg = wcs.hmsStrToDeg(ra)
                    dec_deg = wcs.dmsStrToDeg(dec)

                # convert ra/dec via EQUINOX change if catalog EQUINOX is
                # not the same as our default one (2000)
                if self.equinox != 2000.0:
                    ra_deg, dec_deg = wcs.eqToEq2000(ra_deg, dec_deg,
                                                     self.equinox)

                ra_txt = wcs.raDegToString(ra_deg, format='%02d:%02d:%06.3f')
                dec_txt = wcs.decDegToString(dec_deg,
                                             format='%s%02d:%02d:%05.2f')
                self.logger.debug("STAR %s AT ra=%s dec=%s mag=%f" %
                                  (name, ra_txt, dec_txt, mag))

                results.append(
                    Star(name=name,
                         ra_deg=ra_deg,
                         dec_deg=dec_deg,
                         ra=ra_txt,
                         dec=dec_txt,
                         mag=mag,
                         preference=0.0,
                         priority=0,
                         description=''))

            except Exception as e:
                self.logger.error("Error parsing catalog query results: %s" %
                                  (str(e)))

        # metadata about the list
        columns = [
            ('Name', 'name'),
            ('RA', 'ra'),
            ('DEC', 'dec'),
            ('Mag', 'mag'),
            ('Preference', 'preference'),
            ('Priority', 'priority'),
            ('Description', 'description'),
        ]
        info = Bunch.Bunch(columns=columns, color='Mag')

        return (results, info)