def NFW_fit(e, theta, Lambda, z, h=0.7):

    a = np.linspace(-10, 10, 100)
    x, y = np.meshgrid(a, a)

    q = (1. - e) / (1. + e)

    r = np.sqrt(q * (x**2) + (y**2) / q)

    # SIMET RELATION FOR M200
    M0 = (2.21e14) / h
    alpha = 1.33
    M200 = M0 * ((Lambda / 40.)**alpha)

    # Compute cosmological parameters
    cosmo = LambdaCDM(H0=h * 100, Om0=0.3, Ode0=0.7)
    H = cosmo.H(z).value / (1.0e3 * pc)  #H at z_pair s-1
    roc = (3.0 *
           (H**2.0)) / (8.0 * np.pi * G)  #critical density at z_pair (kg.m-3)
    roc_mpc = roc * ((pc * 1.0e6)**3.0)

    # Compute R_200
    R200 = r200_nfw(M200, roc_mpc)

    # S_nfw R_200
    S_nfw = SIGMA_nfw((r, sigma_c, z, h), R200)

    x_rot = (x * np.cos(t) + y * np.sin(t))
    y_rot = (-1. * x * np.sin(t) + y * np.cos(t))

    w = np.ones(len(x_rot[mask]))
    e, ang = momentos(x_rot[mask], y_rot[mask], w)

    return e, np.rad2deg(ang)
Example #2
0
class AstroPyCosmology(CLMMCosmology):
    def __init__(self, **kwargs):
        super(AstroPyCosmology, self).__init__(**kwargs)

        # this tag will be used to check if the cosmology object is accepted by the modeling
        self.backend = 'ct'

        assert isinstance(self.be_cosmo, LambdaCDM)

    def _init_from_cosmo(self, be_cosmo):

        assert isinstance(be_cosmo, LambdaCDM)
        self.be_cosmo = be_cosmo

    def _init_from_params(self, H0, Omega_b0, Omega_dm0, Omega_k0):

        Om0 = Omega_b0 + Omega_dm0
        Ob0 = Omega_b0

        self.be_cosmo = FlatLambdaCDM(H0=H0,
                                      Om0=Om0,
                                      Ob0=Ob0,
                                      Tcmb0=2.7255,
                                      Neff=3.046,
                                      m_nu=([0.06, 0.0, 0.0] * units.eV))
        if Omega_k0 != 0.0:
            Ode0 = self.be_cosmo.Ode0 - Omega_k0
            self.be_cosmo = LambdaCDM(H0=H0,
                                      Om0=Om0,
                                      Ob0=Ob0,
                                      Ode0=Ode0,
                                      Tcmb0=2.7255,
                                      Neff=3.046,
                                      m_nu=([0.06, 0.0, 0.0] * units.eV))

    def _set_param(self, key, value):
        raise NotImplementedError("Astropy do not support changing parameters")

    def _get_param(self, key):
        if key == "Omega_m0":
            return self.be_cosmo.Om0
        elif key == "Omega_b0":
            return self.be_cosmo.Ob0
        elif key == "Omega_dm0":
            return self.be_cosmo.Odm0
        elif key == "Omega_k0":
            return self.be_cosmo.Ok0
        elif key == 'h':
            return self.be_cosmo.H0.to_value() / 100.0
        elif key == 'H0':
            return self.be_cosmo.H0.to_value()
        else:
            raise ValueError(f"Unsupported parameter {key}")

    def get_Omega_m(self, z):
        return self.be_cosmo.Om(z)

    def get_E2Omega_m(self, z):
        return self.be_cosmo.Om(z) * (self.be_cosmo.H(z) / self.be_cosmo.H0)**2

    def eval_da_z1z2(self, z1, z2):
        return self.be_cosmo.angular_diameter_distance_z1z2(z1, z2).to_value(
            units.Mpc)

    def eval_sigma_crit(self, z_len, z_src):
        if np.any(np.array(z_src) <= z_len):
            warnings.warn(
                f'Some source redshifts are lower than the cluster redshift. Returning Sigma_crit = np.inf for those galaxies.'
            )
        # Constants
        clight_pc_s = const.CLIGHT_KMS.value * 1000. / const.PC_TO_METER.value
        gnewt_pc3_msun_s2 = const.GNEWT.value * const.SOLAR_MASS.value / const.PC_TO_METER.value**3

        d_l = self.eval_da_z1z2(0, z_len)
        d_s = self.eval_da_z1z2(0, z_src)
        d_ls = self.eval_da_z1z2(z_len, z_src)

        beta_s = np.maximum(0., d_ls / d_s)
        return clight_pc_s**2 / (4.0 * np.pi *
                                 gnewt_pc3_msun_s2) * 1 / d_l * np.divide(
                                     1., beta_s) * 1.0e6
Example #3
0
def main(sample='pru',N_min=0,N_max=1000.,
                z_min = 0.0, z_max = 0.5,
                conmin = 0.5, conmax = 5.0,
                lMHmin = 11., lMHmax = 15.5,
                odds_min=0.5, RIN = 100., ROUT =5000.,
                ndots= 15,ncores=10,h=1.):

        '''
        
        INPUT
        ---------------------------------------------------------
        sample         (str) sample name
        N_min          (int) lower limit of galaxy members - >=
        N_max          (int) higher limit of galaxy members - <
        z_min          (float) lower limit for z - >=
        z_max          (float) higher limit for z - <
        conmin         (float) lower limit for C_BG - >=
        conmax         (float) higher limit for C_BG - <
        lMHmin         (float) lower limit for log(MHALO) - >=
        lMHmax         (float) higher limit for log(MHALO) - <        
        odds_min       (float) cut in odds
        RIN            (float) Inner bin radius of profile
        ROUT           (float) Outer bin radius of profile
        ndots          (int) Number of bins of the profile
        ncores         (int) to run in parallel, number of cores
        h              (float) H0 = 100.*h
        '''

        cosmo = LambdaCDM(H0=100*h, Om0=0.3, Ode0=0.7)
        tini = time.time()
        
        print 'Using catalog gx_'+ncat+'_L_RM.fits'
        print 'Sample ',sample
        print 'Selecting groups with:'
        print N_min,' <= N_GAL < ',N_max
        print z_min,' <= z < ',z_max
        print conmin,' <= C_BG < ',conmax
        print lMHmin,' <= log(MH) < ',lMHmax
        print 'Background galaxies with:'
        print 'ODDS > ',odds_min
        print 'Profile has ',ndots,'bins'
        print 'from ',RIN,'kpc to ',ROUT,'kpc'
        print 'h = ',h
              
        # Defining radial bins
        bines = np.logspace(np.log10(RIN),np.log10(ROUT),num=ndots+1)
        R = (bines[:-1] + np.diff(bines)*0.5)*1.e-3
        
        #reading cats
        
        L=LensCat.Catalog.read_catalog(folder+'gx_'+ncat+'_L_RM.fits')        
        # L=LensCat.Catalog.read_catalog(folder+'gx_L_RM_FINAL.fits')
        # L=LensCat.Catalog.read_catalog(folder+'gx_L_RM_FOF.fits')        
        mrich = (L.data.N_GAL >= N_min)*(L.data.N_GAL < N_max)
        mz    = (L.data.Z >= z_min)*(L.data.Z < z_max)
        mcon  = (L.data.C_BG >= conmin)*(L.data.C_BG < conmax)
        mmass = (np.log10(L.data.MASS_HALO) >= lMHmin)*(np.log10(L.data.MASS_HALO) < lMHmax)
        mlenses = mrich*mz*mcon*mmass
        Nlenses = mlenses.sum()

        if Nlenses < ncores:
                ncores = Nlenses
        
        print 'Nlenses',Nlenses
        print 'CORRIENDO EN ',ncores,' CORES'

        
        L.data = L.data[mlenses]
        
        # SPLIT LENSING CAT
        
        lbins = int(round(Nlenses/float(ncores), 0))
        slices = ((np.arange(lbins)+1)*ncores).astype(int)
        slices = slices[(slices < Nlenses)]
        Lsplit = np.split(L.data.iloc[:],slices)
        
        # WHERE THE SUMS ARE GOING TO BE SAVED
        
        DSIGMAwsum_T = np.zeros(ndots) 
        DSIGMAwsum_X = np.zeros(ndots)
        WEIGHTsum    = np.zeros(ndots)
        NGALsum      = np.zeros(ndots)
        Mwsum        = np.zeros(ndots)
        BOOTwsum_T   = np.zeros((100,ndots))
        BOOTwsum_X   = np.zeros((100,ndots))
        BOOTwsum     = np.zeros((100,ndots))
        Ntot         = []
        tslice       = np.array([])
        
        for l in range(len(Lsplit)):
                
                print 'RUN ',l+1,' OF ',len(Lsplit)
                
                t1 = time.time()
                
                num = len(Lsplit[l])
                
                rin  = RIN*np.ones(num)
                rout = ROUT*np.ones(num)
                nd   = ndots*np.ones(num)
                h_a  = h*np.ones(num)
                
                if num == 1:
                        entrada = [Lsplit[l].CATID.iloc[0],Lsplit[l].RA_BG.iloc[0],
                                        Lsplit[l].DEC_BG.iloc[0],Lsplit[l].Z.iloc[0],
                                        RIN,ROUT,ndots,h]
                        
                        salida = [partial_profile_unpack(entrada)]
                else:          
                        entrada = np.array([Lsplit[l].CATID.iloc[:],Lsplit[l].RA_BG,
                                        Lsplit[l].DEC_BG,Lsplit[l].Z,rin,rout,nd,h_a]).T
                        
                        pool = Pool(processes=(num))
                        salida = np.array(pool.map(partial_profile_unpack, entrada))
                        pool.terminate()
                                
                for profilesums in salida:
                        DSIGMAwsum_T += profilesums['DSIGMAwsum_T']
                        DSIGMAwsum_X += profilesums['DSIGMAwsum_X']
                        WEIGHTsum    += profilesums['WEIGHTsum']
                        NGALsum      += profilesums['NGAL']
                        Mwsum        += profilesums['Mwsum']
                        BOOTwsum_T   += profilesums['BOOTwsum_T']
                        BOOTwsum_X   += profilesums['BOOTwsum_X']
                        BOOTwsum     += profilesums['BOOTwsum']
                        Ntot         = np.append(Ntot,profilesums['Ntot'])
                
                t2 = time.time()
                ts = (t2-t1)/60.
                tslice = np.append(tslice,ts)
                print 'TIME SLICE'
                print  ts
                print 'Estimated ramaining time'
                print (np.mean(tslice)*(len(Lsplit)-(l+1)))
        
        # COMPUTING PROFILE        
                
        Mcorr     = Mwsum/WEIGHTsum
        DSigma_T  = (DSIGMAwsum_T/WEIGHTsum)/(1+Mcorr)
        DSigma_X  = (DSIGMAwsum_X/WEIGHTsum)/(1+Mcorr)
        eDSigma_T =  np.std((BOOTwsum_T/BOOTwsum),axis=0)/(1+Mcorr)
        eDSigma_X =  np.std((BOOTwsum_X/BOOTwsum),axis=0)/(1+Mcorr)
        
        # AVERAGE LENS PARAMETERS
        
        zmean        = np.average(L.data.Z,weights=Ntot)
        Ngal_mean    = np.average(L.data.N_GAL,weights=Ntot)
        MH_mean      = np.average(L.data.MASS_HALO,weights=Ntot)
        MD_mean      = np.average(L.data.MASS_DYN,weights=Ntot)
        sigmaH_mean  = np.average(L.data.VDISP_HALO,weights=Ntot)
        sigmaD_mean  = np.average(L.data.VDISP_DYN,weights=Ntot)
        RH_mean      = np.average(L.data.RADIUS_HALO,weights=Ntot)
        
        # FITING AN NFW MODEL
        
        H        = cosmo.H(zmean).value/(1.0e3*pc) #H at z_pair s-1 
        roc      = (3.0*(H**2.0))/(8.0*np.pi*G) #critical density at z_pair (kg.m-3)
        roc_mpc  = roc*((pc*1.0e6)**3.0)
        
        try:
                nfw        = NFW_stack_fit(R,DSigma_T,eDSigma_T,zmean,roc)
        except:
                nfw          = [0.01,0.,100.,[0.,0.],[0.,0.],-999.,0.]

        M200_NFW   = (800.0*np.pi*roc_mpc*(nfw[0]**3))/(3.0*Msun)
        e_M200_NFW =((800.0*np.pi*roc_mpc*(nfw[0]**2))/(Msun))*nfw[1]
        le_M200    = (np.log(10.)/M200_NFW)*e_M200_NFW
 
        # WRITING OUTPUT FITS FILE
        
        
        tbhdu = fits.BinTableHDU.from_columns(
                [fits.Column(name='Rp', format='D', array=R),
                fits.Column(name='DSigma_T', format='D', array=DSigma_T),
                fits.Column(name='error_DSigma_T', format='D', array=eDSigma_T),
                fits.Column(name='DSigma_X', format='D', array=DSigma_X),
                fits.Column(name='error_DSigma_X', format='D', array=eDSigma_X),
                fits.Column(name='NGAL', format='D', array=NGALsum),
                fits.Column(name='NGAL_w', format='D', array=WEIGHTsum)])
        
        h = tbhdu.header
        h.append(('N_LENSES',np.int(Nlenses)))
        h.append(('N_min',np.int(N_min)))
        h.append(('N_max',np.int(N_max)))
        h.append(('z_min',np.round(z_min,4)))
        h.append(('z_max',np.round(z_max,4)))
        h.append(('C_BG_min',np.round(conmin,4)))
        h.append(('C_BG_max',np.round(conmax,4)))
        h.append(('lMH_min',np.round(lMHmin,4)))
        h.append(('lMH_max',np.round(lMHmax,4)))
        h.append(('lM200_NFW',np.round(np.log10(M200_NFW),4)))
        h.append(('elM200_NFW',np.round(le_M200,4)))
        h.append(('CHI2_NFW',np.round(nfw[2],4)))
        h.append(('N_GAL_mean',np.round(Ngal_mean,4)))
        h.append(('lMASS_HALO_mean',np.round(np.log10(MH_mean),4)))
        h.append(('VDISP_HALO_mean',np.round(sigmaH_mean,2)))
        h.append(('VDISP_DYN_mean',np.round(sigmaD_mean,2)))
        h.append(('RADIUS_HALO_mean',np.round(RH_mean,2)))
        h.append(('z_mean',np.round(zmean,4)))


        try:
                h.append(('lMASS_DYN_mean',np.round(np.log10(MD_mean),4)))
        except:
                print 'NO DYN MASS'
                
        
        tbhdu.writeto(folder+'profile_'+sample+'.fits',overwrite=True)
                
        tfin = time.time()
        
        print 'TOTAL TIME ',(tfin-tini)/60.
def multipole_shear(r,
                    M200=1.e14,
                    ellip=0.25,
                    z=0.2,
                    h=0.7,
                    misscentred=False,
                    s_off=0.4,
                    components=['t0', 't', 'tcos', 'xsin'],
                    verbose=True,
                    Yanmiss=False):
    '''
	Equations from van Uitert (vU, arXiv:1610.04226) for the 
	multipole expansion and from Ford et al. (F,2015) for
	the misscentring

	INPUTS:
	r               [Mpc] - Float or numpy_array
	                Distance to the centre of 
	                the gravitational potential
	
	OPTIONAL:
	M200            [M_sun] - Float/ Cluster Mass
	ellip           Float / Halo ellipticity defined as
	                (1-q)/(1+q) where q is the semi-axis
	                ratio (q < 1)
	z               Float/ Lens redshift
	zs              Float/ Source redshift
	h               Float/ Cosmological quantity
	misscentred     Float/ If True computes de misscentred quantities
					The misscentred is considered only in the 
					x - axis
	s_off           [Mpc h-1] Float/ sigma_offset width of the distribution 
	                of cluster offsets (F_Eq11)
	components      List of misscentred components that are going
	                to be computed:
	                't0'   -> Gt0_off
	                't'    -> Gt_off
	                'tcos' -> Gt_off_cos
	                'xsin' -> Gx_off_sin
	verbose         Print time computing
	Yanmiss         if True use Eq 4 to model the miss of Yan et al. 2020
	
	OUTPUT:
	output          Dictionary (the shear is scales with the
	                critical density Gamma_i = Sigma_cr*gamma_i
	                ---------- vU_Eq18 ---------
	                Gt0: Shear monopole
	                Gt2: Tangential component for the quadrupole
	                Gx2: Cross component for the quadrupole
	                --------- Misscentred terms --------
	                Gt0_off: (ellip = 0) F_Eq14
	                Gt_off: Integrated tangential component (vU_Eq17)
	                for considering kappa_offset
	                Gt_off_cos: Integrated tangential component times
	                cos(2theta) (vU_Eq17) for considering kappa_offset
	                Gx_off_sin: Integrated cross component times
	                sin(2theta) (vU_Eq17) for considering kappa_offset
	'''

    if not verbose:
        blockPrint()

    # Check if r is float or numpy array
    if not isinstance(r, (np.ndarray)):
        r = np.array([r])

    # Compute cosmological parameters
    cosmo = LambdaCDM(H0=h * 100, Om0=0.3, Ode0=0.7)
    H = cosmo.H(z).value / (1.0e3 * pc)  #H at z_pair s-1
    roc = (3.0 *
           (H**2.0)) / (8.0 * np.pi * G)  #critical density at z_pair (kg.m-3)
    roc_mpc = roc * ((pc * 1.0e6)**3.0)

    # Compute R_200
    R200 = r200_nfw(M200, roc_mpc)

    # Scaling sigma_off
    s_off = s_off / h

    #print '##################'
    #print '      CENTRED     '
    #print '##################'

    def Delta_Sigma(R):
        '''
		Density contraste for NFW
		
		'''

        #calculo de c usando la relacion de Duffy et al 2008

        M = ((800.0 * np.pi * roc_mpc * (R200**3)) / (3.0 * Msun)) * h
        c = 5.71 * ((M / 2.e12)**-0.084) * ((1. + z)**-0.47)

        ####################################################

        deltac = (200. / 3.) * ((c**3) / (np.log(1. + c) - (c / (1 + c))))
        x = np.round((R * c) / R200, 12)
        m1 = x < 1.0
        m2 = x > 1.0
        m3 = (x == 1.0)

        try:
            jota = np.zeros(len(x))
            atanh = np.arctanh(((1.0 - x[m1]) / (1.0 + x[m1]))**0.5)
            jota[m1]=(4.0*atanh)/((x[m1]**2.0)*((1.0-x[m1]**2.0)**0.5)) \
             + (2.0*np.log(x[m1]/2.0))/(x[m1]**2.0) - 1.0/(x[m1]**2.0-1.0) \
             + (2.0*atanh)/((x[m1]**2.0-1.0)*((1.0-x[m1]**2.0)**0.5))
            atan = np.arctan(((x[m2] - 1.0) / (1.0 + x[m2]))**0.5)
            jota[m2]=(4.0*atan)/((x[m2]**2.0)*((x[m2]**2.0-1.0)**0.5)) \
             + (2.0*np.log(x[m2]/2.0))/(x[m2]**2.0) - 1.0/(x[m2]**2.0-1.0) \
             + (2.0*atan)/((x[m2]**2.0-1.0)**1.5)
            jota[m3] = 2.0 * np.log(0.5) + 5.0 / 3.0
        except:
            if m1:
                atanh = np.arctanh(((1.0 - x[m1]) / (1.0 + x[m1]))**0.5)
                jota = (4.0*atanh)/((x[m1]**2.0)*((1.0-x[m1]**2.0)**0.5)) \
                 + (2.0*np.log(x[m1]/2.0))/(x[m1]**2.0) - 1.0/(x[m1]**2.0-1.0) \
                 + (2.0*atanh)/((x[m1]**2.0-1.0)*((1.0-x[m1]**2.0)**0.5))
            if m2:
                atan = np.arctan(((x[m2] - 1.0) / (1.0 + x[m2]))**0.5)
                jota = (4.0*atan)/((x[m2]**2.0)*((x[m2]**2.0-1.0)**0.5)) \
                 + (2.0*np.log(x[m2]/2.0))/(x[m2]**2.0) - 1.0/(x[m2]**2.0-1.0) \
                 + (2.0*atan)/((x[m2]**2.0-1.0)**1.5)
            if m3:
                jota = 2.0 * np.log(0.5) + 5.0 / 3.0

        rs_m = (R200 * 1.e6 * pc) / c
        kapak = ((2. * rs_m * deltac * roc_mpc) *
                 (pc**2 / Msun)) / ((pc * 1.0e6)**3.0)
        return kapak * jota

    def monopole(R):
        '''
		Projected density for NFW
		
		'''
        if not isinstance(R, (np.ndarray)):
            R = np.array([R])

        # m = R == 0.
        # R[m] = 1.e-8

        #calculo de c usando la relacion de Duffy et al 2008

        M = ((800.0 * np.pi * roc_mpc * (R200**3)) / (3.0 * Msun)) * h
        c = 5.71 * ((M / 2.e12)**-0.084) * ((1. + z)**-0.47)

        ####################################################

        deltac = (200. / 3.) * ((c**3) / (np.log(1. + c) - (c / (1 + c))))

        x = (R * c) / R200
        m1 = x <= (1.0 - 1.e-12)
        m2 = x >= (1.0 + 1.e-12)
        m3 = (x == 1.0)
        m4 = (~m1) * (~m2) * (~m3)

        jota = np.zeros(len(x))
        atanh = np.arctanh(np.sqrt((1.0 - x[m1]) / (1.0 + x[m1])))
        jota[m1] = (1. /
                    (x[m1]**2 - 1.)) * (1. -
                                        (2. / np.sqrt(1. - x[m1]**2)) * atanh)

        atan = np.arctan(((x[m2] - 1.0) / (1.0 + x[m2]))**0.5)
        jota[m2] = (1. /
                    (x[m2]**2 - 1.)) * (1. -
                                        (2. / np.sqrt(x[m2]**2 - 1.)) * atan)

        jota[m3] = 1. / 3.

        x1 = 1. - 1.e-4
        atanh1 = np.arctanh(np.sqrt((1.0 - x1) / (1.0 + x1)))
        j1 = (1. / (x1**2 - 1.)) * (1. - (2. / np.sqrt(1. - x1**2)) * atanh1)

        x2 = 1. + 1.e-4
        atan2 = np.arctan(((x2 - 1.0) / (1.0 + x2))**0.5)
        j2 = (1. / (x2**2 - 1.)) * (1. - (2. / np.sqrt(x2**2 - 1.)) * atan2)

        jota[m4] = np.interp(x[m4].astype(float64), [x1, x2], [j1, j2])

        rs_m = (R200 * 1.e6 * pc) / c
        kapak = ((2. * rs_m * deltac * roc_mpc) *
                 (pc**2 / Msun)) / ((pc * 1.0e6)**3.0)
        return kapak * jota

    def quadrupole(R):
        '''
		Quadrupole term defined as (d(Sigma)/dr)*r
		
		'''
        m0p = derivative(monopole, R, dx=1e-5)
        return m0p * R

    def psi2(R):
        '''
		vU_Eq10
		
		'''
        argumento = lambda x: (x**3) * monopole(x)
        integral = integrate.quad(argumento,
                                  0,
                                  R,
                                  epsabs=1.e-01,
                                  epsrel=1.e-01)[0]
        return integral * (-2. / (R**2))

    vecpsi2 = np.vectorize(psi2)

    #print '##################'
    #print '    MISCENTRED    '
    #print '##################'

    def P_Roff(Roff):
        if Yanmiss:
            Poff = (Roff / s_off**2) * np.exp(-1. * (Roff / s_off))
        else:
            # F_Eq11
            Poff = abs((Roff / s_off**2) * np.exp(-0.5 * (Roff / s_off)**2))
        return Poff

    def monopole_off(R, theta):
        '''
		F_Eq12
		'''
        def moff(x):
            return monopole(np.sqrt(R**2 + x**2 - 2. * x * R *
                                    np.cos(theta))) * P_Roff(x) * 0.5

        argumento = lambda x: moff(x)
        # integral1  = integrate.quad(argumento, -1.*np.inf, 0, epsabs=1.e-01, epsrel=1.e-01)[0]
        integral1 = integrate.quad(argumento,
                                   -1. * np.inf,
                                   -100.,
                                   epsabs=1.e-01,
                                   epsrel=1.e-01)[0]
        # integral2  = integrate.quad(argumento, 0., R, epsabs=1.e-01, epsrel=1.e-01)[0]
        x = np.linspace(-100., 100., 5000)
        integral2 = integrate.simps(moff(x), x, even='first')
        # integral3  = integrate.quad(argumento, R, np.inf, epsabs=1.e-01, epsrel=1.e-01)[0]
        integral3 = integrate.quad(argumento,
                                   100.,
                                   np.inf,
                                   epsabs=1.e-01,
                                   epsrel=1.e-01)[0]
        return integral1 + integral2 + integral3

    vec_moff = np.vectorize(monopole_off)

    def Delta_Sigma_off(R, theta):
        '''
		F_Eq14
		'''

        argumento = lambda x: monopole_off(x, theta) * x
        integral = integrate.quad(argumento,
                                  0,
                                  R,
                                  epsabs=1.e-01,
                                  epsrel=1.e-01)[0]
        DS_off = (2. / R**2) * integral - monopole_off(R, theta)
        return DS_off

    def monopole_off0(R):
        '''
		F_Eq12
		
		'''
        def DS_RRs(Rs, R):
            # F_Eq13
            #argumento = lambda x: monopole(np.sqrt(R**2+Rs**2-2.*Rs*R*np.cos(x)))
            #integral  = integrate.quad(argumento, 0, 2.*np.pi, epsabs=1.e-01, epsrel=1.e-01)[0]
            x = np.linspace(0., 2. * np.pi, 500)
            integral = integrate.simps(monopole(
                np.sqrt(R**2 + Rs**2 - 2. * Rs * R * np.cos(x))),
                                       x,
                                       even='first')
            return integral / (2. * np.pi)

        argumento = lambda x: DS_RRs(x, R) * P_Roff(x)
        integral = integrate.quad(argumento,
                                  0,
                                  np.inf,
                                  epsabs=1.e-02,
                                  epsrel=1.e-02)[0]
        return integral

    def Delta_Sigma_off0(R):
        '''
		F_Eq14
		
		'''
        argumento = lambda x: monopole_off0(x) * x
        integral = integrate.quad(argumento,
                                  0,
                                  R,
                                  epsabs=1.e-02,
                                  epsrel=1.e-02)[0]
        DS_off = (2. / R**2) * integral - monopole_off0(R)
        return DS_off

    vec_DSoff0 = np.vectorize(Delta_Sigma_off0)

    def quadrupole_off(R, theta):
        def q_off(roff):
            rp = np.sqrt(R**2 + roff**2 - 2 * roff * R * np.cos(theta))
            return quadrupole(rp) * P_Roff(roff) * 0.5

        argumento = lambda x: q_off(x)
        # integral10  = integrate.quad(argumento, -1.*np.inf, 0, epsabs=1.e-01, epsrel=1.e-01)[0]
        integral10 = integrate.quad(argumento,
                                    -1. * np.inf,
                                    -100.,
                                    epsabs=1.e-01,
                                    epsrel=1.e-01)[0]
        # integral20  = integrate.quad(argumento, 0., R, epsabs=1.e-01, epsrel=1.e-01)[0]
        x = np.linspace(-100., 100., 5000)
        integral20 = integrate.simps(q_off(x), x, even='first')
        # integral30  = integrate.quad(argumento, R, np.inf, epsabs=1.e-01, epsrel=1.e-01)[0]
        integral30 = integrate.quad(argumento,
                                    100.,
                                    np.inf,
                                    epsabs=1.e-01,
                                    epsrel=1.e-01)[0]

        return integral10 + integral20 + integral30

    vec_qoff = np.vectorize(quadrupole_off)

    def psi2_off(R, theta):
        def arg(x):
            return (x**3) * monopole_off(x, theta)

        argumento = lambda x: arg(x)
        integral = integrate.quad(argumento,
                                  0,
                                  R,
                                  epsabs=1.e-01,
                                  epsrel=1.e-01)[0]
        return integral * (-2. / (R**2))

    vecpsi2_off = np.vectorize(psi2_off)

    def quantities_centred(r):

        gt0 = Delta_Sigma(r)
        monopole_r = monopole(r)
        quadrupole_r = quadrupole(r)
        print 'computing psi2 centred'
        psi2_r = vecpsi2(r)

        return gt0, monopole_r, quadrupole_r, psi2_r

    def quantities_misscentred(r):
        print 'computing misscentred profile'
        gamma_t0_off = []
        gamma_t_off0 = []
        gamma_t_off = []
        gamma_x_off = []
        for R in r:

            if 't0' in components:
                print 'computing DS_t0_off'
                t1 = time.time()
                DSoff = Delta_Sigma_off0(R)
                gamma_t0_off = np.append(gamma_t0_off, DSoff)
                t2 = time.time()
                print(t2 - t1) / 60.

            def DS_t_off(theta):
                gamma_t0 = []
                gamma_t2 = []
                for t in theta:
                    gamma_t0 = np.append(gamma_t0, Delta_Sigma_off(R, t))
                    gamma_t2 = np.append(
                        gamma_t2,
                        ((-6 * psi2_off(R, t) / R**2) -
                         2. * monopole_off(R, t) + quadrupole_off(R, t)) *
                        np.cos(2. * t))
                return gamma_t0 + ellip * gamma_t2

            if 't' in components:
                print 'computing DS_t_off'
                t1 = time.time()
                if ellip == 0.:
                    DSoff = Delta_Sigma_off0(R)
                    gamma_t_off0 = np.append(gamma_t_off0, DSoff)
                else:
                    x = np.linspace(0., 2. * np.pi, 100)
                    integral = integrate.simps(DS_t_off(x), x, even='first')
                    gamma_t_off0 = np.append(gamma_t_off0,
                                             integral / (2. * np.pi))
                t2 = time.time()
                print R, (t2 - t1) / 60.

            if 'tcos' in components:
                print 'computing DS_t_off_cos'
                t1 = time.time()
                x = np.linspace(0., 2. * np.pi, 100)
                integral = integrate.simps(DS_t_off(x) * np.cos(2. * x),
                                           x,
                                           even='first')
                gamma_t_off = np.append(gamma_t_off, integral / np.pi)
                t2 = time.time()
                print 'tcos', R, (t2 - t1) / 60.

            if 'xsin' in components:
                print 'computing DS_x_off_sin'
                t1 = time.time()

                def DS_x_off(theta):
                    gamma_x2 = ((-6 * psi2_off(R, theta) / R**2) -
                                4. * monopole_off(R, theta))
                    return ellip * gamma_x2 * np.sin(2. * theta)

                argumento = lambda x: DS_x_off(x) * np.sin(2. * x)
                integral = integrate.quad(argumento,
                                          0,
                                          2. * np.pi,
                                          points=[np.pi],
                                          epsabs=1.e-01,
                                          epsrel=1.e-01)[0]
                gamma_x_off = np.append(gamma_x_off, integral / np.pi)
                t2 = time.time()
                print 'xsin', R, (t2 - t1) / 60.
            '''

			def DS_t_off(theta):
				gamma_t0 = Delta_Sigma_off(R,theta)
				gamma_t2 = ((-6*psi2_off(R,theta)/R**2) 
							- 2.*monopole_off(R,theta) 
							+ quadrupole_off(R,theta))
				return gamma_t0 + ellip*gamma_t2*np.cos(2.*theta)

			
			
			if 't' in components:
				print 'computing DS_t_off'
				t1 = time.time()
				if ellip == 0.:
					DSoff = Delta_Sigma_off0(R)
					gamma_t_off0 = np.append(gamma_t_off0,DSoff)
				else:
					argumento = lambda x: DS_t_off(x)
					integral  = integrate.quad(argumento, 0., 2.*np.pi,points=[np.pi], epsabs=1.e-01, epsrel=1.e-01)[0]
					gamma_t_off0 = np.append(gamma_t_off0,integral/(2.*np.pi))
				t2 = time.time()
				print (t2-t1)/60.

			
			if 'tcos' in components:	
				print 'computing DS_t_off_cos'
				t1 = time.time()
				argumento = lambda x: DS_t_off(x)*np.cos(2.*x)
				integral  = integrate.quad(argumento, 0., 2.*np.pi,points=[np.pi], epsabs=1.e-01, epsrel=1.e-01)[0]
				gamma_t_off = np.append(gamma_t_off,integral/np.pi)
				t2 = time.time()
			 	print (t2-t1)/60.
			 	
			if 'xsin' in components:
				print 'computing DS_x_off_sin'
				t1 = time.time()
				def DS_x_off(theta):
					gamma_x2 = ((-6*psi2_off(R,theta)/R**2) 
								- 4.*monopole_off(R,theta))
					return ellip*gamma_x2*np.sin(2.*theta)
				argumento = lambda x: DS_x_off(x)*np.sin(2.*x)
				integral  = integrate.quad(argumento, 0, 2.*np.pi,points=[np.pi], epsabs=1.e-01, epsrel=1.e-01)[0]
				gamma_x_off = np.append(gamma_x_off,integral/np.pi)	
				t2 = time.time()
				print 'xsin',R,(t2-t1)/60.			 	
						
			'''

        return gamma_t0_off, gamma_t_off0, gamma_t_off, gamma_x_off

    gt0, m, q, p2 = quantities_centred(r)
    '''
	vU_Eq18
	
	'''
    gt2 = ellip * ((-6 * p2 / r**2) - 2. * m + q)
    gx2 = ellip * ((-6 * p2 / r**2) - 4. * m)

    output = {'Gt0': gt0, 'Gt2': gt2, 'Gx2': gx2}

    if misscentred:
        gt0_off, gt_off0, gt_off, gx_off = quantities_misscentred(r)
        output.update({
            'Gt0_off': gt0_off,
            'Gt_off': gt_off0,
            'Gt_off_cos': gt_off,
            'Gx_off_sin': gx_off
        })

    enablePrint()

    return output
def main(sample='pru',
         l_min=20.,
         l_max=150.,
         z_min=0.1,
         z_max=0.4,
         RIN=100.,
         ROUT=5000.,
         proxy_angle='theta_sat_w1',
         plim=0.,
         Rn_min=0.,
         Rn_max=1000.,
         ndots=10,
         ncores=10,
         h=0.7):
    '''
        
        INPUT
        ---------------------------------------------------------
        sample         (str) sample name
        l_min          (int) lower limit of galaxy members - >=
        l_max          (int) higher limit of galaxy members - <
        z_min          (float) lower limit for z - >=
        z_max          (float) higher limit for z - <
        RIN            (float) Inner bin radius of profile
        ROUT           (float) Outer bin radius of profile
        proxy_angle    (str) proxy definition of the angle to compute the quadrupole
        plim           (float) Cut in centre probability - select clusters with Pcen > plim
        Rn_min         (float) Mpc - Select clusters with a distance to their neirest neighbour >= Rn_min 
        Rn_max         (float) Mpc - Select clusters with a distance to their neirest neighbour < Rn_max 
        ndots          (int) Number of bins of the profile
        ncores         (int) to run in parallel, number of cores
        h              (float) H0 = 100.*h
        '''

    cosmo = LambdaCDM(H0=100 * h, Om0=0.3, Ode0=0.7)
    tini = time.time()

    print('Sample ', sample)
    print('Selecting groups with:')
    print(l_min, ' <= Lambda < ', l_max)
    print(z_min, ' <= z < ', z_max)
    print(Rn_min, ' <= Rprox < ', Rn_max)
    print('P_cen lim ', plim)
    print('Profile has ', ndots, 'bins')
    print('from ', RIN, 'kpc to ', ROUT, 'kpc')
    print('Angle proxy ', proxy_angle)
    print('h ', h)

    # Defining radial bins
    bines = np.logspace(np.log10(RIN), np.log10(ROUT), num=ndots + 1)
    R = (bines[:-1] + np.diff(bines) * 0.5) * 1.e-3

    #reading cats

    L = Table(f[1].data).to_pandas()
    angles = fits.open(folder + 'SAT_angles.fits')[1].data
    borderid = np.loadtxt(folder + 'redMapperID_border.list')

    zlambda = L.Z_LAMBDA
    zspec = L.Z_SPEC
    Z_c = zspec
    Z_c[Z_c < 0] = zlambda[Z_c < 0]
    L.Z_LAMBDA = Z_c
    Pcen = angles.P_cen
    Rprox = angles.Rprox

    mrich = (L.LAMBDA >= l_min) * (L.LAMBDA < l_max)
    mz = (L.Z_LAMBDA >= z_min) * (L.Z_LAMBDA < z_max)
    mborder = (~np.in1d(L.ID, borderid))
    mpcen = (Pcen > plim)
    mprox = (Rprox >= Rn_min) * (Rprox < Rn_max)
    mlenses = mrich * mz * mborder * mpcen * mprox
    Nlenses = mlenses.sum()

    if Nlenses < ncores:
        ncores = Nlenses

    print('Nlenses', Nlenses)
    print('CORRIENDO EN ', ncores, ' CORES')

    # A = fits.open('/mnt/clemente/lensing/RodriguezGroups/angle_Rgroups_FINAL.fits')[1].data
    # theta  = A.theta[mlenses]

    L = L[mlenses]

    if 'control' in proxy_angle:
        theta = np.zeros(sum(mlenses))
        print('entro en control')
    else:
        theta = angles[mlenses][proxy_angle]

    # SPLIT LENSING CAT

    lbins = int(round(Nlenses / float(ncores), 0))
    slices = ((np.arange(lbins) + 1) * ncores).astype(int)
    slices = slices[(slices < Nlenses)]
    Lsplit = np.split(L.iloc[:], slices)
    Tsplit = np.split(theta, slices)

    # WHERE THE SUMS ARE GOING TO BE SAVED

    DSIGMAwsum_T = np.zeros(ndots)
    DSIGMAwsum_X = np.zeros(ndots)
    WEIGHTsum = np.zeros(ndots)
    Mwsum = np.zeros(ndots)

    BOOTwsum_T = np.zeros((100, ndots))
    BOOTwsum_X = np.zeros((100, ndots))
    BOOTwsum = np.zeros((100, ndots))

    GAMMATcos_wsum = np.zeros(ndots)
    GAMMAXsin_wsum = np.zeros(ndots)
    WEIGHTcos_sum = np.zeros(ndots)
    WEIGHTsin_sum = np.zeros(ndots)

    BOOTwsum_Tcos = np.zeros((100, ndots))
    BOOTwsum_Xsin = np.zeros((100, ndots))
    BOOTwsum_cos = np.zeros((100, ndots))
    BOOTwsum_sin = np.zeros((100, ndots))

    Ntot = []
    tslice = np.array([])

    for l in range(len(Lsplit)):

        print('RUN ', l + 1, ' OF ', len(Lsplit))

        t1 = time.time()

        num = len(Lsplit[l])

        rin = RIN * np.ones(num)
        rout = ROUT * np.ones(num)
        nd = ndots * np.ones(num)

        if num == 1:
            entrada = [
                Lsplit[l].CATID.iloc[0], Lsplit[l].RA.iloc[0],
                Lsplit[l].DEC.iloc[0], Lsplit[l].Z_LAMBDA.iloc[0],
                Tsplit[l][0], RIN, ROUT, ndots
            ]

            salida = [partial_profile_unpack(entrada)]
        else:
            entrada = np.array([
                Lsplit[l].CATID.iloc[:], Lsplit[l].RA, Lsplit[l].DEC,
                Lsplit[l].Z_LAMBDA, Tsplit[l][:], rin, rout, nd
            ]).T

            pool = Pool(processes=(num))
            salida = np.array(pool.map(partial_profile_unpack, entrada))
            pool.terminate()

        for profilesums in salida:

            DSIGMAwsum_T += profilesums['DSIGMAwsum_T']
            DSIGMAwsum_X += profilesums['DSIGMAwsum_X']
            WEIGHTsum += profilesums['WEIGHTsum']
            Mwsum += profilesums['Mwsum']

            BOOTwsum_T += profilesums['BOOTwsum_T']
            BOOTwsum_X += profilesums['BOOTwsum_X']
            BOOTwsum += profilesums['BOOTwsum']

            GAMMATcos_wsum += profilesums['GAMMATcos_wsum']
            GAMMAXsin_wsum += profilesums['GAMMAXsin_wsum']
            WEIGHTcos_sum += profilesums['WEIGHTcos_sum']
            WEIGHTsin_sum += profilesums['WEIGHTsin_sum']

            BOOTwsum_Tcos += profilesums['BOOTwsum_Tcos']
            BOOTwsum_Xsin += profilesums['BOOTwsum_Xsin']
            BOOTwsum_cos += profilesums['BOOTwsum_cos']
            BOOTwsum_sin += profilesums['BOOTwsum_sin']

            Ntot = np.append(Ntot, profilesums['Ntot'])

        t2 = time.time()
        ts = (t2 - t1) / 60.
        tslice = np.append(tslice, ts)
        print('TIME SLICE')
        print(ts)
        print('Estimated ramaining time')
        print(np.mean(tslice) * (len(Lsplit) - (l + 1)))

    # COMPUTING PROFILE

    Mcorr = Mwsum / WEIGHTsum
    DSigma_T = (DSIGMAwsum_T / WEIGHTsum) / (1 + Mcorr)
    DSigma_X = (DSIGMAwsum_X / WEIGHTsum) / (1 + Mcorr)
    eDSigma_T = np.std((BOOTwsum_T / BOOTwsum), axis=0) / (1 + Mcorr)
    eDSigma_X = np.std((BOOTwsum_X / BOOTwsum), axis=0) / (1 + Mcorr)

    GAMMA_Tcos = (GAMMATcos_wsum / WEIGHTcos_sum) / (1 + Mcorr)
    GAMMA_Xsin = (GAMMAXsin_wsum / WEIGHTsin_sum) / (1 + Mcorr)
    eGAMMA_Tcos = np.std((BOOTwsum_Tcos / BOOTwsum_cos), axis=0) / (1 + Mcorr)
    eGAMMA_Xsin = np.std((BOOTwsum_Xsin / BOOTwsum_sin), axis=0) / (1 + Mcorr)

    # AVERAGE LENS PARAMETERS

    zmean = np.average(L.Z_LAMBDA, weights=Ntot)
    l_mean = np.average(L.LAMBDA, weights=Ntot)

    # FITING AN NFW MODEL

    H = cosmo.H(zmean).value / (1.0e3 * pc)  #H at z_pair s-1
    roc = (3.0 *
           (H**2.0)) / (8.0 * np.pi * G)  #critical density at z_pair (kg.m-3)
    roc_mpc = roc * ((pc * 1.0e6)**3.0)

    try:
        nfw = NFW_stack_fit(R, DSigma_T, eDSigma_T, zmean, roc)
    except:
        nfw = [0.01, 0., 100., [0., 0.], [0., 0.], -999., 0.]

    M200_NFW = (800.0 * np.pi * roc_mpc * (nfw[0]**3)) / (3.0 * Msun)
    e_M200_NFW = ((800.0 * np.pi * roc_mpc * (nfw[0]**2)) / (Msun)) * nfw[1]
    le_M200 = (np.log(10.) / M200_NFW) * e_M200_NFW

    # WRITING OUTPUT FITS FILE

    tbhdu = fits.BinTableHDU.from_columns([
        fits.Column(name='Rp', format='D', array=R),
        fits.Column(name='DSigma_T', format='D', array=DSigma_T),
        fits.Column(name='error_DSigma_T', format='D', array=eDSigma_T),
        fits.Column(name='DSigma_X', format='D', array=DSigma_X),
        fits.Column(name='error_DSigma_X', format='D', array=eDSigma_X),
        fits.Column(name='GAMMA_Tcos', format='D', array=GAMMA_Tcos),
        fits.Column(name='error_GAMMA_Tcos', format='D', array=eGAMMA_Tcos),
        fits.Column(name='GAMMA_Xsin', format='D', array=GAMMA_Xsin),
        fits.Column(name='error_GAMMA_Xsin', format='D', array=eGAMMA_Xsin)
    ])

    h = tbhdu.header
    h.append(('N_LENSES', np.int(Nlenses)))
    h.append(('l_min', np.int(l_min)))
    h.append(('l_max', np.int(l_max)))
    h.append(('z_min', np.round(z_min, 4)))
    h.append(('z_max', np.round(z_max, 4)))
    h.append(('Rn_min', np.round(Rn_min, 4)))
    h.append(('Rn_max', np.round(Rn_max, 4)))
    h.append(('plim', np.round(plim, 4)))
    h.append(('lM200_NFW', np.round(np.log10(M200_NFW), 4)))
    h.append(('elM200_NFW', np.round(le_M200, 4)))
    h.append(('CHI2_NFW', np.round(nfw[2], 4)))
    h.append(('l_mean', np.round(l_mean, 4)))
    h.append(('z_mean', np.round(zmean, 4)))

    tbhdu.writeto(folder + 'profile_' + sample + '.fits', overwrite=True)

    tfin = time.time()

    print('TOTAL TIME ', (tfin - tini) / 60.)
Example #6
0
epcc_c = np.array([outc[15], outc[16]])

ratio_pcc, eratio_pcc = ratio(pcc_c, epcc_c, pcc, epcc)
ratio_pcc_T, eratio_pcc_T = ratio(pcc_cT, epcc_cT, pcc_T, epcc_T)

ratio_pcc = np.append(ratio_pcc, ratio_pcc_T)
eratio_pcc = np.append(eratio_pcc, eratio_pcc_T)

lMH2 = np.append(lMH, lMH_T)

N = out[3]
mN1 = N == 1
mN23 = (N > 1) * (N < 4)
mN4M = (N > 3)

H = cosmo.H(out[9][mN4M]).value / (1.0e3 * pc)  #H at z_pair s-1
M200_SIS = ((2. * (sdisp * 1.e3)**3) / ((50**0.5) * G * H)) / (Msun)

lMdyn2 = np.log10(M200_SIS)


def y(x, alpha):
    return np.log10(1.e14 * ((x / 500.)**(alpha)))


x = np.arange(250, 600, 20)
fig = plt.figure()
ax1 = fig.add_subplot(111)
# ax2 = ax1.twiny()
ax1.plot(sdisp, lM200[mN4M], 'C8s', ms=8)
ax1.errorbar(sdisp, lM200[mN4M], yerr=elM200[:, mN4M], fmt='none', ecolor='C8')
Example #7
0
class MPShear:
    """
    Equations from van Uitert (vU, arXiv:1610.04226) for the
    multipole expansion and from Ford et al. (F,2015) for
    the misscentring

    INPUTS:
    r               [Mpc] - Float or numpy_array
                    Distance to the centre of
                    the gravitational potential

    OPTIONAL:
    M200            [M_sun] - Float/ Cluster Mass
    ellip           Float / Halo ellipticity defined as
                    (1-q)/(1+q) where q is the semi-axis
                    ratio (q < 1)
    z               Float/ Lens redshift
    zs              Float/ Source redshift
    h               Float/ Cosmological quantity
    misscentred     Float/ If True computes de misscentred quantities
                    The misscentred is considered only in the
                    x - axis
    s_off           [Mpc h-1] Float/ sigma_offset width of the distribution
                    of cluster offsets (F_Eq11)
    components      List of misscentred components that are going
                    to be computed:
                    't0'   -> Gt0_off
                    't'    -> Gt_off
                    'tcos' -> Gt_off_cos
                    'xsin' -> Gx_off_sin
    verbose         Print time computing
    Yanmiss         if True use Eq 4 to model the miss of Yan et al. 2020

    OUTPUT:
    output          Dictionary (the shear is scales with the
                    critical density Gamma_i = Sigma_cr*gamma_i
                    ---------- vU_Eq18 ---------
                    Gt0: Shear monopole
                    Gt2: Tangential component for the quadrupole
                    Gx2: Cross component for the quadrupole
                    --------- Misscentred terms --------
                    Gt0_off: (ellip = 0) F_Eq14
                    Gt_off: Integrated tangential component (vU_Eq17)
                    for considering kappa_offset
                    Gt_off_cos: Integrated tangential component times
                    cos(2theta) (vU_Eq17) for considering kappa_offset
                    Gx_off_sin: Integrated cross component times
                    sin(2theta) (vU_Eq17) for considering kappa_offset
    """

    cvel = 299792458  # Speed of light (m.s-1)
    G = 6.670e-11  # Gravitational constant (m3.kg-1.s-2)
    pc = 3.085678e16  # 1 pc (m)
    Msun = 1.989e30  # Solar mass (kg)

    def __init__(self,
                 r,
                 M200=1.e14,
                 ellip=0.25,
                 z=0.2,
                 h=0.7,
                 misscentred=False,
                 s_off=0.4,
                 components=['t0', 't', 'tcos', 'xsin'],
                 verbose=True,
                 Yanmiss=False):
        """
        init method, it sets up all variables
        """

        if not isinstance(r, (np.ndarray)):
            r = np.array([r])

        self.r = r
        self.M200 = M200
        self.ellip = ellip
        self.z = z
        self.h = h
        self.misscentred = misscentred
        self.s_off = s_off
        self.components = components
        self.verbose = verbose
        self.Yanmiss = Yanmiss

        # Compute cosmological parameters
        self.cosmo = LambdaCDM(H0=self.h * 100, Om0=0.3, Ode0=0.7)
        # H at z_pair s-1
        self.H = self.cosmo.H(self.z).value / (1.0e3 * self.pc)
        # critical density at z_pair (kg.m-3)
        self.roc = (3.0 * (self.H**2.0)) / (8.0 * np.pi * self.G)
        self.roc_mpc = self.roc * ((self.pc * 1.0e6)**3.0)

        # Compute R_200
        self.R200 = profiles_fit.r200_nfw(self.M200, self.roc_mpc)

        # Scaling sigma_off
        self.s_off = self.s_off / self.h
Example #8
0
print 'fitting monopole misscentred'
print folder
print file_name

profile = fits.open(folder + file_name)
h = profile[1].header
p = profile[1].data
zmean = h['Z_MEAN']
Mhalo = 10**h['lMASS_HALO_mean']
Rmean = h['RADIUS_HALO_mean']
ROUT = (2.5 * (2. * (Mhalo / 2.21e14)**0.75)**(1. / 3.)) / 0.7

# Compute cosmological parameters
cosmo = LambdaCDM(H0=0.7 * 100, Om0=0.3, Ode0=0.7)
H = cosmo.H(zmean).value / (1.0e3 * pc)  #H at z_pair s-1
roc = (3.0 *
       (H**2.0)) / (8.0 * np.pi * G)  #critical density at z_pair (kg.m-3)
roc_mpc = roc * ((pc * 1.0e6)**3.0)


def log_likelihood(data_model, r, Gamma, e_Gamma):
    log_M200, pcc, soff = data_model
    M200 = 10**log_M200
    multipoles = multipole_shear_parallel(r,
                                          M200=M200,
                                          misscentred=True,
                                          s_off=soff,
                                          ellip=0,
                                          z=zmean,
                                          components=['t'],
Example #9
0
def plt_map_fitted(samp, RIN, ROUT, fittype=''):

    m_name = '../maps/map_' + samp + '.fits'
    mapa = fits.open(folder + m_name)

    p_name = 'profile_' + samp + '.fits'
    profile = fits.open(folder + p_name)

    print(p_name)

    # '''
    h = profile[0].header
    p = profile[1].data
    m = mapa[1].data

    print(p_name)

    cosmo = LambdaCDM(H0=100 * h['hcosmo'], Om0=0.25, Ode0=0.75)
    '''
    
    h = profile[1].header
    p = profile[1].data
    '''

    zmean = h['z_mean']
    q = np.round(h['q2d_mean'], 2)
    qr = np.round(h['q2dr_mean'], 2)

    print('mean q standard', q)
    print('mean q reduced', qr)

    e = (1 - q) / (1 + q)
    er = (1 - qr) / (1 + qr)

    H = cosmo.H(zmean).value / (1.0e3 * pc)  #H at z_pair s-1
    roc = (3.0 *
           (H**2.0)) / (8.0 * np.pi * G)  #critical density at z_pair (kg.m-3)
    roc_mpc = roc * ((pc * 1.0e6)**3.0)

    ndots = p.shape[0]

    S = m.K
    Sr = m.K_reduced
    Sc = m.K_control

    GT = m.GT
    GTr = m.GT_reduced
    GTc = m.GT_control

    GX = m.GX
    GXr = m.GX_reduced
    GXc = m.GX_control

    x = m.xmpc
    y = m.ympc
    theta = np.arctan2(m.ympc, m.xmpc)
    r = np.sqrt(m.xmpc**2 + m.ympc**2)

    # MCMC results

    fitpar = fits.open(folder + 'fitresults' + fittype + '_' + str(int(RIN)) +
                       '_' + str(int(ROUT)) + '_' + p_name)[0].header
    fitpar_red = fits.open(folder + 'fitresults' + fittype + '_' +
                           str(int(RIN)) + '_' + str(int(ROUT)) + '_reduced_' +
                           p_name)[0].header

    efit = (1. - fitpar['q']) / (1. + fitpar['q'])
    efit_red = (1. - fitpar_red['q']) / (1. + fitpar_red['q'])

    R = r * np.sqrt(fitpar['q'] * (np.cos(theta))**2 +
                    (np.sin(theta))**2 / fitpar['q'])
    Rr = r * np.sqrt(fitpar_red['q'] * (np.cos(theta))**2 +
                     (np.sin(theta))**2 / fitpar_red['q'])

    S0_fit = Sigma_NFW(
        r, zmean, M200=10**fitpar['lM200'], c200=fitpar['c200'],
        cosmo=cosmo) / (1.e6**2)
    Se_fit = Sigma_NFW(
        R, zmean, M200=10**fitpar['lM200'], c200=fitpar['c200'],
        cosmo=cosmo) / (1.e6**2)
    Se_fit_red = Sigma_NFW(Rr,
                           zmean,
                           M200=10**fitpar_red['lM200'],
                           c200=fitpar_red['c200'],
                           cosmo=cosmo) / (1.e6**2)

    S2_fit = quadrupole(r,
                        zmean,
                        M200=10**fitpar['lM200'],
                        c200=fitpar['c200'],
                        cosmo=cosmo)

    gt0 = Delta_Sigma_NFW(r,
                          zmean,
                          M200=10**fitpar['lM200'],
                          c200=fitpar['c200'],
                          cosmo=cosmo)

    gtc, gxs = GAMMA_components(r,
                                zmean,
                                ellip=efit,
                                M200=10**fitpar['lM200'],
                                c200=fitpar['c200'],
                                cosmo=cosmo)
    gtc_red, gxs_red = GAMMA_components(r,
                                        zmean,
                                        ellip=efit_red,
                                        M200=10**fitpar_red['lM200'],
                                        c200=fitpar_red['c200'],
                                        cosmo=cosmo)

    GTfit = gt0 + gtc * np.cos(2 * theta)
    GTfit_red = gt0 + gtc_red * np.cos(2 * theta)

    GXfit = gxs * np.sin(2 * theta)
    GXfit_red = gxs_red * np.sin(2 * theta)

    Sfit = S0_fit + efit * S2_fit * np.cos(2 * theta)
    Sfit_red = S0_fit + efit_red * S2_fit * np.cos(2 * theta)

    print('Results standard fit')
    print('log(M200) = ', fitpar['lM200'], ' c200 = ', fitpar['c200'], ' q ',
          fitpar['q'])
    print('Results reduced fit')
    print('log(M200) = ', fitpar_red['lM200'], ' c200 = ', fitpar_red['c200'],
          ' q ', fitpar_red['q'])

    ##############
    # SURFACE DENSITY PLOT
    # JUST MONOPOLE
    f, ax = plt.subplots(1, 2, figsize=(6.5, 3), sharex=True, sharey=True)
    f.subplots_adjust(hspace=0, wspace=0)

    im0 = ax[0].scatter(x, y, c=Sc, vmin=-10, cmap='cividis', vmax=50.)
    ax[1].scatter(x, y, c=S0_fit, vmin=-10, cmap='cividis', vmax=50.)

    ax[0].set_title('S0_MICE')
    ax[1].set_title('S0_fit')

    ax[0].set_ylabel('y [Mpc]')
    ax[1].set_xlabel('x [Mpc]')
    ax[0].set_xlabel('x [Mpc]')

    f.colorbar(im0, ax=ax, orientation='vertical', fraction=.05)
    f.savefig(folder + '../maps/plots/map_S0_' + samp + fittype + '.png',
              bbox_inches='tight')

    # Res
    f, ax = plt.subplots(1, 1, figsize=(3.5, 3), sharex=True, sharey=True)
    f.subplots_adjust(hspace=0, wspace=0)

    im0 = ax.scatter(x, y, c=Sc - S0_fit, vmin=-10, cmap='cividis', vmax=10.)

    ax.set_title('S0_MICE - S0_fit')

    ax.set_ylabel('y [Mpc]')
    ax.set_xlabel('x [Mpc]')

    f.colorbar(im0, ax=ax, orientation='vertical', fraction=.05)
    f.savefig(folder + '../maps/plots/map_S0_res_' + samp + fittype + '.png',
              bbox_inches='tight')

    # S(R)

    f, ax = plt.subplots(2, 2, figsize=(6.5, 6), sharex=True, sharey=True)
    f.subplots_adjust(hspace=0, wspace=0)

    im0 = ax[0, 0].scatter(x, y, c=S, vmin=-10, cmap='cividis', vmax=50.)
    ax[0, 1].scatter(x, y, c=Se_fit, vmin=-10, cmap='cividis', vmax=50.)

    ax[1, 0].scatter(x, y, c=Sr, vmin=-10, cmap='cividis', vmax=50.)
    ax[1, 1].scatter(x, y, c=Se_fit_red, vmin=-10, cmap='cividis', vmax=50.)

    ax[0, 0].set_ylabel('y [Mpc]')
    ax[1, 0].set_ylabel('y [Mpc]')
    ax[1, 1].set_xlabel('x [Mpc]')
    ax[1, 0].set_xlabel('x [Mpc]')

    ax[0, 0].set_title('S_MICE')
    ax[0, 1].set_title('S_fit(R)')

    f.colorbar(im0, ax=ax, orientation='vertical', fraction=.05)
    f.savefig(folder + '../maps/plots/map_SR_' + samp + fittype + '.png',
              bbox_inches='tight')

    # Res
    f, ax = plt.subplots(2, figsize=(3.5, 6), sharex=True, sharey=True)
    f.subplots_adjust(hspace=0, wspace=0)

    im0 = ax[0].scatter(x, y, c=S - Se_fit, vmin=-10, cmap='cividis', vmax=10.)
    ax[1].scatter(x, y, c=Sr - Se_fit_red, vmin=-10, cmap='cividis', vmax=10.)

    ax[0].set_ylabel('y [Mpc]')
    ax[1].set_ylabel('y [Mpc]')
    ax[1].set_xlabel('x [Mpc]')

    ax[0].set_title('S_MICE - S_fit(R)')

    f.colorbar(im0, ax=ax, orientation='vertical', fraction=.05)
    f.savefig(folder + '../maps/plots/map_SR_res_' + samp + fittype + '.png',
              bbox_inches='tight')

    # S(r) + S2

    f, ax = plt.subplots(2, 2, figsize=(6.5, 6), sharex=True, sharey=True)
    f.subplots_adjust(hspace=0, wspace=0)

    im0 = ax[0, 0].scatter(x, y, c=S, vmin=-10, cmap='cividis', vmax=50.)
    ax[0, 1].scatter(x, y, c=Sfit, vmin=-10, cmap='cividis', vmax=50.)

    ax[1, 0].scatter(x, y, c=Sr, vmin=-10, cmap='cividis', vmax=50.)
    ax[1, 1].scatter(x, y, c=Sfit_red, vmin=-10, cmap='cividis', vmax=50.)

    ax[0, 0].set_ylabel('y [Mpc]')
    ax[1, 0].set_ylabel('y [Mpc]')
    ax[1, 1].set_xlabel('x [Mpc]')
    ax[1, 0].set_xlabel('x [Mpc]')

    ax[0, 0].set_title('S_MICE')
    ax[0, 1].set_title('S0 + e*S2')

    f.colorbar(im0, ax=ax, orientation='vertical', fraction=.05)
    f.savefig(folder + '../maps/plots/map_S_' + samp + fittype + '.png',
              bbox_inches='tight')

    # Res
    f, ax = plt.subplots(2, figsize=(3.5, 6), sharex=True, sharey=True)
    f.subplots_adjust(hspace=0, wspace=0)

    im0 = ax[0].scatter(x, y, c=S - Se_fit, vmin=-10, cmap='cividis', vmax=10.)
    ax[1].scatter(x, y, c=Sr - Se_fit_red, vmin=-10, cmap='cividis', vmax=10.)

    ax[0].set_ylabel('y [Mpc]')
    ax[1].set_ylabel('y [Mpc]')
    ax[1].set_xlabel('x [Mpc]')

    ax[0].set_title('S_MICE - (S0 + e*S2)')

    f.colorbar(im0, ax=ax, orientation='vertical', fraction=.05)
    f.savefig(folder + '../maps/plots/map_S_res_' + samp + fittype + '.png',
              bbox_inches='tight')

    # QUADRUPOLES
    # GTcos

    f, ax = plt.subplots(2, 2, figsize=(6.5, 6), sharex=True, sharey=True)
    f.subplots_adjust(hspace=0, wspace=0)

    im0 = ax[0, 0].scatter(x,
                           y,
                           c=GT - gt0,
                           vmin=-10,
                           cmap='cividis',
                           vmax=50.)
    ax[0, 1].scatter(x,
                     y,
                     c=gtc * np.cos(2. * theta),
                     vmin=-10,
                     cmap='cividis',
                     vmax=50.)

    ax[1, 0].scatter(x, y, c=GTr - gt0, vmin=-10, cmap='cividis', vmax=50.)
    ax[1, 1].scatter(x,
                     y,
                     c=gtc_red * np.cos(2. * theta),
                     vmin=-10,
                     cmap='cividis',
                     vmax=50.)

    ax[0, 0].set_ylabel('y [Mpc]')
    ax[1, 0].set_ylabel('y [Mpc]')
    ax[1, 1].set_xlabel('x [Mpc]')
    ax[1, 0].set_xlabel('x [Mpc]')

    ax[0, 0].set_title('GT_MICE')
    ax[0, 1].set_title('GT_fit')

    f.colorbar(im0, ax=ax, orientation='vertical', fraction=.05)
    f.savefig(folder + '../maps/plots/map_GTcos_' + samp + fittype + '.png',
              bbox_inches='tight')

    f, ax = plt.subplots(2, 2, figsize=(6.5, 6), sharex=True, sharey=True)
    f.subplots_adjust(hspace=0, wspace=0)

    im0 = ax[0, 0].scatter(x, y, c=GT, vmin=-10, cmap='cividis', vmax=50.)
    ax[0, 1].scatter(x, y, c=GTfit, vmin=-10, cmap='cividis', vmax=50.)

    ax[1, 0].scatter(x, y, c=GTr, vmin=-10, cmap='cividis', vmax=50.)
    ax[1, 1].scatter(x, y, c=GTfit_red, vmin=-10, cmap='cividis', vmax=50.)

    ax[0, 0].set_ylabel('y [Mpc]')
    ax[1, 0].set_ylabel('y [Mpc]')
    ax[1, 1].set_xlabel('x [Mpc]')
    ax[1, 0].set_xlabel('x [Mpc]')

    ax[0, 0].set_title('GT_MICE')
    ax[0, 1].set_title('GT_fit')

    f.colorbar(im0, ax=ax, orientation='vertical', fraction=.05)
    f.savefig(folder + '../maps/plots/map_GT_' + samp + fittype + '.png',
              bbox_inches='tight')

    # Res
    f, ax = plt.subplots(2, figsize=(3.5, 6), sharex=True, sharey=True)
    f.subplots_adjust(hspace=0, wspace=0)

    im0 = ax[0].scatter(x, y, c=GT - GTfit, vmin=-10, cmap='cividis', vmax=10.)
    ax[1].scatter(x, y, c=GTr - GTfit_red, vmin=-10, cmap='cividis', vmax=10.)

    ax[0].set_ylabel('y [Mpc]')
    ax[1].set_ylabel('y [Mpc]')
    ax[1].set_xlabel('x [Mpc]')

    ax[0].set_title('GT - (gt0 + e*gt2)')

    f.colorbar(im0, ax=ax, orientation='vertical', fraction=.05)
    f.savefig(folder + '../maps/plots/map_GT_res_' + samp + fittype + '.png',
              bbox_inches='tight')

    # QUADRUPOLES
    # GX

    f, ax = plt.subplots(2, 2, figsize=(6.5, 6), sharex=True, sharey=True)
    f.subplots_adjust(hspace=0, wspace=0)

    im0 = ax[0, 0].scatter(x, y, c=GX, vmin=-10, cmap='cividis', vmax=10.)
    ax[0, 1].scatter(x, y, c=GXfit, vmin=-10, cmap='cividis', vmax=10.)

    ax[1, 0].scatter(x, y, c=GXr, vmin=-10, cmap='cividis', vmax=10.)
    ax[1, 1].scatter(x, y, c=GXfit_red, vmin=-10, cmap='cividis', vmax=10.)

    ax[0, 0].set_ylabel('y [Mpc]')
    ax[1, 0].set_ylabel('y [Mpc]')
    ax[1, 1].set_xlabel('x [Mpc]')
    ax[1, 0].set_xlabel('x [Mpc]')

    ax[0, 0].set_title('GX_MICE')
    ax[0, 1].set_title('GX_fit')

    f.colorbar(im0, ax=ax, orientation='vertical', fraction=.05)
    f.savefig(folder + '../maps/plots/map_GX_' + samp + fittype + '.png',
              bbox_inches='tight')

    # Res
    f, ax = plt.subplots(2, figsize=(3.5, 6), sharex=True, sharey=True)
    f.subplots_adjust(hspace=0, wspace=0)

    im0 = ax[0].scatter(x, y, c=GX - GXfit, vmin=-10, cmap='cividis', vmax=10.)
    ax[1].scatter(x, y, c=GXr - GXfit_red, vmin=-10, cmap='cividis', vmax=10.)

    ax[0].set_ylabel('y [Mpc]')
    ax[1].set_ylabel('y [Mpc]')
    ax[1].set_xlabel('x [Mpc]')

    ax[0].set_title('GX - (e*gx2)')

    f.colorbar(im0, ax=ax, orientation='vertical', fraction=.05)
    f.savefig(folder + '../maps/plots/map_GX_res_' + samp + fittype + '.png',
              bbox_inches='tight')
Example #10
0
def plt_profile_fitted_2h_2q(samp,
                             RIN,
                             ROUT,
                             fittype='_2h_2q',
                             substract=False,
                             component='',
                             terms='1h+2h',
                             pname='NFW'):

    p_name = 'profile_' + samp + '.fits'
    profile = fits.open(folder + p_name)

    print(p_name)

    # '''
    h = profile[0].header
    p = profile[1].data
    cov = profile[2].data

    cosmo = LambdaCDM(H0=100 * h['hcosmo'], Om0=0.25, Ode0=0.75)
    params = {
        'flat': True,
        'H0': 70.0,
        'Om0': 0.25,
        'Ob0': 0.044,
        'sigma8': 0.8,
        'ns': 0.95
    }
    '''
    
    h = profile[1].header
    p = profile[1].data
    '''

    zmean = h['z_mean']
    q = np.round(h['q2d_mean'], 2)
    qr = np.round(h['q2dr_mean'], 2)

    print('mean q standard', q)
    print('mean q reduced', qr)

    e = (1 - q) / (1 + q)
    er = (1 - qr) / (1 + qr)

    H = cosmo.H(zmean).value / (1.0e3 * pc)  #H at z_pair s-1
    roc = (3.0 *
           (H**2.0)) / (8.0 * np.pi * G)  #critical density at z_pair (kg.m-3)
    roc_mpc = roc * ((pc * 1.0e6)**3.0)

    ndots = p.shape[0]

    GT = p.GAMMA_Tcos
    GTr = p.GAMMA_Tcos_reduced
    GTc = p.GAMMA_Tcos_control

    GX = p.GAMMA_Xsin
    GXr = p.GAMMA_Xsin_reduced
    GXc = p.GAMMA_Xsin_control

    # '''
    CovDS = cov.COV_ST.reshape(len(GT), len(GT))
    CovS = cov.COV_S.reshape(len(GT), len(GT))

    CovGT = cov.COV_GT.reshape(len(GT), len(GT))
    CovGTr = cov.COV_GT_reduced.reshape(len(GT), len(GT))
    CovGTc = cov.COV_GT_control.reshape(len(GT), len(GT))

    CovGX = cov.COV_GX.reshape(len(GT), len(GT))
    CovGXr = cov.COV_GX_reduced.reshape(len(GT), len(GT))
    CovGXc = cov.COV_GX_control.reshape(len(GT), len(GT))

    rplot = np.round(p.Rp, 2)

    # MCMC results

    # fitpar = fits.open(folder+'fitresults_2h_250_2000_'+p_name)[0].header
    # fitpar_red = fits.open(folder+'fitresults_2h_250_5000_reduced_'+p_name)[0].header

    fitpar = fits.open(folder + 'fitresults' + fittype + component + '_' +
                       str(int(RIN)) + '_' + str(int(ROUT)) + '_' +
                       p_name)[0].header
    fitpar_red = fits.open(folder + 'fitresults' + fittype + component + '_' +
                           str(int(RIN)) + '_' + str(int(ROUT)) + '_reduced_' +
                           p_name)[0].header

    fitd = fits.open(folder + 'fitresults' + fittype + component + '_' +
                     str(int(RIN)) + '_' + str(int(ROUT)) + '_' +
                     p_name)[1].data
    fitd_red = fits.open(folder + 'fitresults' + fittype + component + '_' +
                         str(int(RIN)) + '_' + str(int(ROUT)) + '_reduced_' +
                         p_name)[1].data

    efit = (1. - fitpar['q']) / (1. + fitpar['q'])
    efit_red = (1. - fitpar_red['q']) / (1. + fitpar_red['q'])

    efit2h = (1. - fitpar['q2h']) / (1. + fitpar['q2h'])
    efit_red2h = (1. - fitpar_red['q']) / (1. + fitpar_red['q'])

    DS = Delta_Sigma_NFW_2h(rplot,
                            zmean,
                            M200=10**fitpar['lM200'],
                            c200=fitpar['c200'],
                            cosmo_params=params,
                            terms=terms)
    DSr = DS

    gt1h, gx1h = GAMMA_components(rplot,
                                  zmean,
                                  ellip=efit,
                                  M200=10**fitpar['lM200'],
                                  c200=fitpar['c200'],
                                  cosmo_params=params,
                                  terms='1h',
                                  pname=pname)
    gt1hr, gx1hr = GAMMA_components(rplot,
                                    zmean,
                                    ellip=efit_red,
                                    M200=10**fitpar_red['lM200'],
                                    c200=fitpar_red['c200'],
                                    cosmo_params=params,
                                    terms='1h',
                                    pname=pname)

    gt2h, gx2h = GAMMA_components(rplot,
                                  zmean,
                                  ellip=efit2h,
                                  M200=10**fitpar['lM200'],
                                  c200=fitpar['c200'],
                                  cosmo_params=params,
                                  terms='2h',
                                  pname=pname)
    gt2hr, gx2hr = GAMMA_components(rplot,
                                    zmean,
                                    ellip=efit_red2h,
                                    M200=10**fitpar_red['lM200'],
                                    c200=fitpar_red['c200'],
                                    cosmo_params=params,
                                    terms='2h',
                                    pname=pname)

    gt = gt1h + gt2h
    gtr = gt1hr + gt2hr
    gx = gx1h + gx2h
    gxr = gx1hr + gx2hr

    print('Results standard fit')
    print('log(M200) = ', fitpar['lM200'], ' c200 = ', fitpar['c200'], ' q ',
          fitpar['q'])
    print('Results reduced fit')
    print('log(M200) = ', fitpar_red['lM200'], ' c200 = ', fitpar_red['c200'],
          ' q ', fitpar_red['q'])

    ##############
    mass = str(np.round(fitpar['lM200'], 2))
    c200 = str(np.round(fitpar['c200'], 2))
    qfit = str(np.round(fitpar['q'], 2))
    qfit2h = str(np.round(fitpar['q2h'], 2))

    mass_red = str(np.round(fitpar_red['lM200'], 2))
    c200_red = str(np.round(fitpar_red['c200'], 2))
    qfit_red = str(np.round(fitpar_red['q'], 2))
    qfit2h_red = str(np.round(fitpar_red['q2h'], 2))

    f, ax_all = plt.subplots(2, 2, figsize=(12, 8), sharex=True)
    f.subplots_adjust(hspace=0)
    ax, ax1, ax2, ax3 = ax_all[0, 0], ax_all[0, 1], ax_all[1, 0], ax_all[1, 1]

    if substract:
        GT = GT - GTc
        GTr = GTr - GTc
        GX = GX - GXc
        GXr = GXr - GXc
        p.DSigma_T = p.DSigma_T - p.DSigma_X

    ax.set_title(p_name + fittype + component)

    ax.plot(p.Rp, p.DSigma_T, 'C1')
    ax.plot(rplot,
            DS,
            'C3',
            label='$\log M_{200}=$' + mass + ', $c_{200} = $' + c200)
    ax.plot(rplot,
            DSr,
            'C3--',
            label='$\log M_{200}=$' + mass_red + ', $c_{200} = $' + c200_red)
    ax.fill_between(p.Rp,
                    p.DSigma_T + np.diag(CovDS),
                    p.DSigma_T - np.diag(CovDS),
                    color='C1',
                    alpha=0.4)
    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.set_ylabel(r'$\Delta\Sigma$')
    ax.set_xlabel('r [$h^{-1}$ Mpc]')
    ax.set_ylim(2, 200)
    ax.set_xlim(0.1, 10)
    ax.xaxis.set_ticks([0.1, 1, 5, 7])
    ax.set_xticklabels([0.1, 1, 5, 7])
    ax.yaxis.set_ticks([5, 10, 100])
    ax.set_yticklabels([5, 10, 100])
    ax.axvline(RIN / 1000., color='C7')
    ax.axvline(ROUT / 1000., color='C7')
    ax.legend(loc=3, frameon=False)

    # ax1.plot(RMt[0]*0.7,RMt[1]/0.7,'k',label='redMaPPer')
    # ax1.errorbar(RMt[0]*0.7,RMt[1]/0.7,yerr=RMt[2]/0.7,fmt = 'none',ecolor='0.5')

    ax1.plot(p.Rp, GT, 'C4')
    ax1.plot(p.Rp, GTr, 'C0--')
    ax1.plot(rplot,
             gt,
             'C3',
             label='$q_{fit} = $' + qfit + ', $q_{2h} = $' + qfit2h +
             ', $q = $' + str(q))
    ax1.plot(rplot,
             gtr,
             'C3--',
             label='$q_{fit} = $' + qfit_red + ', $q_{2h} = $' + qfit2h_red +
             ', $q = $' + str(qr))
    # ax1.plot(rplot,gt1h,'C2',lw=2)
    # ax1.plot(rplot,gt2h,'C2',lw=1)
    # ax1.plot(rplot,gt1hr,'C2--',lw=2)
    # ax1.plot(rplot,gt2hr,'C2--',lw=1)

    ax1.legend(loc=3, frameon=False)

    ax1.fill_between(p.Rp,
                     GT + np.diag(CovGT),
                     GT - np.diag(CovGT),
                     color='C4',
                     alpha=0.4)
    ax1.fill_between(p.Rp,
                     GTr + np.diag(CovGTr),
                     GTr - np.diag(CovGTr),
                     color='C0',
                     alpha=0.4)
    ax1.set_xscale('log')
    ax1.set_yscale('log')
    ax1.set_xlabel('r [$h^{-1}$ Mpc]')
    ax1.set_ylabel(r'$\Gamma_T$')
    ax1.set_ylim(1, 100)
    ax1.set_xlim(0.1, 10)
    ax1.xaxis.set_ticks([0.1, 1, 5, 7])
    ax1.set_xticklabels([0.1, 1, 5, 7])
    ax1.yaxis.set_ticks([0.3, 10, 100])
    ax1.set_yticklabels([0.3, 10, 100])
    ax1.axvline(RIN / 1000., color='C7')
    ax1.axvline(ROUT / 1000., color='C7')

    # ax2.plot(RMt[0]*0.7,RMt[3]/0.7,'k',label='redMaPPer')
    # ax2.errorbar(RMt[0]*0.7,RMt[3]/0.7,yerr=RMt[4]/0.7,fmt = 'none',ecolor='0.5')

    ax2.plot([0, 10], [0, 0], 'C7')
    ax2.plot(p.Rp, GX, 'C2')
    ax2.plot(p.Rp, GXr, 'C5--')
    ax2.plot(rplot, gx, 'C3')
    ax2.plot(rplot, gxr, 'C3--')
    # ax2.plot(rplot,gx1h,'C2',lw=2)
    # ax2.plot(rplot,gx2h,'C2',lw=1)
    # ax2.plot(rplot,gx1hr,'C2--',lw=2)
    # ax2.plot(rplot,gx2hr,'C2--',lw=1)
    ax2.axvline(RIN / 1000., color='C7')
    ax2.axvline(ROUT / 1000., color='C7')

    ax2.fill_between(p.Rp,
                     GX + np.diag(CovGX),
                     GX - np.diag(CovGX),
                     color='C2',
                     alpha=0.4)
    ax2.fill_between(p.Rp,
                     GXr + np.diag(CovGXr),
                     GXr - np.diag(CovGXr),
                     color='C5',
                     alpha=0.4)
    ax2.set_xlabel('r [$h^{-1}$ Mpc]')
    ax2.set_ylabel(r'$\Gamma_\times$')
    ax2.set_xscale('log')
    ax2.set_xlim(0.1, 10)
    ax2.set_ylim(-20, 16)
    ax2.xaxis.set_ticks([0.1, 1, 5, 7])
    ax2.set_xticklabels([0.1, 1, 5, 7])

    ax3.plot([0, 10], [0, 0], 'C7')
    ax3.plot(p.Rp, GTc, 'k', label='GT control')
    ax3.plot(p.Rp, GXc, 'C8--', label='GX control')
    ax3.fill_between(p.Rp,
                     GXc + np.diag(CovGXc),
                     GXc - np.diag(CovGXc),
                     color='C8',
                     alpha=0.4)
    ax3.fill_between(p.Rp,
                     GTc + np.diag(CovGTc),
                     GTc - np.diag(CovGTc),
                     color='C7',
                     alpha=0.4)
    ax3.set_xlabel('r [$h^{-1}$ Mpc]')
    ax3.set_xscale('log')
    ax3.set_xlim(0.1, 10)
    ax3.set_ylim(-20, 16)
    ax3.xaxis.set_ticks([0.1, 1, 5, 7])
    ax3.set_xticklabels([0.1, 1, 5, 7])
    ax3.legend(frameon=False)

    if substract == True:
        f.savefig(folder + 'plots/profile_' + samp + '_2q_+' + fittype +
                  component + '_substracted.png',
                  bbox_inches='tight')
    else:
        f.savefig(folder + 'plots/profile_' + samp + '_2q_+' + fittype +
                  component + '.png',
                  bbox_inches='tight')

    f, ax = plt.subplots(2, 1, figsize=(12, 4), sharex=True)
    f.subplots_adjust(hspace=0)
    ax[0].plot(fitd.q2h, 'C7', alpha=0.7, label='2h')
    ax[0].plot(fitd.q, 'C6', alpha=0.7, label='1h')
    ax[1].plot(fitd_red.q2h, 'C7', alpha=0.7, label='2h')
    ax[1].plot(fitd_red.q, 'C6', alpha=0.7, label='1h')
    ax[0].legend(frameon=False, loc=1)
    ax[0].set_ylabel('$q$')
    ax[1].set_ylabel('$q_r$')
    ax[1].set_xlabel('$N$')
    f.savefig(folder + 'plots/fit_2q_' + samp + '.png', bbox_inches='tight')