예제 #1
0
def calculate_rf_lens_magnitudes(lens_redshift, velocity_dispersion,
                                 filters_dict):
    """Calculates the reference-frame lens magnitudes in multiple filters

    Parameters
    ----------
    lens_redshift : float
        Redshift of the lens
    velocity_dispersion : float
        Velocity dispersion of the lens
    filters_dict : dict
        (See output of `get_sdss_filters` for details)
        Throughputs of various filters

    Returns
    -------
    dict
        Each key is one of string characters 'u', 'g', 'r', 'i', 'z'
        representing the filter
        Each value is the reference-frame apparent magnitude of the quasar
        in the 'key' filter, of type float
    """
    from stellarpop import tools
    from lenspop import population_functions, distances
    from astropy.cosmology import FlatLambdaCDM

    # Instantiate Distance
    distance = distances.Distance()  #TODO: necessary?
    # Instantiate LensPopulation
    lenspop = population_functions.LensPopulation_()
    # Instantiate FlatLambdaCDM cosmology with reasonable parameters
    cosmology = FlatLambdaCDM(H0=70.0, Om0=0.3)

    lens_sed = tools.getSED('BC_Z=1.0_age=9.000gyr')
    velocity_dispersion = np.atleast_1d(velocity_dispersion)

    # Absolute --> apparent magnitude conversion in the R-band
    lens_abmag_r = tools.ABFilterMagnitude(filters_dict['r'], lens_sed,
                                           lens_redshift)
    distance_modulus = cosmology.distmod(lens_redshift).value
    lens_appmag_r = lens_abmag_r + distance_modulus

    # [Reference frame] Absolute --> apparent magnitude conversion in the R-band
    rf_lens_abmag_r, _ = lenspop.EarlyTypeRelations(velocity_dispersion)
    rf_lens_appmag = {}
    rf_lens_appmag['r'] = rf_lens_abmag_r + distance_modulus

    # Quantity which is added to ~magnitude to convert it into reference-frame ~magnitude
    offset_rf = rf_lens_abmag_r - lens_abmag_r

    # Converting absolute magnitude to reference-frame apparent magnitude
    for band in 'ugiz':
        rf_lens_appmag[band] = tools.ABFilterMagnitude(
            filters_dict[band], lens_sed,
            lens_redshift) + offset_rf + distance_modulus
    return rf_lens_appmag
    def create_models(self):
        import scipy, cPickle
        from stellarpop import tools
        from stellarpop.ndinterp import ndInterp

        index = {}
        shape = []
        axes = {}
        axes_index = 0
        for key in self.axes_names:
            index[key] = {}
            shape.append(self.axes[key]['points'].size)
            axes[axes_index] = self.axes[key]['eval']
            axes_index += 1
            for i in range(self.axes[key]['points'].size):
                index[key][self.axes[key]['points'][i]] = i

        models = {}
        model = scipy.empty(shape) * scipy.nan
        for f in self.filter_names:
            models[f] = {}
            for z in self.redshifts:
                models[f][z] = model.copy()

        for file in self.files:
            f = open(file, 'rb')
            data = cPickle.load(f)
            wave = cPickle.load(f)
            f.close()
            for key in data.keys():
                obj = data[key]
                jj = key
                spec = obj['sed']
                ind = []
                for key in self.axes_names:
                    try:
                        ind.append([index[key][obj[key]]])
                    except:
                        print key, index[key]
                        print obj
                        df
                for f in self.filter_names:
                    for i in range(len(self.redshifts)):
                        z = self.redshifts[i]
                        # correction is the units correction factor
                        correction = self.corrections[i]
                        sed = [wave, spec * correction]
                        mag = tools.ABFilterMagnitude(self.filters[f], sed, z)
                        if scipy.isnan(mag) == True:
                            df
                        models[f][z][ind] = mag

        for f in self.filter_names:
            for z in self.redshifts:
                model = models[f][z].copy()
                if scipy.isnan(model).any():
                    models[f][z] = None
                else:
                    models[f][z] = ndInterp(axes, model)
        return models
예제 #3
0
def getColor(f1, f2, z):
    import numpy
    from stellarpop import tools
    import spasmoid
    dir = spasmoid.__path__[0] + "/data"

    qso = numpy.loadtxt('%s/vandenBerk.dat' % dir)
    w = qso[:, 0].copy()
    m = qso[:, 1].copy()
    s = qso[:, 2].copy()

    f1 = tools.filterfromfile(f1)
    f2 = tools.filterfromfile(f2)

    sed = [w, m]
    color = tools.ABFilterMagnitude(f1, sed, z) - tools.ABFilterMagnitude(
        f2, sed, z)
    return color
예제 #4
0
def calculate_rf_quasar_magnitudes(quasar_redshift, apparent_magnitude_i,
                                   filters_dict):
    """Calculates the reference-frame quasar magnitudes in multiple filters

    Parameters
    ----------
    quasar_redshift : float
        Redshift of the source quasar
    apparent_magnitude_i : float
        Apparent magnitude of the source AGN in the I-band
    filters_dict : dict
        (See output of `get_sdss_filters` for details)
        Throughputs of various filters

    Returns
    -------
    dict
        Each key is one of string characters 'u', 'g', 'r', 'i', 'z'
        representing the filter
        Each value is the reference-frame apparent magnitude of the quasar
        in the 'key' filter, of type float
    """
    from stellarpop import tools

    quasar_sed = tools.getSED('agn')
    q_offset = apparent_magnitude_i - tools.ABFilterMagnitude(
        filters_dict['i'], quasar_sed, quasar_redshift)
    rf_quasar_appmag = {}
    if quasar_redshift < 3.9:
        rf_quasar_appmag['u'] = tools.ABFilterMagnitude(
            filters_dict['u'], quasar_sed, quasar_redshift) + q_offset
    else:
        rf_quasar_appmag['u'] = 99.0
    for band in 'griz':
        rf_quasar_appmag[band] = tools.ABFilterMagnitude(
            filters_dict[band], quasar_sed, quasar_redshift) + q_offset
    return rf_quasar_appmag
예제 #5
0
파일: db.py 프로젝트: stevet40/OM10
    def calculate_rest_frame_r_magnitude(self, sed, veldisp, redshift, cosmo):
        """
        Computes rest-frame r-band magnitude of a lens galaxy

        Parameters
        ----------
        sed : string
            Name of SED to use
        redshift : float
            Redshift of object
        d : float
            Distance modulus to object
        veldisp : float
            For lens galaxies, the velocity dispersion can be passed in to
            provide the absolute magnitude via the Fundamental Plane

        Returns
        -------
        RF_Rmag_app : float
            Reference r-band apparent magnitude
        offset_RF_abs : float
            Magnitude offset for converting absolute to apparent magnitude

        Notes
        -----
        We don't need this function when painting quasars, because the OM10
        catalog contains a reliable i-band apparent magnitude for each source.
        """
        lenspop_constructor = population_functions.LensPopulation_()
        # Reference Frame Absolute R magnitude
        RF_RMag_abs, _ = lenspop_constructor.EarlyTypeRelations(veldisp)
        RMag_abs = tools.ABFilterMagnitude(Rfilter, sed, redshift)
        distModulus = cosmo.distmod(redshift).value
        Rmag_app = RMag_abs + distModulus
        offset_abs_app = RMag_abs - Rmag_app
        offset_RF_abs = RF_RMag_abs - RMag_abs
        RF_Rmag_app = RF_RMag_abs - offset_abs_app
        return RF_Rmag_app, offset_RF_abs, distModulus
예제 #6
0
파일: db.py 프로젝트: stevet40/OM10
    def paint(self, Nmax=None, verbose=False,
              lrg_input_cat='$OM10_DIR/data/LRGo.txt',
              qso_input_cat='$OM10_DIR/data/QSOo.txt',
              synthetic=False):
        """
        Add new columns to the table, for the magnitudes in various filters.

        Parameters
        ----------
        synthetic : boolean
            Use `lenspop` to make synthetic magnitudes in various filters
        target : string
            Paint lenses ('lens') or sources ('source')
        lrg_input_cat : string
            Name of LRG catalog, if not using synthetic paint
        qso_input_cat : string
            Name of QSO catalog, if not using synthetic paint
        verbose : boolean
           print progress to stdout

        Notes
        -----
        * Synthetic painting is very slow, as we loop over each object.
        * The treatment of QSOs may be flawed: the offset calculation has not
          been tested.

        """

        if synthetic==False:
        # read data from SDSS
            f=open(os.path.expandvars(lrg_input_cat),'r')
            lrg=loadtxt(f)
            f.close()
            g=open(os.path.expandvars(qso_input_cat),'r')
            qso=loadtxt(g)
            g.close()

        ###MY OWN REDSHIFT ONLY MATCHING HERE:

            lens_props = ['MAGG_LENS','MAGR_LENS','MAGI_LENS','MAGZ_LENS', \
            'MAGW1_LENS','MAGW2_LENS','MAGW3_LENS','MAGW4_LENS', 'SDSS_FLAG_LENS']

            src_props = ['MAGG_SRC','MAGR_SRC','MAGI_SRC','MAGZ_SRC', \
            'MAGW1_SRC','MAGW2_SRC','MAGW3_SRC','MAGW4_SRC', 'SDSS_FLAG_SRC']

            tmp_lens = Table(np.zeros((len(self.sample),len(lens_props)),dtype='f8'),names=lens_props)
            tmp_src = Table(np.zeros((len(self.sample),len(src_props)),dtype='f8'),names=src_props)

            if verbose: print('setup done')

            lrg_sort = lrg[np.argsort(lrg[:,0]),:]
            qso_sort = qso[np.argsort(qso[:,0]),:]
            lens_count = 0

            for lens in self.sample:

                #paint lens
                ind = np.searchsorted(lrg_sort[:,0],lens['ZLENS'])
                if ind >= len(lrg_sort): ind = len(lrg_sort) - 1
                tmp_lens[lens_count] = lrg_sort[ind,6:] - lrg_sort[ind,8] + lens['APMAG_I'] #assign colors, not mags
                #paint source
                qso_ind = np.searchsorted(qso_sort[:,0],lens['ZSRC'])
                if qso_ind >= len(qso_sort): qso_ind = len(qso_sort) - 1
                tmp_src[lens_count] = qso_sort[qso_ind,1:] - qso_sort[qso_ind,3] + lens['MAGI']

                lens_count += 1

            self.sample = hstack([self.sample,tmp_lens,tmp_src])


        if synthetic==True:
            lens_count = 0
            total = len(self.sample)
            Rfilter = tools.filterfromfile('r_SDSS')
            Ufilter = tools.filterfromfile('u_SDSS')
            # sort the Ufilter array
            Ufilterarg=np.sort(Ufilter[1])
            Ufilter = (Ufilter[0], Ufilterarg, 1)
            Gfilter = tools.filterfromfile('g_SDSS')
            Ifilter = tools.filterfromfile('i_SDSS')
            Zfilter = tools.filterfromfile('z_SDSS')
            self.Nlenses=len(self.sample)
            bands = ('r_SDSS_lens', 'g_SDSS_lens', 'i_SDSS_lens', 'z_SDSS_lens', 'u_SDSS_lens','r_SDSS_quasar', 'g_SDSS_quasar', 'i_SDSS_quasar', 'z_SDSS_quasar', 'u_SDSS_quasar')
            if verbose: print('OM10: computing synthetic magnitudes in the following bands: ', bands)
            # call a distance class constructor
            d = distances.Distance()
            # number of data in the table of calculated magnitude
            totalEntrees = self.Nlenses*10.0
            t = Table(np.arange(totalEntrees).reshape(self.Nlenses, 10),
                      names=bands)
            Lsed = tools.getSED('BC_Z=1.0_age=9.000gyr')
            Qsed = tools.getSED('agn')
            from astropy.cosmology import FlatLambdaCDM
            cosmo = FlatLambdaCDM(H0=70, Om0=0.3)
            lenspop_constructor = population_functions.LensPopulation_()
            for lens in self.sample:
                # calculate the quasar magnitude
                redshift = lens['ZSRC']
                RF_Imag_app_q = lens['MAGI_IN']
                Qoffset = RF_Imag_app_q - tools.ABFilterMagnitude(Ifilter, Qsed, redshift)
                RF_Rmag_app_q = tools.ABFilterMagnitude(Rfilter, Qsed, redshift) + Qoffset
                RF_Gmag_app_q = tools.ABFilterMagnitude(Gfilter, Qsed, redshift) + Qoffset
                RF_Zmag_app_q = tools.ABFilterMagnitude(Zfilter, Qsed, redshift) + Qoffset
                if(redshift<3.9):
                    RF_Umag_app_q = tools.ABFilterMagnitude(Ufilter, Qsed, redshift) + Qoffset
                elif(redshift>=3.9):
                    RF_Umag_app_q = 99
                # calculate the lens magnitude
                veldisp = np.atleast_1d(lens['VELDISP'])
                redshift = lens['ZLENS']
                # Reference Frame Absolute R magnitude
                RF_RMag_abs, _ = lenspop_constructor.EarlyTypeRelations(veldisp)
                RMag_abs = tools.ABFilterMagnitude(Rfilter, Lsed, redshift)
                distMod = cosmo.distmod(redshift).value
                Rmag_app = RMag_abs + distMod
                offset_abs_app = RMag_abs - Rmag_app
                offset_RF_abs = RF_RMag_abs - RMag_abs
                RF_Rmag_app = RF_RMag_abs - offset_abs_app
                # Get filters and calculate magnitudes for each filter:
                RF_Umag_app = tools.ABFilterMagnitude(Ufilter, Lsed, redshift) + offset_RF_abs + distMod
                RF_Gmag_app = tools.ABFilterMagnitude(Gfilter, Lsed, redshift) + offset_RF_abs + distMod
                RF_Imag_app = tools.ABFilterMagnitude(Ifilter, Lsed, redshift) + offset_RF_abs + distMod
                RF_Zmag_app = tools.ABFilterMagnitude(Zfilter, Lsed, redshift) + offset_RF_abs + distMod
                t['u_SDSS_lens'][lens_count] = RF_Umag_app
                t['r_SDSS_lens'][lens_count] = RF_Rmag_app
                t['g_SDSS_lens'][lens_count] = RF_Gmag_app
                t['i_SDSS_lens'][lens_count] = RF_Imag_app
                t['z_SDSS_lens'][lens_count] = RF_Zmag_app
                t['u_SDSS_quasar'][lens_count] = RF_Umag_app_q
                t['r_SDSS_quasar'][lens_count] = RF_Rmag_app_q
                t['g_SDSS_quasar'][lens_count] = RF_Gmag_app_q
                t['i_SDSS_quasar'][lens_count] = RF_Imag_app_q
                t['z_SDSS_quasar'][lens_count] = RF_Zmag_app_q
                lens_count = lens_count + 1
                dot = np.mod(lens_count, total/np.min([79,total])) == 0
                if verbose and dot:
                    print('.', end="")

            # Update the sample by adding the table of calculated magnitude
            self.sample.add_columns(t.columns.values())
            self.lenses = self.sample.copy()

        return
예제 #7
0
파일: mag2mag.py 프로젝트: peterrwi/LensPop
f1 = tools.filterfromfile(f1)
if f2 is None:
    f2 = f1
else:
    f2 = tools.filterfromfile(f2)
if z2 is None:
    z2 = z1

SED = tools.getSED(SEDtype)

if vega:
    filtermag = tools.VegaFilterMagnitude(f1, SED, z1)
#    vegatmp = tools.getSED('Vega')
#    vegaAB = tools.ABFilterMagnitude(f1,vegatmp,0.)
else:
    filtermag = tools.ABFilterMagnitude(f1, SED, z1)
magoffset = m1 - filtermag
#print magoffset

if vega:
    m2 = tools.VegaFilterMagnitude(f2, SED, z2) + magoffset
else:
    m2 = tools.ABFilterMagnitude(f2, SED, z2) + magoffset
if z1 != z2:
    from stellarpop import distances
    from math import log10
    dist = distances.Distance()
    dist.OMEGA_M = Om
    dist.OMEGA_L = OL
    dist.h = H0 / 100.
    if z2 != 0.:
예제 #8
0
    def create_models(self):
        import numpy, cPickle
        from stellarpop import tools
        from ndinterp import ndInterp

        index = {}
        shape = []
        axes = {}
        axes_index = 0
        for key in self.axes_names:
            index[key] = {}
            shape.append(self.axes[key]['points'].size)
            axes[axes_index] = self.axes[key]['eval']
            axes_index += 1
            for i in range(self.axes[key]['points'].size):
                index[key][self.axes[key]['points'][i]] = i
        self.redshifts = self.axes['redshift']['points']
        self.corrections = self.luminosity_correction()

        zindex = self.axes_names.index('redshift')

        models = {}
        model = numpy.empty(shape) * numpy.nan
        for f in self.filter_names:
            models[f] = model.copy()

        for file in self.files:
            f = open(file, 'rb')
            data = cPickle.load(f)
            wave = cPickle.load(f)
            f.close()
            for key in data.keys():
                obj = data[key]
                jj = key
                spec = obj['sed']
                ind = []
                for key in self.axes_names:
                    if key == 'redshift':
                        continue
                    try:
                        ind.append([index[key][obj[key]]])
                    except:
                        print key, index[key]
                        print obj
                        df
                ind.insert(zindex, None)
                for f in self.filter_names:
                    for i in range(self.redshifts.size):
                        z = self.redshifts[i]
                        # correction is the units correction factor
                        correction = self.corrections[i]
                        sed = [wave, spec * correction]
                        mag = tools.ABFilterMagnitude(self.filters[f], sed, z)
                        if numpy.isnan(mag) == True:
                            df
                        ind[zindex] = i
                        models[f][ind] = mag
        self.interpAxes = axes
        return models
        for f in self.filter_names:
            model = models[f].copy()
            if numpy.isnan(model).any():
                models[f] = None
            else:
                models[f] = ndInterp(axes, model, order=1)
        return models