Exemple #1
0
    def supplement(self):
        """ Add some supplemental columns """
        from ugali.utils.projector import gal2cel, gal2cel_angle

        kwargs = dict(usemask=False, asrecarray=True)
        out = copy.deepcopy(self)

        if ('lon' in out.names) and ('lat' in out.names):
            # Ignore entries that are all zero
            zeros = np.all(self.ndarray == 0, axis=1)

            ra, dec = gal2cel(out.lon, out.lat)
            ra[zeros] = 0
            dec[zeros] = 0
            out = recfuncs.append_fields(out, ['ra', 'dec'], [ra, dec],
                                         **kwargs).view(Samples)

            if 'position_angle' in out.names:
                pa = gal2cel_angle(out.lon, out.lat, out.position_angle)
                pa = pa - 180. * (pa > 180.)
                pa[zeros] = 0
                out = recfuncs.append_fields(out, ['position_angle_cel'], [pa],
                                             **kwargs).view(Samples)

        return out
Exemple #2
0
    def supplement(self, coordsys='gal'):
        """ Add some supplemental columns """
        from ugali.utils.projector import gal2cel, gal2cel_angle
        from ugali.utils.projector import cel2gal, cel2gal_angle

        coordsys = coordsys.lower()
        kwargs = dict(usemask=False, asrecarray=True)
        out = copy.deepcopy(self)

        if ('lon' in out.names) and ('lat' in out.names):
            # Ignore entries that are all zero
            zeros = np.all(self.ndarray == 0, axis=1)

            if coordsys == 'gal':
                ra, dec = gal2cel(out.lon, out.lat)
                glon, glat = out.lon, out.lat
            else:
                ra, dec = out.lon, out.lat
                glon, glat = cel2gal(out.lon, out.lat)

            ra[zeros] = 0
            dec[zeros] = 0
            glon[zeros] = 0
            glat[zeros] = 0

            names = ['ra', 'dec', 'glon', 'glat']
            arrs = [ra, dec, glon, glat]
            out = mlab.rec_append_fields(out, names, arrs).view(Samples)
            #out = recfuncs.append_fields(out,names,arrs,**kwargs).view(Samples)

            if 'position_angle' in out.names:
                if coordsys == 'gal':
                    pa_gal = out.position_angle
                    pa_cel = gal2cel_angle(out.lon, out.lat,
                                           out.position_angle)
                    pa_cel = pa_cel - 180. * (pa_cel > 180.)
                else:
                    pa_gal = cel2gal_angle(out.lon, out.lat,
                                           out.position_angle)
                    pa_cel = out.position_angle
                    pa_gal = pa_gal - 180. * (pa_gal > 180.)

                pa_gal[zeros] = 0
                pa_cel[zeros] = 0
                names = ['position_angle_gal', 'position_angle_cel']
                arrs = [pa_gal, pa_cel]
                out = recfuncs.append_fields(out, names, arrs,
                                             **kwargs).view(Samples)

        return out
Exemple #3
0
    def supplement(self,coordsys='gal'):
        """ Add some supplemental columns """
        from ugali.utils.projector import gal2cel, gal2cel_angle
        from ugali.utils.projector import cel2gal, cel2gal_angle

        coordsys = coordsys.lower()
        kwargs = dict(usemask=False, asrecarray=True)
        out = copy.deepcopy(self)

        if ('lon' in out.names) and ('lat' in out.names):
            # Ignore entries that are all zero
            zeros = np.all(self.ndarray==0,axis=1)

            if coordsys == 'gal':
                ra,dec = gal2cel(out.lon,out.lat)
                glon,glat = out.lon,out.lat
            else:
                ra,dec = out.lon,out.lat
                glon,glat = cel2gal(out.lon,out.lat)

            ra[zeros] = 0; dec[zeros] = 0
            glon[zeros] = 0; glat[zeros] = 0

            names = ['ra','dec','glon','glat']
            arrs = [ra,dec,glon,glat]
            out = mlab.rec_append_fields(out,names,arrs).view(Samples)
            #out = recfuncs.append_fields(out,names,arrs,**kwargs).view(Samples)

            if 'position_angle' in out.names:
                if coordsys == 'gal':
                    pa_gal = out.position_angle
                    pa_cel = gal2cel_angle(out.lon,out.lat,out.position_angle)
                    pa_cel = pa_cel - 180.*(pa_cel > 180.)
                else:
                    pa_gal = cel2gal_angle(out.lon,out.lat,out.position_angle)
                    pa_cel = out.position_angle
                    pa_gal = pa_gal - 180.*(pa_gal > 180.)
                    
                pa_gal[zeros] = 0; pa_cel[zeros] = 0
                names = ['position_angle_gal','position_angle_cel']
                arrs = [pa_gal,pa_cel]
                out = recfuncs.append_fields(out,names,arrs,**kwargs).view(Samples)
        
        return out
Exemple #4
0
    def get_results(self, **kwargs):
        kwargs.setdefault('alpha', self.alpha)
        kwargs.setdefault('burn', self.nburn * self.nwalkers)

        # Calculate best-fit parameters from MCMC chain
        logger.debug('Estimating parameters...')
        estimate = self.estimate_params(**kwargs)
        params = {k: v[0] for k, v in estimate.items()}
        results = dict(estimate)

        # Extra parameters from the MCMC chain
        logger.debug('Estimating auxiliary parameters...')
        try:
            results['ra'] = self.estimate('ra', **kwargs)
            results['dec'] = self.estimate('dec', **kwargs)
        except KeyError:
            logger.warn("Didn't find 'ra' or 'dec'")
            ra, dec = gal2cel(results['lon'][0], results['lat'][0])
            results['ra'] = ugali.utils.stats.interval(ra)
            results['dec'] = ugali.utils.stats.interval(dec)

        ra, dec = results['ra'][0], results['dec'][0]
        glon, glat = lon, lat = results['lon'][0], results['lat'][0]
        results.update(gal=[float(glon), float(glat)])
        results.update(cel=[float(ra), float(dec)])

        try:
            results['position_angle_cel'] = self.estimate(
                'position_angle_cel', **kwargs)
        except KeyError:
            results['position_angle_cel'] = ugali.utils.stats.interval(np.nan)

        # Update the loglike to the best-fit parameters from the chain
        logger.debug('Calculating TS...')
        ts = 2 * self.loglike.value(**params)
        results['ts'] = ugali.utils.stats.interval(ts, np.nan, np.nan)

        #lon,lat = estimate['lon'][0],estimate['lat'][0]
        #
        #results.update(gal=[float(lon),float(lat)])
        #ra,dec = gal2cel(lon,lat)
        #results.update(cel=[float(ra),float(dec)])
        #results['ra'] = ugali.utils.stats.interval(ra,np.nan,np.nan)
        #results['dec'] = ugali.utils.stats.interval(dec,np.nan,np.nan)

        # Celestial position angle
        # Break ambiguity in direction with '% 180.'
        pa, pa_err = results['position_angle']
        pa_cel = gal2cel_angle(lon, lat, pa) % 180.
        pa_cel_err = np.array(pa_err) - pa + pa_cel
        results['position_angle_cel'] = ugali.utils.stats.interval(
            pa_cel, pa_cel_err[0], pa_cel_err[1])

        mod, mod_err = estimate['distance_modulus']
        dist = mod2dist(mod)
        dist_lo, dist_hi = [mod2dist(mod_err[0]), mod2dist(mod_err[1])]
        results['distance'] = ugali.utils.stats.interval(
            dist, dist_lo, dist_hi)
        dist, dist_err = results['distance']

        ext, ext_err = estimate['extension']
        ext_sigma = np.nan_to_num(np.array(ext_err) - ext)
        results['extension_arcmin'] = ugali.utils.stats.interval(
            60 * ext, 60 * ext_err[0], 60 * ext_err[1])

        # Radially symmetric extension (correct for ellipticity).
        ell, ell_err = estimate['ellipticity']
        rext, rext_err = ext * np.sqrt(1 -
                                       ell), np.array(ext_err) * np.sqrt(1 -
                                                                         ell)
        rext_sigma = np.nan_to_num(np.array(rext_err) - rext)
        results['extension_radial'] = ugali.utils.stats.interval(
            rext, rext_err[0], rext_err[1])
        results['extension_radial_arcmin'] = ugali.utils.stats.interval(
            60 * rext, 60 * rext_err[0], 60 * rext_err[1])

        # Bayes factor for ellipticity
        results['ellipticity_bayes_factor'] = self.bayes_factor(
            'ellipticity', burn=kwargs['burn'])

        # Physical Size (should do this with the posteriors)
        # Radially symmetric
        dist_sigma = np.nan_to_num(np.array(dist_err) - dist)

        size = np.arctan(np.radians(ext)) * dist
        size_sigma = size * np.sqrt((ext_sigma / ext)**2 +
                                    (dist_sigma / dist)**2)
        size_err = [size - size_sigma[0], size + size_sigma[1]]
        results['physical_size'] = ugali.utils.stats.interval(
            size, size_err[0], size_err[1])

        rsize = np.arctan(np.radians(rext)) * dist
        rsize_sigma = rsize * np.sqrt((rext_sigma / rext)**2 +
                                      (dist_sigma / dist)**2)
        rsize_err = [rsize - rsize_sigma[0], rsize + rsize_sigma[1]]
        results['physical_size_radial'] = ugali.utils.stats.interval(
            rsize, rsize_err[0], rsize_err[1])

        # Richness
        rich, rich_err = estimate['richness']

        # Number of observed stars (sum of p-values)
        nobs = self.loglike.p.sum()
        nobs_lo, nobs_hi = nobs + np.sqrt(nobs) * np.array([-1, 1])
        results['nobs'] = ugali.utils.stats.interval(nobs, nobs_lo, nobs_hi)

        # Number of predicted stars (pixelization effects?)
        npred = self.loglike.f * rich
        npred_lo, npred_hi = rich_err[0] * self.loglike.f, rich_err[
            1] * self.loglike.f
        results['npred'] = ugali.utils.stats.interval(npred, npred_lo,
                                                      npred_hi)

        # Careful, depends on the isochrone...
        stellar_mass = self.source.stellar_mass()
        mass = rich * stellar_mass
        mass_lo, mass_hi = rich_err[0] * stellar_mass, rich_err[
            1] * stellar_mass
        results['mass'] = ugali.utils.stats.interval(mass, mass_lo, mass_hi)

        stellar_luminosity = self.source.stellar_luminosity()
        lum = rich * stellar_luminosity
        lum_lo, lum_hi = rich_err[0] * stellar_luminosity, rich_err[
            1] * stellar_luminosity
        results['luminosity'] = ugali.utils.stats.interval(lum, lum_lo, lum_hi)

        Mv = self.source.absolute_magnitude(rich)
        Mv_lo = self.source.absolute_magnitude(rich_err[0])
        Mv_hi = self.source.absolute_magnitude(rich_err[1])
        results['Mv'] = ugali.utils.stats.interval(Mv, Mv_lo, Mv_hi)

        # ADW: WARNING this is very fragile.
        # Also, this is not quite right, should cut on the CMD available space
        kwargs = dict(richness=rich,
                      mag_bright=16.,
                      mag_faint=23.,
                      n_trials=5000,
                      alpha=self.alpha,
                      seed=0)
        martin = self.config['results'].get('martin')
        if martin:
            logger.info("Calculating Martin magnitude...")
            if martin > 1: kwargs['n_trials'] = martin
            Mv_martin = self.source.isochrone.absolute_magnitude_martin(
                **kwargs)
            results['Mv_martin'] = Mv_martin
        else:
            logger.warning("Skipping Martin magnitude")
            results['Mv_martin'] = np.nan

        mu = surfaceBrightness(Mv, size, dist)
        results['surface_brightness'] = ugali.utils.stats.interval(
            mu, np.nan, np.nan)

        try:
            results['constellation'] = ugali.utils.projector.ang2const(
                lon, lat)[1]
        except:
            pass
        results['iau'] = ugali.utils.projector.ang2iau(lon, lat)

        coord = SkyCoord(ra * u.deg, dec * u.deg, distance=dist * u.kpc)
        results['ra_sex'] = str(coord.ra.to_string())
        results['dec_sex'] = str(coord.dec.to_string())

        # Calculate some separations from GC, LMC, SMC
        #NED coordinates with de Grisj distance
        LMC = SkyCoord(80.8939 * u.deg,
                       -69.7561 * u.deg,
                       distance=49.89 * u.kpc)
        #NED coordinates with de Grisj distance
        SMC = SkyCoord(13.1866 * u.deg,
                       -72.8286 * u.deg,
                       distance=61.94 * u.kpc)
        # GC from astropy?
        GC = SkyCoord(266.4168262 * u.deg,
                      -29.0077969 * u.deg,
                      distance=8.0 * u.kpc)

        results['d_gc'] = coord.separation_3d(GC).value
        results['d_lmc'] = coord.separation_3d(LMC).value
        results['d_smc'] = coord.separation_3d(SMC).value

        try:
            results['feh'] = float(self.source.isochrone.feh)
        except:
            results['feh'] = np.nan

        output = dict()
        output['params'] = params
        output['results'] = results
        return output
Exemple #5
0
    def get_results(self,**kwargs):
        kwargs.setdefault('alpha',self.alpha)
        kwargs.setdefault('burn',self.nburn*self.nwalkers)

        # Calculate best-fit parameters from MCMC chain
        logger.debug('Estimating parameters...')
        estimate = self.estimate_params(**kwargs)
        params = {k:v[0] for k,v in estimate.items()}
        results = dict(estimate)

        # Extra parameters from the MCMC chain
        logger.debug('Estimating auxiliary parameters...')
        try: 
            results['ra']  = self.estimate('ra',**kwargs)
            results['dec'] = self.estimate('dec',**kwargs)
        except KeyError:
            logger.warn("Didn't find 'ra' or 'dec'")
            ra,dec = gal2cel(results['lon'][0],results['lat'][0])
            results['ra'] = ugali.utils.stats.interval(ra)
            results['dec'] = ugali.utils.stats.interval(dec)

        ra,dec = results['ra'][0],results['dec'][0]
        glon,glat = lon,lat = results['lon'][0],results['lat'][0]
        results.update(gal=[float(glon),float(glat)])
        results.update(cel=[float(ra),float(dec)])

        try:
            results['position_angle_cel']  = self.estimate('position_angle_cel',**kwargs)
        except KeyError:
            results['position_angle_cel'] = ugali.utils.stats.interval(np.nan)

        # Update the loglike to the best-fit parameters from the chain
        logger.debug('Calculating TS...')
        ts = 2*self.loglike.value(**params)
        results['ts'] = ugali.utils.stats.interval(ts,np.nan,np.nan)
 
        #lon,lat = estimate['lon'][0],estimate['lat'][0]
        # 
        #results.update(gal=[float(lon),float(lat)])
        #ra,dec = gal2cel(lon,lat)
        #results.update(cel=[float(ra),float(dec)])
        #results['ra'] = ugali.utils.stats.interval(ra,np.nan,np.nan)
        #results['dec'] = ugali.utils.stats.interval(dec,np.nan,np.nan)
 
        # Celestial position angle
        # Break ambiguity in direction with '% 180.'
        pa,pa_err = results['position_angle']
        pa_cel = gal2cel_angle(lon,lat,pa) % 180.
        pa_cel_err = np.array(pa_err) - pa + pa_cel
        results['position_angle_cel'] = ugali.utils.stats.interval(pa_cel,pa_cel_err[0],pa_cel_err[1])
        
        mod,mod_err = estimate['distance_modulus']
        dist = mod2dist(mod)
        dist_lo,dist_hi = [mod2dist(mod_err[0]),mod2dist(mod_err[1])]
        results['distance'] = ugali.utils.stats.interval(dist,dist_lo,dist_hi)
        dist,dist_err = results['distance']
 
        ext,ext_err = estimate['extension']
        ext_sigma = np.nan_to_num(np.array(ext_err) - ext)
        results['extension_arcmin'] = ugali.utils.stats.interval(60*ext,60*ext_err[0],60*ext_err[1])
 
        # Radially symmetric extension (correct for ellipticity).
        ell,ell_err = estimate['ellipticity']
        rext,rext_err = ext*np.sqrt(1-ell),np.array(ext_err)*np.sqrt(1-ell)
        rext_sigma = np.nan_to_num(np.array(rext_err) - rext)
        results['extension_radial'] = ugali.utils.stats.interval(rext,rext_err[0],rext_err[1])
        results['extension_radial_arcmin'] = ugali.utils.stats.interval(60*rext,60*rext_err[0],60*rext_err[1])
 
        # Bayes factor for ellipticity
        results['ellipticity_bayes_factor'] = self.bayes_factor('ellipticity',burn=kwargs['burn'])
 
        # Physical Size (should do this with the posteriors)
        # Radially symmetric
        dist_sigma = np.nan_to_num(np.array(dist_err) - dist)

        size = np.arctan(np.radians(ext)) * dist
        size_sigma = size * np.sqrt((ext_sigma/ext)**2 + (dist_sigma/dist)**2)
        size_err = [size-size_sigma[0],size+size_sigma[1]]
        results['physical_size'] = ugali.utils.stats.interval(size,size_err[0],size_err[1])

        rsize = np.arctan(np.radians(rext)) * dist
        rsize_sigma = rsize * np.sqrt((rext_sigma/rext)**2 + (dist_sigma/dist)**2)
        rsize_err = [rsize-rsize_sigma[0],rsize+rsize_sigma[1]]
        results['physical_size_radial'] = ugali.utils.stats.interval(rsize,rsize_err[0],rsize_err[1])
 
        # Richness
        rich,rich_err = estimate['richness']
 
        # Number of observed stars (sum of p-values)
        nobs = self.loglike.p.sum()
        nobs_lo,nobs_hi = nobs + np.sqrt(nobs)*np.array([-1,1])
        results['nobs'] = ugali.utils.stats.interval(nobs,nobs_lo,nobs_hi)
 
        # Number of predicted stars (pixelization effects?)
        npred = self.loglike.f*rich
        npred_lo,npred_hi = rich_err[0]*self.loglike.f,rich_err[1]*self.loglike.f
        results['npred'] = ugali.utils.stats.interval(npred,npred_lo,npred_hi)
        
        # Careful, depends on the isochrone...
        stellar_mass = self.source.stellar_mass()
        mass = rich*stellar_mass
        mass_lo,mass_hi = rich_err[0]*stellar_mass,rich_err[1]*stellar_mass
        results['mass'] = ugali.utils.stats.interval(mass,mass_lo,mass_hi)
 
        stellar_luminosity = self.source.stellar_luminosity()
        lum = rich*stellar_luminosity
        lum_lo,lum_hi = rich_err[0]*stellar_luminosity,rich_err[1]*stellar_luminosity
        results['luminosity'] = ugali.utils.stats.interval(lum,lum_lo,lum_hi)

        # Absolute magnitude only calculated for DES isochrones with g,r 
        try:
            Mv = self.source.absolute_magnitude(rich)
            Mv_lo = self.source.absolute_magnitude(rich_err[0])
            Mv_hi = self.source.absolute_magnitude(rich_err[1])
            results['Mv'] = ugali.utils.stats.interval(Mv,Mv_lo,Mv_hi)
        except ValueError as e:
            logger.warning("Skipping absolute magnitude")
            logger.warn(str(e))
            results['Mv'] = np.nan

        # ADW: WARNING this is very fragile.
        # Also, this is not quite right, should cut on the CMD available space
        kwargs = dict(richness=rich,mag_bright=16., mag_faint=23.,
                      n_trials=5000,alpha=self.alpha, seed=0)
        martin = self.config['results'].get('martin')
        if martin:
            logger.info("Calculating Martin magnitude...")
            if martin > 1: kwargs['n_trials'] = martin
            Mv_martin = self.source.isochrone.absolute_magnitude_martin(**kwargs)
            results['Mv_martin'] = Mv_martin
        else:
            logger.warning("Skipping Martin magnitude")
            results['Mv_martin'] = np.nan
        
        mu = surfaceBrightness(Mv, size, dist)
        results['surface_brightness'] = ugali.utils.stats.interval(mu,np.nan,np.nan)
 
        try: 
            results['constellation'] = ang2const(lon,lat,self.coordsys)[1]
        except:
            pass
        results['iau'] = ugali.utils.projector.ang2iau(lon,lat)
 
        coord = SkyCoord(ra*u.deg,dec*u.deg,distance=dist*u.kpc)
        results['ra_sex'] = str(coord.ra.to_string())
        results['dec_sex'] = str(coord.dec.to_string())
 
        # Calculate some separations from GC, LMC, SMC
        #NED coordinates with de Grisj distance
        LMC = SkyCoord(80.8939*u.deg,-69.7561*u.deg,distance=49.89*u.kpc)
        #NED coordinates with de Grisj distance
        SMC = SkyCoord(13.1866*u.deg,-72.8286*u.deg,distance=61.94*u.kpc)
        # GC from astropy?
        GC = SkyCoord(266.4168262*u.deg,-29.0077969*u.deg,distance=8.0*u.kpc)
         
        results['d_gc'] = coord.separation_3d(GC).value
        results['d_lmc'] = coord.separation_3d(LMC).value
        results['d_smc'] = coord.separation_3d(SMC).value

        try:
            results['feh'] = float(self.source.isochrone.feh)
        except:
            results['feh'] = np.nan
        
        output = dict()
        output['params'] = params
        output['results'] = results
        return output