Esempio n. 1
0
    def interpolate_at_skydir(self, skydir):

        coordsys = wcs_utils.get_coordsys(self.wcs)
        if coordsys == 'CEL':
            skydir = skydir.transform_to('icrs')
            return self.interpolate(skydir.ra.deg, skydir.dec.deg)
        else:
            skydir = skydir.transform_to('galactic')
            return self.interpolate(skydir.l.deg, skydir.b.deg)
Esempio n. 2
0
    def interpolate_at_skydir(self, skydir):

        coordsys = wcs_utils.get_coordsys(self.wcs)
        if coordsys == 'CEL':
            skydir = skydir.transform_to('icrs')
            return self.interpolate(skydir.ra.deg, skydir.dec.deg)
        else:
            skydir = skydir.transform_to('galactic')
            return self.interpolate(skydir.l.deg, skydir.b.deg)
Esempio n. 3
0
    def _scan_position(self, name, **kwargs):

        saved_state = LikelihoodState(self.like)

        skydir = kwargs.pop('skydir', self.roi[name].skydir)
        scan_cdelt = kwargs.pop('scan_cdelt', 0.02)
        nstep = kwargs.pop('nstep', 5)
        use_cache = kwargs.get('use_cache', True)
        use_pylike = kwargs.get('use_pylike', False)
        optimizer = kwargs.get('optimizer', {})

        # Fit without source
        self.zero_source(name, loglevel=logging.DEBUG)
        fit_output_nosrc = self._fit(loglevel=logging.DEBUG, **optimizer)
        self.unzero_source(name, loglevel=logging.DEBUG)
        saved_state.restore()
        self.free_norm(name, loglevel=logging.DEBUG)

        lnlmap = WcsNDMap.create(skydir=skydir,
                                 binsz=scan_cdelt,
                                 npix=(nstep, nstep),
                                 frame=wcs_utils.coordsys_to_frame(
                                     wcs_utils.get_coordsys(self.geom.wcs)))

        src = self.roi.copy_source(name)

        if use_cache and not use_pylike:
            self._create_srcmap_cache(src.name, src)

        coord = MapCoord.create(lnlmap.geom.get_coord(flat=True),
                                frame=lnlmap.geom.frame)
        scan_skydir = coord.skycoord.icrs
        for lon, lat, ra, dec in zip(coord.lon, coord.lat, scan_skydir.ra.deg,
                                     scan_skydir.dec.deg):

            spatial_pars = {'ra': ra, 'dec': dec}
            self.set_source_morphology(name,
                                       spatial_pars=spatial_pars,
                                       use_pylike=use_pylike)
            fit_output = self._fit(loglevel=logging.DEBUG, **optimizer)
            lnlmap.set_by_coord((lon, lat), fit_output['loglike'])

        self.set_source_morphology(name,
                                   spatial_pars=src.spatial_pars,
                                   use_pylike=use_pylike)
        saved_state.restore()

        lnlmap.data -= fit_output_nosrc['loglike']
        tsmap = WcsNDMap(lnlmap.geom, 2.0 * lnlmap.data)

        self._clear_srcmap_cache()
        return tsmap, fit_output_nosrc['loglike']
Esempio n. 4
0
    def _scan_position(self, name, **kwargs):

        saved_state = LikelihoodState(self.like)

        skydir = kwargs.pop('skydir', self.roi[name].skydir)
        scan_cdelt = kwargs.pop('scan_cdelt', 0.02)
        nstep = kwargs.pop('nstep', 5)
        use_cache = kwargs.get('use_cache', True)
        use_pylike = kwargs.get('use_pylike', False)
        optimizer = kwargs.get('optimizer', {})

        # Fit without source
        self.zero_source(name, loglevel=logging.DEBUG)
        fit_output_nosrc = self._fit(loglevel=logging.DEBUG,
                                     **optimizer)
        self.unzero_source(name, loglevel=logging.DEBUG)
        saved_state.restore()
        self.free_norm(name, loglevel=logging.DEBUG)

        lnlmap = WcsNDMap.create(skydir=skydir, binsz=scan_cdelt, npix=(nstep, nstep),
                                 coordsys=wcs_utils.get_coordsys(self.geom.wcs))

        src = self.roi.copy_source(name)

        if use_cache and not use_pylike:
            self._create_srcmap_cache(src.name, src)

        coord = MapCoord.create(lnlmap.geom.get_coord(flat=True),
                                coordsys=lnlmap.geom.coordsys)
        scan_skydir = coord.skycoord.icrs
        for lon, lat, ra, dec in zip(coord.lon, coord.lat,
                                     scan_skydir.ra.deg, scan_skydir.dec.deg):

            spatial_pars = {'ra': ra, 'dec': dec}
            self.set_source_morphology(name,
                                       spatial_pars=spatial_pars,
                                       use_pylike=use_pylike)
            fit_output = self._fit(loglevel=logging.DEBUG,
                                   **optimizer)
            lnlmap.set_by_coord((lon, lat), fit_output['loglike'])

        self.set_source_morphology(name, spatial_pars=src.spatial_pars,
                                   use_pylike=use_pylike)
        saved_state.restore()

        lnlmap.data -= fit_output_nosrc['loglike']
        tsmap = WcsNDMap(lnlmap.geom, 2.0 * lnlmap.data)

        self._clear_srcmap_cache()
        return tsmap, fit_output_nosrc['loglike']
Esempio n. 5
0
    def _scan_position(self, name, **kwargs):

        saved_state = LikelihoodState(self.like)

        skydir = kwargs.pop('skydir', self.roi[name].skydir)
        scan_cdelt = kwargs.pop('scan_cdelt', 0.02)
        nstep = kwargs.pop('nstep', 5)
        use_cache = kwargs.get('use_cache', True)
        use_pylike = kwargs.get('use_pylike', False)
        optimizer = kwargs.get('optimizer', {})

        # Fit without source
        self.zero_source(name, loglevel=logging.DEBUG)
        fit_output_nosrc = self._fit(loglevel=logging.DEBUG,
                                     **optimizer)
        self.unzero_source(name, loglevel=logging.DEBUG)
        saved_state.restore()
        self.free_norm(name, loglevel=logging.DEBUG)

        lnlmap = Map.create(skydir, scan_cdelt, (nstep, nstep),
                            coordsys=wcs_utils.get_coordsys(self._skywcs))

        src = self.roi.copy_source(name)

        if use_cache and not use_pylike:
            self._create_srcmap_cache(src.name, src)

        scan_skydir = lnlmap.get_pixel_skydirs().transform_to('icrs')
        loglike = []
        for ra, dec in zip(scan_skydir.ra.deg, scan_skydir.dec.deg):

            spatial_pars = {'ra': ra, 'dec': dec}
            self.set_source_morphology(name,
                                       spatial_pars=spatial_pars,
                                       use_pylike=use_pylike)
            fit_output = self._fit(loglevel=logging.DEBUG,
                                   **optimizer)
            loglike += [fit_output['loglike']]

        self.set_source_morphology(name, spatial_pars=src.spatial_pars,
                                   use_pylike=use_pylike)
        saved_state.restore()

        lnlmap.data = np.array(loglike).reshape((nstep, nstep)).T
        lnlmap.data -= fit_output_nosrc['loglike']
        tsmap = Map(2.0 * lnlmap.data, lnlmap.wcs)

        self._clear_srcmap_cache()
        return tsmap, fit_output_nosrc['loglike']
Esempio n. 6
0
    def _scan_position(self, name, **kwargs):

        saved_state = LikelihoodState(self.like)

        skydir = kwargs.pop('skydir', self.roi[name].skydir)
        scan_cdelt = kwargs.pop('scan_cdelt', 0.02)
        nstep = kwargs.pop('nstep', 5)
        use_cache = kwargs.get('use_cache', True)
        use_pylike = kwargs.get('use_pylike', False)
        optimizer = kwargs.get('optimizer', {})

        # Fit without source
        self.zero_source(name, loglevel=logging.DEBUG)
        fit_output_nosrc = self._fit(loglevel=logging.DEBUG, **optimizer)
        self.unzero_source(name, loglevel=logging.DEBUG)
        saved_state.restore()
        self.free_norm(name, loglevel=logging.DEBUG)

        lnlmap = Map.create(skydir,
                            scan_cdelt, (nstep, nstep),
                            coordsys=wcs_utils.get_coordsys(self._skywcs))

        src = self.roi.copy_source(name)

        if use_cache and not use_pylike:
            self._create_srcmap_cache(src.name, src)

        scan_skydir = lnlmap.get_pixel_skydirs().transform_to('icrs')
        loglike = []
        for ra, dec in zip(scan_skydir.ra.deg, scan_skydir.dec.deg):

            spatial_pars = {'ra': ra, 'dec': dec}
            self.set_source_morphology(name,
                                       spatial_pars=spatial_pars,
                                       use_pylike=use_pylike)
            fit_output = self._fit(loglevel=logging.DEBUG, **optimizer)
            loglike += [fit_output['loglike']]

        self.set_source_morphology(name,
                                   spatial_pars=src.spatial_pars,
                                   use_pylike=use_pylike)
        saved_state.restore()

        lnlmap.data = np.array(loglike).reshape((nstep, nstep)).T
        lnlmap.data -= fit_output_nosrc['loglike']
        tsmap = Map(2.0 * lnlmap.data, lnlmap.wcs)

        self._clear_srcmap_cache()
        return tsmap, fit_output_nosrc['loglike']
Esempio n. 7
0
def fit_error_ellipse(tsmap, xy=None, dpix=3, zmin=None):
    """Fit a positional uncertainty ellipse from a TS map.  The fit
    will be performed over pixels in the vicinity of the peak pixel
    with D < dpix OR z > zmin where D is the distance from the peak
    pixel in pixel coordinates and z is the difference in amplitude
    from the peak pixel.

    Parameters
    ----------
    tsmap : `~fermipy.skymap.Map`

    xy : tuple

    dpix : float

    zmin : float

    Returns
    -------
    fit : dict
        Dictionary with fit results.
    """

    if xy is None:
        ix, iy = np.unravel_index(np.argmax(tsmap.counts.T),
                                  tsmap.counts.T.shape)
    else:
        ix, iy = xy

    pbfit = utils.fit_parabola(tsmap.counts.T, ix, iy, dpix=dpix,
                               zmin=zmin)

    wcs = tsmap.wcs
    cdelt0 = tsmap.wcs.wcs.cdelt[0]
    cdelt1 = tsmap.wcs.wcs.cdelt[1]
    npix0 = tsmap.counts.T.shape[0]
    npix1 = tsmap.counts.T.shape[1]

    o = {}
    o['fit_success'] = pbfit['fit_success']
    o['fit_inbounds'] = True

    if pbfit['fit_success']:
        sigmax = 2.0**0.5 * pbfit['sigmax'] * np.abs(cdelt0)
        sigmay = 2.0**0.5 * pbfit['sigmay'] * np.abs(cdelt1)
        theta = pbfit['theta']
        sigmax = min(sigmax, np.abs(2.0 * npix0 * cdelt0))
        sigmay = min(sigmay, np.abs(2.0 * npix1 * cdelt1))
        o['xpix'] = pbfit['x0']
        o['ypix'] = pbfit['y0']
        o['zoffset'] = pbfit['z0']
    else:
        sigmax = np.nan
        sigmay = np.nan
        theta = np.nan
        o['xpix'] = float(ix)
        o['ypix'] = float(iy)
        o['zoffset'] = tsmap.counts.T[ix, iy]

    if (o['xpix'] <= 0 or o['xpix'] >= npix0 - 1 or
            o['ypix'] <= 0 or o['ypix'] >= npix1 - 1):
        o['fit_inbounds'] = False
        o['xpix'] = float(ix)
        o['ypix'] = float(iy)

    o['peak_offset'] = np.sqrt((float(ix) - o['xpix'])**2 +
                               (float(iy) - o['ypix'])**2)

    skydir = SkyCoord.from_pixel(o['xpix'], o['ypix'], wcs)
    sigma = (sigmax * sigmay)**0.5
    r68 = 2.30**0.5 * sigma
    r95 = 5.99**0.5 * sigma
    r99 = 9.21**0.5 * sigma

    if sigmax < sigmay:
        o['pos_err_semimajor'] = sigmay
        o['pos_err_semiminor'] = sigmax
        o['theta'] = np.fmod(2 * np.pi + np.pi / 2. + theta, np.pi)
    else:
        o['pos_err_semimajor'] = sigmax
        o['pos_err_semiminor'] = sigmay
        o['theta'] = np.fmod(2 * np.pi + theta, np.pi)

    o['pos_angle'] = np.degrees(o['theta'])
    o['pos_err'] = sigma
    o['pos_r68'] = r68
    o['pos_r95'] = r95
    o['pos_r99'] = r99
    o['ra'] = skydir.icrs.ra.deg
    o['dec'] = skydir.icrs.dec.deg
    o['glon'] = skydir.galactic.l.deg
    o['glat'] = skydir.galactic.b.deg
    a = o['pos_err_semimajor']
    b = o['pos_err_semiminor']

    o['pos_ecc'] = np.sqrt(1 - b**2 / a**2)
    o['pos_ecc2'] = np.sqrt(a**2 / b**2 - 1)
    o['skydir'] = skydir

    if wcs_utils.get_coordsys(tsmap.wcs) == 'GAL':
        gal_cov = utils.ellipse_to_cov(o['pos_err_semimajor'],
                                       o['pos_err_semiminor'],
                                       o['theta'])
        theta_cel = wcs_utils.get_cel_to_gal_angle(skydir)
        cel_cov = utils.ellipse_to_cov(o['pos_err_semimajor'],
                                       o['pos_err_semiminor'],
                                       o['theta'] + theta_cel)

    else:
        cel_cov = utils.ellipse_to_cov(o['pos_err_semimajor'],
                                       o['pos_err_semiminor'],
                                       o['theta'])
        theta_gal = 2 * np.pi - wcs_utils.get_cel_to_gal_angle(skydir)
        gal_cov = utils.ellipse_to_cov(o['pos_err_semimajor'],
                                       o['pos_err_semiminor'],
                                       o['theta'] + theta_gal)

    o['pos_gal_cov'] = gal_cov
    o['pos_cel_cov'] = cel_cov
    o['pos_gal_corr'] = utils.cov_to_correlation(gal_cov)
    o['pos_cel_corr'] = utils.cov_to_correlation(cel_cov)
    o['glon_err'], o['glat_err'] = np.sqrt(
        gal_cov[0, 0]), np.sqrt(gal_cov[1, 1])
    o['ra_err'], o['dec_err'] = np.sqrt(cel_cov[0, 0]), np.sqrt(cel_cov[1, 1])

    return o
Esempio n. 8
0
    def localize(self, name, **kwargs):
        """Find the best-fit position of a source.  Localization is
        performed in two steps.  First a TS map is computed centered
        on the source with half-width set by ``dtheta_max``.  A fit is
        then performed to the maximum TS peak in this map.  The source
        position is then further refined by scanning the likelihood in
        the vicinity of the peak found in the first step.  The size of
        the scan region is set to encompass the 99% positional
        uncertainty contour as determined from the peak fit.

        Parameters
        ----------
        name : str
            Source name.

        dtheta_max : float
            Maximum offset in RA/DEC in deg from the nominal source
            position that will be used to define the boundaries of the
            TS map search region.

        nstep : int
            Number of steps in longitude/latitude that will be taken
            when refining the source position.  The bounds of the scan
            range are set to the 99% positional uncertainty as
            determined from the TS map peak fit.  The total number of
            sampling points will be nstep**2.

        fix_background : bool
            Fix background parameters when fitting the source position.

        update : bool
            Update the model for this source with the best-fit
            position.  If newname=None this will overwrite the
            existing source map of this source with one corresponding
            to its new location.

        newname : str
            Name that will be assigned to the relocalized source
            when update=True.  If newname is None then the existing
            source name will be used.

        make_plots : bool
           Generate plots.

        write_fits : bool
           Write the output to a FITS file.

        write_npy : bool
           Write the output dictionary to a numpy file.

        optimizer : dict
            Dictionary that overrides the default optimizer settings.

        Returns
        -------
        localize : dict
            Dictionary containing results of the localization
            analysis.  This dictionary is also saved to the
            dictionary of this source in 'localize'.

        """

        name = self.roi.get_source_by_name(name).name

        schema = ConfigSchema(self.defaults['localize'],
                              optimizer=self.defaults['optimizer'])
        schema.add_option('make_plots', False)
        schema.add_option('write_fits', True)
        schema.add_option('write_npy', True)
        schema.add_option('newname', name)
        schema.add_option('prefix', '')
        config = utils.create_dict(self.config['localize'],
                                   optimizer=self.config['optimizer'])
        config = schema.create_config(config, **kwargs)

        nstep = config['nstep']
        dtheta_max = config['dtheta_max']
        update = config['update']
        newname = config['newname']
        prefix = config['prefix']

        self.logger.info('Running localization for %s' % name)

        saved_state = LikelihoodState(self.like)

        if config['fix_background']:
            self.free_sources(free=False, loglevel=logging.DEBUG)

        src = self.roi.copy_source(name)
        skydir = src.skydir
        skywcs = self._skywcs
        src_pix = skydir.to_pixel(skywcs)

        tsmap_fit, tsmap = self._localize_tsmap(name,
                                                prefix=prefix,
                                                dtheta_max=dtheta_max)

        self.logger.debug(
            'Completed localization with TS Map.\n'
            '(ra,dec) = (%10.4f,%10.4f)\n'
            '(glon,glat) = (%10.4f,%10.4f)', tsmap_fit['ra'], tsmap_fit['dec'],
            tsmap_fit['glon'], tsmap_fit['glat'])

        # Fit baseline (point-source) model
        self.free_norm(name)
        fit_output = self._fit(loglevel=logging.DEBUG, **config['optimizer'])

        # Save likelihood value for baseline fit
        loglike0 = fit_output['loglike']
        self.logger.debug('Baseline Model Likelihood: %f', loglike0)

        self.zero_source(name)

        o = {
            'name': name,
            'config': config,
            'fit_success': True,
            'loglike_base': loglike0,
            'loglike_loc': np.nan,
            'dloglike_loc': np.nan
        }

        cdelt0 = np.abs(skywcs.wcs.cdelt[0])
        cdelt1 = np.abs(skywcs.wcs.cdelt[1])
        scan_step = 2.0 * tsmap_fit['r95'] / (nstep - 1.0)

        self.logger.debug(
            'Refining localization search to '
            'region of width: %.4f deg', tsmap_fit['r95'])

        scan_map = Map.create(SkyCoord(tsmap_fit['ra'],
                                       tsmap_fit['dec'],
                                       unit='deg'),
                              scan_step, (nstep, nstep),
                              coordsys=wcs_utils.get_coordsys(skywcs))

        scan_skydir = scan_map.get_pixel_skydirs()

        lnlscan = dict(wcs=scan_map.wcs.to_header().items(),
                       loglike=np.zeros((nstep, nstep)),
                       dloglike=np.zeros((nstep, nstep)),
                       dloglike_fit=np.zeros((nstep, nstep)))

        for i, t in enumerate(scan_skydir):
            model_name = '%s_localize' % (name.replace(' ', '').lower())
            src.set_name(model_name)
            src.set_position(t)
            self.add_source(model_name,
                            src,
                            free=True,
                            init_source=False,
                            save_source_maps=False,
                            loglevel=logging.DEBUG)
            fit_output = self._fit(loglevel=logging.DEBUG,
                                   **config['optimizer'])

            loglike1 = fit_output['loglike']
            lnlscan['loglike'].flat[i] = loglike1
            self.delete_source(model_name, loglevel=logging.DEBUG)

        lnlscan['dloglike'] = lnlscan['loglike'] - np.max(lnlscan['loglike'])
        scan_tsmap = Map(2.0 * lnlscan['dloglike'].T, scan_map.wcs)

        self.unzero_source(name)
        saved_state.restore()
        self._sync_params(name)
        self._update_roi()

        scan_fit, new_skydir = fit_error_ellipse(scan_tsmap, dpix=3)
        o.update(scan_fit)

        o['loglike_loc'] = np.max(
            lnlscan['loglike']) + 0.5 * scan_fit['offset']
        o['dloglike_loc'] = o['loglike_loc'] - o['loglike_base']

        # lnlscan['dloglike_fit'] = \
        #   utils.parabola(np.linspace(0,nstep-1.0,nstep)[:,np.newaxis],
        #                  np.linspace(0,nstep-1.0,nstep)[np.newaxis,:],
        #                  *scan_fit['popt']).reshape((nstep,nstep))

        o['lnlscan'] = lnlscan

        # Best fit position and uncertainty from fit to TS map
        o['tsmap_fit'] = tsmap_fit

        # Best fit position and uncertainty from pylike scan
        o['scan_fit'] = scan_fit
        pix = new_skydir.to_pixel(skywcs)
        o['xpix'] = float(pix[0])
        o['ypix'] = float(pix[1])
        o['deltax'] = (o['xpix'] - src_pix[0]) * cdelt0
        o['deltay'] = (o['ypix'] - src_pix[1]) * cdelt1

        o['offset'] = skydir.separation(new_skydir).deg

        if o['offset'] > dtheta_max:
            o['fit_success'] = False

        if not o['fit_success']:
            self.logger.error(
                'Localization failed.\n'
                '(ra,dec) = (%10.4f,%10.4f)\n'
                '(glon,glat) = (%10.4f,%10.4f)\n'
                'offset = %8.4f deltax = %8.4f '
                'deltay = %8.4f', o['ra'], o['dec'], o['glon'], o['glat'],
                o['offset'], o['deltax'], o['deltay'])
        else:
            self.logger.info(
                'Localization succeeded with '
                'coordinates:\n'
                '(ra,dec) = (%10.4f,%10.4f)\n'
                '(glon,glat) = (%10.4f,%10.4f)\n'
                'offset = %8.4f r68 = %8.4f', o['ra'], o['dec'], o['glon'],
                o['glat'], o['offset'], o['r68'])

        self.roi[name]['localize'] = copy.deepcopy(o)

        if config['make_plots']:
            self._plotter.make_localization_plots(o,
                                                  tsmap,
                                                  self.roi,
                                                  prefix=prefix,
                                                  skydir=scan_skydir)

        if update and o['fit_success']:
            self.logger.info('Updating source %s '
                             'to localized position.', name)
            src = self.delete_source(name)
            src.set_position(new_skydir)
            src.set_name(newname, names=src.names)

            self.add_source(newname, src, free=True)
            fit_output = self.fit(loglevel=logging.DEBUG)
            o['loglike_loc'] = fit_output['loglike']
            o['dloglike_loc'] = o['loglike_loc'] - o['loglike_base']
            src = self.roi.get_source_by_name(newname)
            self.roi[newname]['localize'] = copy.deepcopy(o)
            self.logger.info('LogLike: %12.3f DeltaLogLike: %12.3f',
                             o['loglike_loc'], o['dloglike_loc'])

        if o['fit_success']:
            src = self.roi.get_source_by_name(newname)
            src['pos_sigma'] = o['sigma']
            src['pos_sigma_semimajor'] = o['sigma_semimajor']
            src['pos_sigma_semiminor'] = o['sigma_semiminor']
            src['pos_r68'] = o['r68']
            src['pos_r95'] = o['r95']
            src['pos_r99'] = o['r99']
            src['pos_angle'] = np.degrees(o['theta'])

        self.logger.info('Finished localization.')
        return o
Esempio n. 9
0
def fit_error_ellipse(tsmap, xy=None, dpix=3, zmin=None):
    """Fit a positional uncertainty ellipse from a TS map.  The fit
    will be performed over pixels in the vicinity of the peak pixel
    with D < dpix OR z > zmin where D is the distance from the peak
    pixel in pixel coordinates and z is the difference in amplitude
    from the peak pixel.

    Parameters
    ----------
    tsmap : `~fermipy.skymap.Map`

    xy : tuple

    dpix : float

    zmin : float

    Returns
    -------
    fit : dict
        Dictionary with fit results.
    """

    if xy is None:
        ix, iy = np.unravel_index(np.argmax(tsmap.counts.T),
                                  tsmap.counts.T.shape)
    else:
        ix, iy = xy

    pbfit0 = utils.fit_parabola(tsmap.counts.T, ix, iy, dpix=1.5)
    pbfit1 = utils.fit_parabola(tsmap.counts.T, ix, iy, dpix=dpix, zmin=zmin)

    wcs = tsmap.wcs
    cdelt0 = tsmap.wcs.wcs.cdelt[0]
    cdelt1 = tsmap.wcs.wcs.cdelt[1]
    npix0 = tsmap.counts.T.shape[0]
    npix1 = tsmap.counts.T.shape[1]

    o = {}
    o['fit_success'] = pbfit0['fit_success']
    o['fit_inbounds'] = True

    if pbfit0['fit_success']:
        o['xpix'] = pbfit0['x0']
        o['ypix'] = pbfit0['y0']
        o['zoffset'] = pbfit0['z0']
    else:
        o['xpix'] = float(ix)
        o['ypix'] = float(iy)
        o['zoffset'] = tsmap.counts.T[ix, iy]

    if pbfit1['fit_success']:
        sigmax = 2.0**0.5 * pbfit1['sigmax'] * np.abs(cdelt0)
        sigmay = 2.0**0.5 * pbfit1['sigmay'] * np.abs(cdelt1)
        theta = pbfit1['theta']
        sigmax = min(sigmax, np.abs(2.0 * npix0 * cdelt0))
        sigmay = min(sigmay, np.abs(2.0 * npix1 * cdelt1))
    elif pbfit0['fit_success']:
        sigmax = 2.0**0.5 * pbfit0['sigmax'] * np.abs(cdelt0)
        sigmay = 2.0**0.5 * pbfit0['sigmay'] * np.abs(cdelt1)
        theta = pbfit0['theta']
        sigmax = min(sigmax, np.abs(2.0 * npix0 * cdelt0))
        sigmay = min(sigmay, np.abs(2.0 * npix1 * cdelt1))
    else:
        pix_area = np.abs(cdelt0) * np.abs(cdelt1)
        mask = get_region_mask(tsmap.data, 1.0, (ix, iy))
        area = np.sum(mask) * pix_area
        sigmax = (area / np.pi)**0.5
        sigmay = (area / np.pi)**0.5
        theta = 0.0

    if (o['xpix'] <= 0 or o['xpix'] >= npix0 - 1 or o['ypix'] <= 0
            or o['ypix'] >= npix1 - 1):
        o['fit_inbounds'] = False
        o['xpix'] = float(ix)
        o['ypix'] = float(iy)

    o['peak_offset'] = np.sqrt((float(ix) - o['xpix'])**2 +
                               (float(iy) - o['ypix'])**2)

    skydir = SkyCoord.from_pixel(o['xpix'], o['ypix'], wcs)
    sigma = (sigmax * sigmay)**0.5
    r68 = 2.30**0.5 * sigma
    r95 = 5.99**0.5 * sigma
    r99 = 9.21**0.5 * sigma

    if sigmax < sigmay:
        o['pos_err_semimajor'] = sigmay
        o['pos_err_semiminor'] = sigmax
        o['theta'] = np.fmod(2 * np.pi + np.pi / 2. + theta, np.pi)
    else:
        o['pos_err_semimajor'] = sigmax
        o['pos_err_semiminor'] = sigmay
        o['theta'] = np.fmod(2 * np.pi + theta, np.pi)

    o['pos_angle'] = np.degrees(o['theta'])
    o['pos_err'] = sigma
    o['pos_r68'] = r68
    o['pos_r95'] = r95
    o['pos_r99'] = r99
    o['ra'] = skydir.icrs.ra.deg
    o['dec'] = skydir.icrs.dec.deg
    o['glon'] = skydir.galactic.l.deg
    o['glat'] = skydir.galactic.b.deg
    a = o['pos_err_semimajor']
    b = o['pos_err_semiminor']

    o['pos_ecc'] = np.sqrt(1 - b**2 / a**2)
    o['pos_ecc2'] = np.sqrt(a**2 / b**2 - 1)
    o['skydir'] = skydir

    if wcs_utils.get_coordsys(tsmap.wcs) == 'GAL':
        gal_cov = utils.ellipse_to_cov(o['pos_err_semimajor'],
                                       o['pos_err_semiminor'], o['theta'])
        theta_cel = wcs_utils.get_cel_to_gal_angle(skydir)
        cel_cov = utils.ellipse_to_cov(o['pos_err_semimajor'],
                                       o['pos_err_semiminor'],
                                       o['theta'] + theta_cel)

    else:
        cel_cov = utils.ellipse_to_cov(o['pos_err_semimajor'],
                                       o['pos_err_semiminor'], o['theta'])
        theta_gal = 2 * np.pi - wcs_utils.get_cel_to_gal_angle(skydir)
        gal_cov = utils.ellipse_to_cov(o['pos_err_semimajor'],
                                       o['pos_err_semiminor'],
                                       o['theta'] + theta_gal)

    o['pos_gal_cov'] = gal_cov
    o['pos_cel_cov'] = cel_cov
    o['pos_gal_corr'] = utils.cov_to_correlation(gal_cov)
    o['pos_cel_corr'] = utils.cov_to_correlation(cel_cov)
    o['glon_err'], o['glat_err'] = np.sqrt(gal_cov[0, 0]), np.sqrt(gal_cov[1,
                                                                           1])
    o['ra_err'], o['dec_err'] = np.sqrt(cel_cov[0, 0]), np.sqrt(cel_cov[1, 1])

    return o