def set_prof(self, prof, vec, pop, gp):
     gh.sanitize_vector(vec, len(self.x0), -200, 1e30, gp.debug)
     if prof == "rho":
         self.rho = vec
     elif prof == "nr":
         self.nr = vec
     elif prof == "J":
         self.J = vec
     elif prof == "M":
         self.M = vec
     elif prof == "nu":
         self.nu[pop * self.nepol : (pop + 1) * self.nepol] = vec  # vec has nrho-3 entries
     elif prof == "nrnu":
         self.nrnu[pop * self.nepol : (pop + 1) * self.nepol] = vec
     elif prof == "betastar":
         self.betastar[pop * self.nepol : (pop + 1) * self.nepol] = vec
     elif prof == "beta":
         self.beta[pop * self.nepol : (pop + 1) * self.nepol] = vec
     elif prof == "Sig":
         self.Sig[pop * self.nepol : (pop + 1) * self.nepol] = vec
     elif prof == "sig":
         self.sig[pop * self.nepol : (pop + 1) * self.nepol] = vec
     elif prof == "kap":
         self.kap[pop * self.nepol : (pop + 1) * self.nepol] = vec
     else:
         raise Exception("unknown profile to be set in gi_class_profiles.set_prof")
 def set_prof(self, prof, vec, pop, gp):
     gh.sanitize_vector(vec, len(self.x0), -200, 1e30, gp.debug)
     if prof == 'rho':
         self.rho = vec
     elif prof == 'nr':
         self.nr = vec
     elif prof == 'J':
         self.J = vec
     elif prof == 'M':
         self.M = vec
     elif prof == 'nu':
         self.nu[pop*self.nepol:(pop+1)*self.nepol] = vec # vec has nrho-3 entries
     elif prof == 'nrnu':
         self.nrnu[pop*self.nepol:(pop+1)*self.nepol] = vec
     elif prof == 'betastar':
         self.betastar[pop*self.nepol:(pop+1)*self.nepol] = vec
     elif prof == 'beta':
         self.beta[pop*self.nepol:(pop+1)*self.nepol] = vec
     elif prof == 'Sig':
         self.Sig[pop*self.nepol:(pop+1)*self.nepol] = vec
     elif prof == 'sig':
         self.sig[pop*self.nepol:(pop+1)*self.nepol] = vec
     elif prof == 'kap':
         self.kap[pop*self.nepol:(pop+1)*self.nepol] = vec
     else:
         raise Exception('unknown profile to be set in gi_class_profiles.set_prof')
Beispiel #3
0
def betastar_4(r0, params, gp):
    gh.sanitize_vector(params, gp.nbeta, -1, max(gp.xepol), gp.debug)
    a0 = params[0]
    a1 = params[1]
    alpha = params[2]
    s0 = np.log(r0 / np.exp(params[3]))  # r_s=params[3] is given in log
    betatmp = (a0 - a1) / (1 + np.exp(alpha * s0)) + a1
    return betatmp
Beispiel #4
0
def betastar_4(r0, params, gp):
    gh.sanitize_vector(params, gp.nbeta, -1, max(gp.xepol), gp.debug)
    a0 = params[0]
    a1 = params[1]
    alpha = params[2]
    s0 = np.log(r0/np.exp(params[3])) # r_s=params[3] is given in log
    betatmp = (a0-a1)/(1+np.exp(alpha*s0))+a1
    return betatmp
Beispiel #5
0
def map_nr_tracers(params, pop, gp):
    gh.sanitize_vector(params, gp.nrho, 0, 1, gp.debug)
    # first, if we already have a Sig-converged run, use the parameters as stored
    if gp.getSigdata:
        return params * (gp.nupar_max - gp.nupar_min) + gp.nupar_min
    nr = np.zeros(gp.nepol)  # to hold the n(r) = dlog(rho)/dlog(r) values
    # get offset and n(r) profiles, calculate rho
    nrscale = gp.nrtol_nu / (max(np.log(gp.xipol)) - min(np.log(gp.xipol)))
    # first parameter gives half-light radius value of rho directly
    # use [0,1]**3 to increase probability of sampling close to 0
    # fix value with tracer densities,
    # sample a flat distribution over log(rho_half)
    rhohalf = 10**((params[0] - 0.5) * 2. * gp.log10nuspread +
                   np.log10(gp.dat.nuhalf[pop]))
    # 10** is correct
    # nr(r=0) is = rho slope for approaching r=0 asymptotically, given directly
    # should be smaller than -3 to exclude infinite enclosed mass
    nrasym0 = params[
        1]**2 * gp.innerslope  # **2 tweaks it toward lower values while still keeping general
    # work directly with the dn(r)/dlog(r) parameters here
    dnrdlrparams = params[1:]

    for k in range(0, gp.nepol):
        deltalogr = (np.log(gp.xepol[k - 1]) - np.log(gp.xepol[k - 2]))
        # construct n(r_k+1) from n(r_k)+dn/dlogr*Delta log r, integrated
        if gp.monotonic_nu:
            # only increase n(r), use pa[i]>=0 directly
            nr[k] = nr[k - 1] + dnrdlrparams[k] * nrscale / 2. * deltalogr
        else:
            # use pa => [-1, 1] for full interval
            scal = nrscale
            # check whether we are in extension bins
            if k < 3 or k >= gp.nepol - 3:
                # if so, increase nrscale 5-fold
                scal = 5 * nrscale
            nr[k] = nr[k - 1] + (dnrdlrparams[k] - 0.5) * 2. * scal * deltalogr

        # cut at zero: we do not want to have density rising outwards
    for k in range(0, gp.nepol):
        nr[k] = max(0., nr[k])
    # rho slope for asymptotically reaching r = \infty is given directly
    # must lie below -3, thus n(r)>3
    #deltalogrlast = (np.log(gp.xepol[-1])-np.log(gp.xepol[-2]))
    # finite mass prior: to bound between 3 and ..
    nrasyminfty = max(nr[-1], 3.001)
    params = np.hstack([rhohalf, nrasym0, nr, nrasyminfty])
    return params
Beispiel #6
0
def map_nr_tracers(params, pop, gp):
    gh.sanitize_vector(params, gp.nrho, 0, 1, gp.debug)
    # first, if we already have a Sig-converged run, use the parameters as stored
    if gp.getSigdata:
        return params*(gp.nupar_max-gp.nupar_min)+gp.nupar_min
    nr = np.zeros(gp.nepol) # to hold the n(r) = dlog(rho)/dlog(r) values
    # get offset and n(r) profiles, calculate rho
    nrscale = gp.nrtol_nu/(max(np.log(gp.xipol))-min(np.log(gp.xipol)))
    # first parameter gives half-light radius value of rho directly
    # use [0,1]**3 to increase probability of sampling close to 0
    # fix value with tracer densities,
    # sample a flat distribution over log(rho_half)
    rhohalf = 10**((params[0]-0.5)*2.*gp.log10nuspread+np.log10(gp.dat.nuhalf[pop]))
    # 10** is correct
    # nr(r=0) is = rho slope for approaching r=0 asymptotically, given directly
    # should be smaller than -3 to exclude infinite enclosed mass
    nrasym0 = params[1]**2*gp.innerslope # **2 tweaks it toward lower values while still keeping general
    # work directly with the dn(r)/dlog(r) parameters here
    dnrdlrparams = params[1:]

    for k in range(0, gp.nepol):
        deltalogr = (np.log(gp.xepol[k-1])-np.log(gp.xepol[k-2]))
        # construct n(r_k+1) from n(r_k)+dn/dlogr*Delta log r, integrated
        if gp.monotonic_nu:
            # only increase n(r), use pa[i]>=0 directly
            nr[k] = nr[k-1] + dnrdlrparams[k] * nrscale/2. * deltalogr
        else:
            # use pa => [-1, 1] for full interval
            scal = nrscale
            # check whether we are in extension bins
            if k<3 or k>=gp.nepol-3:
                # if so, increase nrscale 5-fold
                scal = 5*nrscale
            nr[k] = nr[k-1] + (dnrdlrparams[k]-0.5)*2. * scal * deltalogr

        # cut at zero: we do not want to have density rising outwards
    for k in range(0, gp.nepol):
        nr[k] = max(0., nr[k])
    # rho slope for asymptotically reaching r = \infty is given directly
    # must lie below -3, thus n(r)>3
    #deltalogrlast = (np.log(gp.xepol[-1])-np.log(gp.xepol[-2]))
    # finite mass prior: to bound between 3 and ..
    nrasyminfty = max(nr[-1], 3.001)
    params = np.hstack([rhohalf, nrasym0, nr, nrasyminfty])
    return params
Beispiel #7
0
def map_betastar_sigmoid(params, gp):
    gh.sanitize_vector(params, gp.nbeta, 0, 1, gp.debug)
    bdiff = gp.maxbetastar_0-gp.minbetastar_0
    a0 = params[0]*bdiff + gp.minbetastar_0  # a0
    # TODO: remove parameter for the case that beta00prior is set, as then we already know its value (and thus need to sample one dimension less)
    if gp.beta00prior:
        a0 = 0.
    bdiff = gp.maxbetastar_inf-gp.minbetastar_inf
    a1 = params[1]*bdiff + gp.minbetastar_inf  # a1
    alpha = params[2]*4             # alpha
    # r_s, sampled in log space over all radii,
    # as we want flat prior in log space
    #logrs = params[3]*(np.log(max(gp.xepol))-np.log(min(gp.xepol)))+np.log(min(gp.xepol))
    logrs = params[3]*(np.log(2*gp.Xscale[0])-np.log(gp.Xscale[0]/2))+np.log(gp.Xscale[0]/2)
    if gp.checkbeta:
        a1 = max(0.99, a1) # for Gaia02 runs only!
        logrs = gp.betalogrs
    return np.hstack([a0, a1, alpha, logrs])
 def set_prof(self, prof, vec, pop, gp):
     gh.sanitize_vector(vec, len(self.x0), -1e30, 1e30, gp.debug)
     if prof == 'rho':
         self.rho = vec
     elif prof == 'nr':
         self.nr = vec
     elif prof == 'M':
         self.M = vec
     elif prof == 'nu':
         self.nu[pop*self.nipol:(pop+1)*self.nipol] = vec
     elif prof == 'Sig':
         self.Sig[pop*self.nipol:(pop+1)*self.nipol] = vec
     elif prof == 'tilt':
         self.tilt[pop*self.nipol:(pop+1)*self.nipol] = vec
     elif prof == 'sig':
         self.sig[pop*self.nipol:(pop+1)*self.nipol] = vec
     elif prof == 'kap':
         self.kap[pop*self.nipol:(pop+1)*self.nipol] = vec
Beispiel #9
0
 def set_prof(self, prof, vec, pop, gp):
     gh.sanitize_vector(vec, len(self.x0), -1e30, 1e30, gp.debug)
     if prof == 'rho':
         self.rho = vec
     elif prof == 'nr':
         self.nr = vec
     elif prof == 'M':
         self.M = vec
     elif prof == 'nu':
         self.nu[pop * self.nipol:(pop + 1) * self.nipol] = vec
     elif prof == 'Sig':
         self.Sig[pop * self.nipol:(pop + 1) * self.nipol] = vec
     elif prof == 'tilt':
         self.tilt[pop * self.nipol:(pop + 1) * self.nipol] = vec
     elif prof == 'sig':
         self.sig[pop * self.nipol:(pop + 1) * self.nipol] = vec
     elif prof == 'kap':
         self.kap[pop * self.nipol:(pop + 1) * self.nipol] = vec
Beispiel #10
0
def map_nr(params, prof, pop, gp):
    gh.sanitize_vector(params, gp.nrho, 0, 1, gp.debug)
    nr = np.zeros(gp.nepol)  # to hold the n(r) = dlog(rho)/dlog(r) values
    # get offset and n(r) profiles, calculate rho
    # first parameter gives half-light radius value of rho directly
    # use [0,1]**3 to increase probability of sampling close to 0
    # fix value with tracer densities,
    # sample a flat distribution over log(rho_half)
    rhohalf = 10**((params[0] - 0.5) * 2. * gp.log10rhospread +
                   np.log10(gp.rhohalf))
    # nr(r=0) is = rho slope for approaching r=0 asymptotically, given directly
    # should be smaller than -3 to exclude infinite enclosed mass
    nrasym0 = params[1]**4 * gp.innerslope
    # work directly with the dn(r)/dlog(r) parameters here
    dnrdlrparams = params[1:]
    if gp.monotonic:
        gpar = ginv(np.array(dnrdlrparams) / 2. + 0.5, 0., gp.nrtol)
    else:
        gpar = ginv(dnrdlrparams, 0., gp.nrtol)

    # set the innermost nr parameter starting from nrasym0 parameter instead of 0
    deltalogr = (np.log(gp.xepol[0]) - np.log(gp.xepol[0] / gp.rinfty))
    nr[0] = nrasym0 + gpar[0] * deltalogr

    for k in range(1, gp.nepol):
        deltalogr = (np.log(gp.xepol[k]) - np.log(gp.xepol[k - 1]))
        # construct n(r_k+1) from n(r_k)+dn/dlogr*Delta log r, integrated
        # cut at zero: we do not want to have density rising outwards
        nr[k] = nr[k - 1] + gpar[k] * deltalogr

    # correct n(r) >= 0 after calculating them, to keep parameters independent
    for k in range(gp.nepol):
        if nr[k] < 0:
            nr[k] = 0.0

    # rho slope for asymptotically reaching r = \infty is given directly
    # must lie below -3, thus n(r)>3
    #deltalogrlast = (np.log(gp.xepol[-1])-np.log(gp.xepol[-2]))

    # finite mass prior: to bound between 3 and ..
    nrasyminfty = max(nr[-1], 3.001)
    params = np.hstack([rhohalf, nrasym0, nr, nrasyminfty])

    return params
Beispiel #11
0
def map_nr(params, prof, pop, gp):
    gh.sanitize_vector(params, gp.nrho, 0, 1, gp.debug)
    nr = np.zeros(gp.nepol) # to hold the n(r) = dlog(rho)/dlog(r) values
    # get offset and n(r) profiles, calculate rho
    # first parameter gives half-light radius value of rho directly
    # use [0,1]**3 to increase probability of sampling close to 0
    # fix value with tracer densities,
    # sample a flat distribution over log(rho_half)
    rhohalf = 10**((params[0]-0.5)*2.*gp.log10rhospread+np.log10(gp.rhohalf))
    # nr(r=0) is = rho slope for approaching r=0 asymptotically, given directly
    # should be smaller than -3 to exclude infinite enclosed mass
    nrasym0 = params[1]**4*gp.innerslope
    # work directly with the dn(r)/dlog(r) parameters here
    dnrdlrparams = params[1:]
    if gp.monotonic:
        gpar = ginv(np.array(dnrdlrparams)/2.+0.5, 0., gp.nrtol)
    else:
        gpar = ginv(dnrdlrparams, 0., gp.nrtol)

    # set the innermost nr parameter starting from nrasym0 parameter instead of 0
    deltalogr = (np.log(gp.xepol[0])-np.log(gp.xepol[0]/gp.rinfty))
    nr[0] = nrasym0 + gpar[0] * deltalogr

    for k in range(1, gp.nepol):
        deltalogr = (np.log(gp.xepol[k])-np.log(gp.xepol[k-1]))
        # construct n(r_k+1) from n(r_k)+dn/dlogr*Delta log r, integrated
        # cut at zero: we do not want to have density rising outwards
        nr[k] = nr[k-1] + gpar[k] * deltalogr

    # correct n(r) >= 0 after calculating them, to keep parameters independent
    for k in range(gp.nepol):
        if nr[k]<0:
            nr[k] = 0.0

    # rho slope for asymptotically reaching r = \infty is given directly
    # must lie below -3, thus n(r)>3
    #deltalogrlast = (np.log(gp.xepol[-1])-np.log(gp.xepol[-2]))

    # finite mass prior: to bound between 3 and ..
    nrasyminfty = max(nr[-1], 3.001)
    params = np.hstack([rhohalf, nrasym0, nr, nrasyminfty])

    return params
Beispiel #12
0
def map_betastar_sigmoid(params, gp):
    gh.sanitize_vector(params, gp.nbeta, 0, 1, gp.debug)
    bdiff = gp.maxbetastar_0 - gp.minbetastar_0
    a0 = params[0] * bdiff + gp.minbetastar_0  # a0
    # TODO: remove parameter for the case that beta00prior is set, as then we already know its value (and thus need to sample one dimension less)
    if gp.beta00prior:
        a0 = 0.
    bdiff = gp.maxbetastar_inf - gp.minbetastar_inf
    a1 = params[1] * bdiff + gp.minbetastar_inf  # a1
    alpha = params[2] * 4  # alpha
    # r_s, sampled in log space over all radii,
    # as we want flat prior in log space
    #logrs = params[3]*(np.log(max(gp.xepol))-np.log(min(gp.xepol)))+np.log(min(gp.xepol))
    logrs = params[3] * (np.log(2 * gp.Xscale[0]) -
                         np.log(gp.Xscale[0] / 2)) + np.log(gp.Xscale[0] / 2)
    if gp.checkbeta:
        a1 = max(0.99, a1)  # for Gaia02 runs only!
        logrs = gp.betalogrs
    return np.hstack([a0, a1, alpha, logrs])
Beispiel #13
0
def myloglike(cube, ndim, nparams):
    off = 0
    split_mu = []
    split_sig = []
    frac = cube[off]
    off += 1
    for pop in range(2):
        split_mu.append(cube[off])
        off += 1
        split_sig.append(cube[off])
        off += 1
    gh.sanitize_vector(split_mu, 2, -10, 10, True)
    if off != ndim:
        gh.LOG(1, 'wrong number of parameters in myloglike.cube')
        pdb.set_trace()
    gh.LOG(2, 'starting logev evaluation')
    p1_split= 1/np.sqrt(2*np.pi*(split_sig[0]**2+e_split**2))*\
           np.exp(-(split-split_mu[0])**2/(2*(split_sig[0]**2+e_split**2)))
    p2_split= 1/np.sqrt(2*np.pi*(split_sig[1]**2+e_split**2))*\
           np.exp(-(split-split_mu[1])**2/(2*(split_sig[1]**2+e_split**2)))
    p1 = frac * PM * p1_split
    for i in range(0, len(p1)):
        if p1[i] == 0.0:
            p1[i] = 1e-30
    p2 = (1 - frac) * PM * p2_split
    for i in range(0, len(p2)):
        if p2[i] == 0.0:
            p2[i] = 1e-30
    pcom = p1 + p2

    #print('pcom (min, max) = ', min(pcom), max(pcom))
    #print('fraction of pcom == 0 : ', sum(pcom==0)/len(pcom))
    lpcom = np.log(pcom)
    logev = np.sum(lpcom)
    #print(logev)
    #gh.LOG(1, 'logL:',logev)
    if logev < -1e300:
        logev = -1e300
    #    pdb.set_trace()
    return logev
Beispiel #14
0
def myloglike(cube, ndim, nparams):
    off = 0
    split_mu = []; split_sig = []
    frac = cube[off]
    off += 1
    for pop in range(2):
        split_mu.append(cube[off])
        off += 1
        split_sig.append(cube[off])
        off += 1
    gh.sanitize_vector(split_mu, 2, -10, 10, True)
    if off != ndim:
        gh.LOG(1, 'wrong number of parameters in myloglike.cube')
        pdb.set_trace()
    gh.LOG(2,'starting logev evaluation')
    p1_split= 1/np.sqrt(2*np.pi*(split_sig[0]**2+e_split**2))*\
           np.exp(-(split-split_mu[0])**2/(2*(split_sig[0]**2+e_split**2)))
    p2_split= 1/np.sqrt(2*np.pi*(split_sig[1]**2+e_split**2))*\
           np.exp(-(split-split_mu[1])**2/(2*(split_sig[1]**2+e_split**2)))
    p1 = frac*PM*p1_split
    for i in range(0,len(p1)):
        if p1[i] == 0.0:
            p1[i] = 1e-30
    p2 = (1-frac)*PM*p2_split
    for i in range(0, len(p2)):
        if p2[i] == 0.0:
            p2[i] = 1e-30
    pcom = p1+p2

    #print('pcom (min, max) = ', min(pcom), max(pcom))
    #print('fraction of pcom == 0 : ', sum(pcom==0)/len(pcom))
    lpcom = np.log(pcom)
    logev = np.sum(lpcom)
    #print(logev)
    #gh.LOG(1, 'logL:',logev)
    if logev < -1e300:
        logev = -1e300
    #    pdb.set_trace()
    return logev
Beispiel #15
0
def rho(r0, rhodmpar, pop, gp):
    gh.sanitize_vector(rhodmpar, gp.nrho, 0, 1e30, gp.debug)
    vec = 1. * rhodmpar  # make a new copy so we do not overwrite rhodmpar
    rho_at_rhalf = vec[0]
    vec = vec[1:]
    # get spline representation on gp.xepol, where rhodmpar are defined on
    spline_n = nr(gp.xepol, vec, pop, gp)
    # and apply it to these radii, which may be anything in between
    # self.Xscale is determined in 2D, not 3D
    # use gp.dat.rhalf[0]
    rs = np.log(r0 / gp.dat.rhalf[pop])  # have to integrate in d log(r)
    lnrright = []
    lnrleft = []
    if np.rank(rs) == 0:
        if rs > 0:
            lnrright.append(rs)
        else:
            lnrleft.append(rs)
    else:
        lnrright = rs[(rs >= 0.)]
        lnrleft = rs[(rs < 0.)]
        lnrleft = lnrleft[::-1]  # inverse order

    lnrhoright = []
    for i in np.arange(0, len(lnrright)):
        lnrhoright.append(np.log(rho_at_rhalf) + \
                           splint(0., lnrright[i], spline_n))
        # integration along dlog(r) instead of dr

    lnrholeft = []
    for i in np.arange(0, len(lnrleft)):
        lnrholeft.append(np.log(rho_at_rhalf) + \
                          splint(0., lnrleft[i], spline_n))

    tmp = np.exp(np.hstack([lnrholeft[::-1],
                            lnrhoright]))  # still defined on ln(r)
    gh.checkpositive(tmp, 'rho()')
    return tmp
Beispiel #16
0
def rho(r0, rhodmpar, pop, gp):
    gh.sanitize_vector(rhodmpar, gp.nrho, 0, 1e30, gp.debug)
    vec = 1.*rhodmpar # make a new copy so we do not overwrite rhodmpar
    rho_at_rhalf = vec[0]
    vec = vec[1:]
    # get spline representation on gp.xepol, where rhodmpar are defined on
    spline_n = nr(gp.xepol, vec, pop, gp)
    # and apply it to these radii, which may be anything in between
    # self.Xscale is determined in 2D, not 3D
    # use gp.dat.rhalf[0]
    rs =  np.log(r0/gp.dat.rhalf[pop]) # have to integrate in d log(r)
    lnrright = []
    lnrleft = []
    if np.rank(rs) == 0:
        if rs>0:
            lnrright.append(rs)
        else:
            lnrleft.append(rs)
    else:
        lnrright = rs[(rs>=0.)]
        lnrleft  = rs[(rs<0.)]
        lnrleft  = lnrleft[::-1] # inverse order

    lnrhoright = []
    for i in np.arange(0, len(lnrright)):
        lnrhoright.append(np.log(rho_at_rhalf) + \
                           splint(0., lnrright[i], spline_n))
                           # integration along dlog(r) instead of dr

    lnrholeft = []
    for i in np.arange(0, len(lnrleft)):
        lnrholeft.append(np.log(rho_at_rhalf) + \
                          splint(0., lnrleft[i], spline_n))

    tmp = np.exp(np.hstack([lnrholeft[::-1], lnrhoright])) # still defined on ln(r)
    gh.checkpositive(tmp, 'rho()')
    return tmp
Beispiel #17
0
def geom_loglike(cube, ndim, nparams, gp):
    tmp_profs = Profiles(gp.pops, gp.nepol)
    off = 0
    offstep = gp.nrho
    if gp.chi2_Sig_converged <= 0:
        rhodmpar = np.array(cube[off : off + offstep])
        tmp_rho0 = phys.rho(gp.xepol, rhodmpar, 0, gp)
        # for J factor calculation (has been deferred to output routine)
        # tmp_rhofine = phys.rho(gp.xfine, rhodmpar, 0, gp)
        # tmp_Jfine = gip.Jpar(gp.xfine, tmp_rhofine, gp) #tmp_rhofine
        # tck = splrep(gp.xfine[:-3], tmp_Jfine)
        # tmp_J = splev(gp.xepol, tck)
        # rhodmpar hold [rho(rhalf), nr to be used for integration
        # from halflight radius, defined on gp.xepol]
        # (only calculate) M, check
        tmp_M0 = gip.rho_SUM_Mr(gp.xepol, tmp_rho0)
        # store profiles
        tmp_profs.set_prof("nr", 1.0 * rhodmpar[1 + 1 : -1], 0, gp)
        tmp_profs.set_prof("rho", tmp_rho0, 0, gp)
        # tmp_profs.set_prof('J', tmp_J, 0, gp)
        tmp_profs.set_prof("M", tmp_M0, 0, gp)
    off += offstep  # anyhow, even if Sig not yet converged

    # get profile for rho*
    if gp.investigate == "obs":
        offstep = gp.nrho
        lbaryonpar = np.array(cube[off : off + offstep])
        rhostar = phys.rho(gp.xepol, lbaryonpar, 0, gp)
        off += offstep
        Signu = gip.rho_param_INT_Sig(gp.xepol, lbaryonpar, 0, gp)  # [Munit/pc^2]
        MtoL = cube[off]
        off += 1
        # store these profiles every time
        tmp_profs.set_prof("nu", rhostar, 0, gp)
        tmp_profs.set_prof("Sig", Signu, 0, gp)
        tmp_profs.set_MtoL(MtoL)
    else:
        lbaryonpar = np.zeros(gp.nrho)
        MtoL = 0.0
    for pop in np.arange(1, gp.pops + 1):  # [1, 2, ..., gp.pops]
        offstep = gp.nrho
        nupar = np.array(cube[off : off + offstep])
        tmp_nrnu = 1.0 * nupar[1 + 1 : -1]

        tmp_nu = phys.rho(gp.xepol, nupar, pop, gp)
        tmp_Signu = gip.rho_param_INT_Sig(gp.xepol, nupar, pop, gp)
        # tmp_nu = pool.apply_async(phys.rho, [gp.xepol, nupar, pop, gp])
        # tmp_Signu = pool.apply_async(gip.rho_param_INT_Sig, [gp.xepol, nupar, pop, gp])
        off += offstep

        offstep = 1
        tmp_hyperSig = cube[off : off + offstep]
        off += offstep

        offstep = 1
        tmp_hypersig = cube[off : off + offstep]
        off += offstep

        offstep = gp.nbeta
        if gp.chi2_Sig_converged <= 0:
            betapar = np.array(cube[off : off + offstep])
            tmp_beta, tmp_betastar = phys.beta(gp.xepol, betapar, gp)
            if check_beta(tmp_beta, gp):
                gh.LOG(2, "beta error")
                tmp_profs.chi2 = gh.err(1.0, gp)
                return tmp_profs
            try:
                # if True:
                if gp.checksig and gp.investigate == "hern":
                    import gi_analytic as ga

                    anrho = ga.rho(gp.xepol, gp)[0]
                    rhodmpar_half = np.exp(splev(gp.dat.rhalf[0], splrep(gp.xepol, np.log(anrho))))
                    nr = -gh.derivipol(np.log(anrho), np.log(gp.xepol))
                    dlr = np.hstack([nr[0], nr, nr[-1]])
                    if gp.investigate == "gaia":
                        dlr[-1] = 4
                        rhodmpar = np.hstack([rhodmpar_half, dlr])
                    lbaryonpar = 0.0 * rhodmpar
                    MtoL = 0.0
                    betapar = np.array([0, 0, 2, max(gp.xipol) / 2])  # for hern
                    annu = ga.rho(gp.xepol, gp)[1]
                    nupar_half = np.exp(splev(gp.dat.rhalf[1], splrep(gp.xepol, np.log(annu))))
                    nrnu = -gh.derivipol(np.log(annu), np.log(gp.xepol))
                    dlrnu = np.hstack([nrnu[0], nrnu, nrnu[-1]])
                    if gp.investigate == "gaia":
                        dlrnu[-1] = 6
                    nupar = np.hstack([nupar_half, dlrnu])
                elif gp.checkbeta and gp.investigate == "gaia":
                    #                    rhodmpar = np.array([ 0.41586608, 0.38655515, 0.60898657, 0.50936769, 0.52601378, 0.54526758,  0.5755599, 0.57900806, 0.60252357, 0.60668445, 0.62252721, 0.63173754, 0.64555439, 0.65777175, 0.67083556, 0.68506606, 0.69139872, 0.66304763, 0.61462276, 0.70916575, 0.53287872])
                    rhodmpar = np.array(
                        [
                            0.18235821,
                            0.4719348,
                            0.0,
                            0.0,
                            0.10029569,
                            0.11309553,
                            0.25637863,
                            0.31815175,
                            0.40621336,
                            0.46247927,
                            0.53545415,
                            0.60874961,
                            0.68978141,
                            0.79781574,
                            0.91218048,
                            1.08482356,
                            1.36074895,
                            1.88041885,
                            2.31792908,
                            2.62089078,
                            3.001,
                        ]
                    )

                    betapar = np.array([1.23555034e-03, 9.89999994e-01, 2.03722518e00, 5.85640906e00])
                    nupar = np.array(
                        [
                            0.15649498,
                            6.65618254,
                            0.10293663,
                            0.1087109,
                            0.13849277,
                            0.24371261,
                            0.62633345,
                            1.05913181,
                            1.43774113,
                            1.82346043,
                            2.20091446,
                            2.60007997,
                            2.98745825,
                            3.423104,
                            3.80766658,
                            4.2089698,
                            4.62950843,
                            4.91166037,
                            4.97380638,
                            4.99718073,
                            5.2277589,
                        ]
                    )
                    gp.dat.nrnu = [
                        np.array(
                            [
                                0.15476906,
                                0.85086798,
                                0.9342867,
                                0.88161169,
                                0.83254241,
                                0.85086798,
                                0.99930431,
                                1.22211638,
                                1.47184763,
                                1.78910057,
                                2.1987677,
                                2.51961046,
                                2.80345393,
                                3.10336133,
                                3.88504346,
                                4.52442727,
                                4.88817769,
                                5.07880404,
                                4.83455511,
                                6.32165657,
                                4.88817769,
                            ]
                        ),
                        np.array(
                            [
                                0.15476906,
                                0.85086798,
                                0.9342867,
                                0.88161169,
                                0.83254241,
                                0.85086798,
                                0.99930431,
                                1.22211638,
                                1.47184763,
                                1.78910057,
                                2.1987677,
                                2.51961046,
                                2.80345393,
                                3.10336133,
                                3.88504346,
                                4.52442727,
                                4.88817769,
                                5.07880404,
                                4.83455511,
                                6.32165657,
                                4.88817769,
                            ]
                        ),
                        np.array(
                            [
                                0.15476906,
                                0.85086798,
                                0.9342867,
                                0.88161169,
                                0.83254241,
                                0.85086798,
                                0.99930431,
                                1.22211638,
                                1.47184763,
                                1.78910057,
                                2.1987677,
                                2.51961046,
                                2.80345393,
                                3.10336133,
                                3.88504346,
                                4.52442727,
                                4.88817769,
                                5.07880404,
                                4.83455511,
                                6.32165657,
                                4.88817769,
                            ]
                        ),
                        np.array(
                            [
                                0.15476906,
                                0.85086798,
                                0.9342867,
                                0.88161169,
                                0.83254241,
                                0.85086798,
                                0.99930431,
                                1.22211638,
                                1.47184763,
                                1.78910057,
                                2.1987677,
                                2.51961046,
                                2.80345393,
                                3.10336133,
                                3.88504346,
                                4.52442727,
                                4.88817769,
                                5.07880404,
                                4.83455511,
                                6.32165657,
                                4.88817769,
                            ]
                        ),
                    ]
                    gp.dat.nrnuerr = [
                        np.array(
                            [
                                0.05158969,
                                12.22044422,
                                2.44408884,
                                2.44408884,
                                2.44408884,
                                2.44408884,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                2.44408884,
                                2.44408884,
                                2.44408884,
                                2.44408884,
                            ]
                        ),
                        np.array(
                            [
                                0.05158969,
                                12.22044422,
                                2.44408884,
                                2.44408884,
                                2.44408884,
                                2.44408884,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                2.44408884,
                                2.44408884,
                                2.44408884,
                                2.44408884,
                            ]
                        ),
                        np.array(
                            [
                                0.05158969,
                                12.22044422,
                                2.44408884,
                                2.44408884,
                                2.44408884,
                                2.44408884,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                2.44408884,
                                2.44408884,
                                2.44408884,
                                2.44408884,
                            ]
                        ),
                        np.array(
                            [
                                0.05158969,
                                12.22044422,
                                2.44408884,
                                2.44408884,
                                2.44408884,
                                2.44408884,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                0.48881777,
                                2.44408884,
                                2.44408884,
                                2.44408884,
                                2.44408884,
                            ]
                        ),
                    ]

                    lbaryonpar = 0.0 * rhodmpar
                    MtoL = 0.0

                sig, kap, zetaa, zetab = phys.sig_kap_zet(gp.xepol, rhodmpar, lbaryonpar, MtoL, nupar, betapar, pop, gp)
                # fill_between(gp.xipol, gp.dat.sig[1]-gp.dat.sigerr[1], gp.dat.sig[1]+gp.dat.sigerr[1])
                # plot(gp.xepol, sig, 'r')
                # xscale('log')
                # ylim([0, 30])
                # xlabel('$r$ [pc]')
                # ylabel('$\sigma_{LOS}$ [km/s]')
                # savefig('siglos_gaia_2.pdf')
                # pdb.set_trace()
            except Exception:
                gh.LOG(1, "sigma error")
                tmp_profs.chi2 = gh.err(2.0, gp)
                return tmp_profs
            # now store the profiles
            gh.sanitize_vector(tmp_beta, len(tmp_profs.x0), -200, 1, gp.debug)
            tmp_profs.set_prof("beta", tmp_beta, pop, gp)
            gh.sanitize_vector(tmp_betastar, len(tmp_profs.x0), -1, 1, gp.debug)
            tmp_profs.set_prof("betastar", tmp_betastar, pop, gp)
            tmp_profs.set_prof("sig", sig, pop, gp)
            tmp_profs.hypersig = tmp_hypersig
            tmp_profs.set_prof("kap", kap, pop, gp)
            tmp_profs.set_zeta(zetaa, zetab, pop)

        tmp_profs.set_prof("nrnu", tmp_nrnu, pop, gp)
        tmp_profs.set_prof("nu", tmp_nu, pop, gp)  # pool: tmp_nu.get()

        # following profile needs to be stored at all times, to calculate chi
        tmp_profs.set_prof("Sig", tmp_Signu, pop, gp)
        tmp_profs.hyperSig = tmp_hyperSig

        off += offstep  # still do this even if gp.chi2_Sig_converged is False
    if off != gp.ndim:
        gh.LOG(1, "wrong subscripts in gi_loglike")
        pdb.set_trace()

    # determine log likelihood
    chi2 = calc_chi2(tmp_profs, gp)
    gh.LOG(-1, gp.investigate + "/" + str(gp.case) + "/" + gp.files.timestamp + ":  ln L = ", gh.pretty(-chi2 / 2.0))
    # x=gp.dat.rbin
    # linedat,=ax.loglog(x, gp.dat.Sig[1], 'b')
    # line,=ax.loglog(x, tmp_profs.get_prof("Sig", 1), 'r', alpha=0.1)
    # plt.draw()
    # plt.show()
    tmp_profs.chi2 = chi2

    # after some predefined wallclock time and Sig convergence, plot all profiles
    # if time.time() - gp.last_plot >= gp.plot_after and gp.chi2_Sig_converged <= 0:
    #    gp.last_plot = time.time()
    #    try:
    #        import plotting.plot_profiles
    #        plotting.plot_profiles.run(gp.files.timestamp, gp.files.outdir, gp)
    #    except:
    #        print('plotting error in gi_loglike!')
    # close pool automatically after with clause
    return tmp_profs
Beispiel #18
0
def w(Rk):
    gh.sanitize_vector(Rk, Nsample, 0, 1e30, DEBUG)
    w_ipol = np.zeros(Nsample)
    for k in range(Nsample):
        w_ipol[k] = wpt[np.where(abs(Rk[k] - Rpt) == min(abs(Rk[k] - Rpt)))]
    return w_ipol
Beispiel #19
0
def map_nr(params, prof, pop, gp):
    gh.sanitize_vector(params, gp.nrho, 0, 1, gp.debug)
    nr = np.zeros(gp.nepol) # to hold the n(r) = dlog(rho)/dlog(r) values

    # get offset and n(r) profiles, calculate rho
    if prof=='rho':
        rhoscale = gp.rhohalf
        Rscale = gp.Xscale[0]
        width = gp.log10rhospread
        rlimnr = gp.rlimnr
        maxrhoslope = gp.maxrhoslope
        nrscale = gp.nztol/(max(np.log(gp.xipol))-min(np.log(gp.xipol)))
        monotonic = gp.monotonic
    elif prof=='nu':
        rhoscale = gp.dat.nuhalf[pop]
        Rscale = gp.Xscale[pop]
        width = gp.log10nuspread
        rlimnr = gp.rlimnr_nu
        maxrhoslope = gp.maxnuslope
        nrscale = gp.nztol_nu/(max(np.log(gp.xipol))-min(np.log(gp.xipol)))
        monotonic = gp.monotonic_nu
    else:
        raise Exception('wrong profile in gi_class_cube.map_nr')

    # first parameter gives half-light radius value of rho directly
    # use [0,1]**3 to increase probability of sampling close to 0
    # fix value with tracer densities,
    # sample a flat distribution over log(rho_half)
    rhohalf = 10**((params[0]-0.5)*2.*width+np.log10(rhoscale))

    # nr(r=0) is = rho slope for approaching r=0 asymptotically, given directly
    # should be smaller than -3 to exclude infinite enclosed mass
    if gp.xepol[0] <= rlimnr*Rscale:
        nrasym0 = params[1]*min(maxrhoslope/2, 2.99)
    else:
        nrasym0 = params[1]*2.99

    # work directly with the dn(r)/dlog(r) parameters here
    dnrdlrparams = params[2:-1]
    # offset for the integration of dn(r)/dlog(r) at smallest radius
    if gp.xepol[1] <= rlimnr*Rscale:
        nr[0] = dnrdlrparams[0]*min(maxrhoslope/2, 2.99)
    else:
        nr[0] = dnrdlrparams[0]*maxrhoslope

    for k in range(1, gp.nepol):
        # all -dlog(rho)/dlog(r) at data points and 2,4,8rmax can
        # lie in between 0 and gp.maxrhoslope
        deltalogr = (np.log(gp.xepol[k-1])-np.log(gp.xepol[k-2]))
        # construct n(r_k+1) from n(r_k)+dn/dlogr*Delta log r, integrated
        if monotonic:
            # only increase n(r), use pa[i]>=0 directly
            nr[k] = nr[k-1] + dnrdlrparams[k] * nrscale * deltalogr
        else:
            # use pa => [-1, 1] for full interval
            nr[k] = nr[k-1] + (dnrdlrparams[k]-0.5)*2. * nrscale * deltalogr
        # cut at zero: we do not want to have density rising outwards
        nr[k] = max(0., nr[k])
        # restrict n(r)
        if gp.xepol[k] <= rlimnr*Rscale:
            nr[k] = min(maxrhoslope/2, nr[k])
        else:
            nr[k] = min(maxrhoslope, nr[k])
    # rho slope for asymptotically reaching r = \infty is given directly
    # must lie below -3, thus n(r)>3
    deltalogrlast = (np.log(gp.xepol[-1])-np.log(gp.xepol[-2]))
    # to ensure we have a finite mass at all radii 0<r<=\infty
    if monotonic:
        nrasyminfty = nr[-1]+params[-1] * nrscale * deltalogrlast
    else:
        nrasyminfty = nr[-1]+(params[-1]-0.5)*2 * nrscale * deltalogrlast

    # finite mass prior: to bound between 3 and gp.maxrhoslope, favoring 3:
    nrasyminfty = max(nrasyminfty, 3.001)

    params = np.hstack([rhohalf, nrasym0, nr, nrasyminfty])
    return params
Beispiel #20
0
def map_nr(params, prof, pop, gp):
    gh.sanitize_vector(params, gp.nrho, 0, 1, gp.debug)
    nr = np.zeros(gp.nepol)  # to hold the n(r) = dlog(rho)/dlog(r) values

    # get offset and n(r) profiles, calculate rho
    if prof == 'rho':
        rhoscale = gp.rhohalf
        Rscale = gp.Xscale[0]
        width = gp.log10rhospread
        rlimnr = gp.rlimnr
        maxrhoslope = gp.maxrhoslope
        nrscale = gp.nztol / (max(np.log(gp.xipol)) - min(np.log(gp.xipol)))
        monotonic = gp.monotonic
    elif prof == 'nu':
        rhoscale = gp.dat.nuhalf[pop]
        Rscale = gp.Xscale[pop]
        width = gp.log10nuspread
        rlimnr = gp.rlimnr_nu
        maxrhoslope = gp.maxnuslope
        nrscale = gp.nztol_nu / (max(np.log(gp.xipol)) - min(np.log(gp.xipol)))
        monotonic = gp.monotonic_nu
    else:
        raise Exception('wrong profile in gi_class_cube.map_nr')

    # first parameter gives half-light radius value of rho directly
    # use [0,1]**3 to increase probability of sampling close to 0
    # fix value with tracer densities,
    # sample a flat distribution over log(rho_half)
    rhohalf = 10**((params[0] - 0.5) * 2. * width + np.log10(rhoscale))

    # nr(r=0) is = rho slope for approaching r=0 asymptotically, given directly
    # should be smaller than -3 to exclude infinite enclosed mass
    if gp.xepol[0] <= rlimnr * Rscale:
        nrasym0 = params[1] * min(maxrhoslope / 2, 2.99)
    else:
        nrasym0 = params[1] * 2.99

    # work directly with the dn(r)/dlog(r) parameters here
    dnrdlrparams = params[2:-1]
    # offset for the integration of dn(r)/dlog(r) at smallest radius
    if gp.xepol[1] <= rlimnr * Rscale:
        nr[0] = dnrdlrparams[0] * min(maxrhoslope / 2, 2.99)
    else:
        nr[0] = dnrdlrparams[0] * maxrhoslope

    for k in range(1, gp.nepol):
        # all -dlog(rho)/dlog(r) at data points and 2,4,8rmax can
        # lie in between 0 and gp.maxrhoslope
        deltalogr = (np.log(gp.xepol[k - 1]) - np.log(gp.xepol[k - 2]))
        # construct n(r_k+1) from n(r_k)+dn/dlogr*Delta log r, integrated
        if monotonic:
            # only increase n(r), use pa[i]>=0 directly
            nr[k] = nr[k - 1] + dnrdlrparams[k] * nrscale * deltalogr
        else:
            # use pa => [-1, 1] for full interval
            nr[k] = nr[k -
                       1] + (dnrdlrparams[k] - 0.5) * 2. * nrscale * deltalogr
        # cut at zero: we do not want to have density rising outwards
        nr[k] = max(0., nr[k])
        # restrict n(r)
        if gp.xepol[k] <= rlimnr * Rscale:
            nr[k] = min(maxrhoslope / 2, nr[k])
        else:
            nr[k] = min(maxrhoslope, nr[k])
    # rho slope for asymptotically reaching r = \infty is given directly
    # must lie below -3, thus n(r)>3
    deltalogrlast = (np.log(gp.xepol[-1]) - np.log(gp.xepol[-2]))
    # to ensure we have a finite mass at all radii 0<r<=\infty
    if monotonic:
        nrasyminfty = nr[-1] + params[-1] * nrscale * deltalogrlast
    else:
        nrasyminfty = nr[-1] + (params[-1] - 0.5) * 2 * nrscale * deltalogrlast

    # finite mass prior: to bound between 3 and gp.maxrhoslope, favoring 3:
    nrasyminfty = max(nrasyminfty, 3.001)

    params = np.hstack([rhohalf, nrasym0, nr, nrasyminfty])
    return params
Beispiel #21
0
def ant_sigkaplos(r0, rhodmpar, lbaryonpar, MtoL, nupar, betapar, pop, gp):
    rmin = np.log10(min(r0))
    rmax = np.log10(max(r0)*gp.rinfty)
    r0fine = np.logspace(rmin, rmax, gp.nfine)

    # rho
    # --------------------------------------------------------------------------
    rhofine  = phys.rho(r0fine,  rhodmpar, 0, gp) # DM mass profile (first)
    if gp.checksig and gp.stopstep <= 1:
        clf()
        loglog(r0fine, rhofine, 'r.-', label='rederived from dn/dlogr params')
        loglog(r0fine, ga.rho(r0fine, gp)[0], 'b--', label='analytic')
        axvline(max(gp.xipol))
        axvline(min(gp.xipol))
        axvline(gp.dat.rhalf[0], lw=2)
        xlabel('$r/\\rm{pc}$')
        ylabel('$\\rho(r)$')
        legend(loc='lower left')
        savefig('fit_rho_'+gp.investigate+'.pdf')
        pdb.set_trace()

    # add up tracer densities to get overall density profile
    # add rho* to take into account the baryonic addition
    # (*not* Sigma from nu_i, could miss populations, have
    # varying selection function as fct of radius
    # need a M/L parameter)
    # only if we work on real data, add up total baryonic contribution
    if gp.investigate == 'obs':
        nu_baryons = MtoL*phys.rho(r0fine, lbaryonpar, pop, gp)
        rhofine += nu_baryons

    # beta
    # ------------------------------------------------------------------------
    betafine = phys.beta(r0fine, betapar, gp)[0]
    if gp.checksig and gp.stopstep <= 2:
        clf()
        anbeta = ga.beta(r0fine, gp)[1]
        plot(r0fine, betafine, 'r.-', label='model')
        plot(r0fine, anbeta, 'b--', label='analytic')
        xscale('log')
        axvline(max(gp.xipol))
        axvline(min(gp.xipol))
        axvline(gp.dat.rhalf[0], lw=2)
        xlabel('$r/\\rm{pc}$')
        ylabel('$\\beta$')
        ylim([-0.5, 1.0])
        legend(loc='lower right')
        savefig('fit_beta_'+gp.investigate+'.pdf')
        pdb.set_trace()

    # nu
    # ------------------------------------------------------------------------
    nufine   = phys.rho(r0fine, nupar, pop, gp)
    if gp.checksig:
        annu = ga.rho(r0fine, gp)[pop]
    if gp.checksig and gp.stopstep <= 3:
        clf()
        loglog(gp.xipol, gp.dat.nu[pop], 'g.-', label='data')
        fill_between(gp.xipol, gp.dat.nu[pop]-gp.dat.nuerr[pop], \
                     gp.dat.nu[pop]+gp.dat.nuerr[pop],\
                     color='g', alpha=0.6)
        loglog(r0fine, nufine, 'r.-', label='model')
        loglog(r0fine, annu, 'b--', label='analytic')
        legend(loc='lower left')
        axvline(max(gp.xipol))
        axvline(min(gp.xipol))
        axvline(gp.dat.rhalf[0], lw=2)
        xlabel('$r/\\rm{pc}$')
        ylabel('$\\nu$')
        savefig('fit_nu_'+gp.investigate+'.pdf')
        pdb.set_trace()


    # \Sigma
    # ---------------------------------------------------------------
    Sigfine  = gip.rho_param_INT_Sig_theta(r0fine, nupar, pop, gp)
    if gp.checksig and gp.stopstep <= 4:
        clf()
        anSig = ga.Sigma(r0fine, gp)[pop]
        loglog(gp.xipol, gp.dat.Sig[pop], 'g--', label='data')
        loglog(r0fine, Sigfine, 'r.-', label='model')
        loglog(r0fine, anSig, 'b--', label='analytic')
        fill_between(gp.xipol, gp.dat.Sig[pop]-gp.dat.Sigerr[pop], \
                     gp.dat.Sig[pop]+gp.dat.Sigerr[pop],\
                     color='g', alpha=0.6)
        axvline(max(gp.xipol))
        axvline(min(gp.xipol))
        axvline(gp.Xscale[0], lw=2)
        xlabel('$r/\\rm{pc}$')
        ylabel('$\\Sigma$')
        legend(loc='lower left')
        savefig('fit_Sig_'+gp.investigate+'.pdf')
        pdb.set_trace()

    # int beta(s)/s ds
    # ------------------------------------------------------
    # test for constant \beta
    if gp.checksig:
        if gp.investigate == 'gaia':
            beta_star1, r_DM, gamma_star1, r_star1, r_a1, gamma_DM, rho0 = gp.files.params
            anintbetasfine = 0.5*(np.log(r0fine**2+r_a1**2)-np.log(r_a1**2))
        elif gp.investigate == 'hern':
            anintbetasfine = 0.0*r0fine
    #betapar[0] = 1
    #betapar[1] = 1
    anintbetasfine = np.log(r0fine)-np.log(r0fine[0])
    intbetasfine   = ant_intbeta(r0fine, betapar, gp)
    if gp.checksig and gp.stopstep <= 5 :
        clf()
        plot(r0fine, intbetasfine, 'r.-', label='model')
        plot(r0fine, anintbetasfine, 'b--', label='analytic')
        ylim([-5, 5])
        axvline(max(gp.xipol))
        axvline(min(gp.xipol))
        axvline(gp.dat.rhalf[0], lw=2)
        xscale('log')
        xlabel('$r/\\rm{pc}$')
        ylabel('$\\int ds \\beta(s)/s$')
        legend(loc='lower right')
        savefig('fit_intbeta_'+gp.investigate+'.pdf')
        pdb.set_trace()

    # M(r)
    # -------------------------------------------------------
    #rhofine = ga.rho_hern(r0fine, gp)[0]
    rhoint = 4.*np.pi*r0fine**2*rhofine
    # add point to avoid 0.0 in Mrfine(r0fine[0])
    r0tmp = np.hstack([0.,r0fine])
    rhotmp = np.hstack([0.,rhoint])
    splpar_rho = splrep(r0tmp, rhotmp, k=1, s=0.) # not necessarily monotonic
    Mrfine = np.zeros(len(r0fine)) # work in refined model
    for i in range(len(r0fine)):
        Mrfine[i] = splint(0., r0fine[i], splpar_rho)
    gh.checkpositive(Mrfine, 'Mrfine')
    if gp.checksig:
        anMr = ga.Mr(r0fine, gp)[0] # earlier: pop
        anMr = Mrfine
        #anMr = ga.M_hern(r0fine, gp)[0]
    if gp.checksig and gp.stopstep <= 6:
        #loglog(gp.xipol, gp.dat.Mr[pop], 'g.-', label='data')
        #s = r0fine/r_DM # [1]
        clf()
        loglog(r0fine, Mrfine, 'r.-', label='model')
        #loglog(r0fine, anMr, 'b--', label='analytic')
        axvline(max(gp.xipol))
        axvline(min(gp.xipol))
        axvline(gp.dat.rhalf[0], lw=2)
        xlabel('$r/\\rm{pc}$')
        ylabel('$M(r)$')
        legend(loc='lower right')
        savefig('fit_M_'+gp.investigate+'.pdf')
        pdb.set_trace()

    # nu(r)\cdot\sigma_r^2(r) integrand
    # -------------------------------------------------------
    # (sigr2, 3D) * nu/exp(-intbetasfine)
    xint = r0fine                           # [pc]
    yint = gu.G1__pcMsun_1km2s_2 * Mrfine / r0fine**2         # [1/pc (km/s)^2]
    yint *= nufine                          # [Munit/pc^4 (km/s)^2]
    yint *= np.exp(2*(intbetasfine))                  # [Munit/pc^4 (km/s)^2]
    gh.checkpositive(yint, 'yint sigr2')
    if gp.checksig and gp.stopstep <= 7:
        clf()
        loglog(xint, yint, 'r.-', label='model')
        loglog(xint, gu.G1__pcMsun_1km2s_2 * anMr / r0fine**2 * annu * np.exp(2*anintbetasfine), 'b--', label='from analytic')
        axvline(max(gp.xipol))
        axvline(min(gp.xipol))
        axvline(gp.dat.rhalf[0], lw=2)
        xlabel('$xint/\\rm{pc}$')
        ylabel('$yint$')
        legend(loc='lower left')
        savefig('fit_nu_sigmar2_'+gp.investigate+'.pdf')
        pdb.set_trace()

    # actual integration, gives \sigma_r^2 \nu
    sigr2nu_model = np.zeros(len(r0fine))
    for k in range(len(r0fine)):
        #theta_old = np.linspace(0, np.arccos(r0fine[k]/(gp.rinfty*max(gp.xepol))), gp.nfine)
        theta = np.arccos(r0fine[k]/r0fine[k:])
        rq = r0fine[k]/np.cos(theta)

        #Mrq = np.interp(rq, r0fine, Mrfine, left=0, right=0)
        #nuq = np.interp(rq, r0fine, nufine, left=0, right=0)
        #intbetaq = np.interp(rq, r0fine, intbetasfine, left=0, right=0)
        #func_interp_before = Mrq*nuq*np.exp(2*intbetaq)

        func_base = Mrfine*nufine*np.exp(2*intbetasfine)
        #func_interp_after = np.interp(rq, r0fine, func_base, left=0, right=0)
        func_interp_after = func_base[k:]

        #print('median(func_interp_after / func_interp_before = ',\
        #      np.median(func_interp_after / func_interp_before))

        #sigr2nu_model[k] =  np.exp(-2*intbetasfine[k])/r0fine[k] * \
        #                    gu.G1__pcMsun_1km2s_2*simps(func_interp_before*np.sin(theta), theta)

        sigr2nu_model[k] = np.exp(-2*intbetasfine[k])/r0fine[k] * \
                               gu.G1__pcMsun_1km2s_2*simps(func_interp_after*np.sin(theta), theta)

    # clean last value (which is always 0 by construction)
    sigr2nu_model[-1] = sigr2nu_model[-2]/10.
    gh.checkpositive(sigr2nu_model, 'sigr2nu_model in sigl2s')
    #gh.checkpositive(sigr2nu_model_new, 'sigr2nu_model_new in sigl2s')
    if gp.checksig and gp.stopstep <= 8:
        clf()
        ansigr2nu = ga.sigr2(r0fine, gp)*annu
        loglog(r0fine, sigr2nu_model, 'r.-', label='model')
        loglog(r0fine, ansigr2nu, 'b--', label='analytic')
        axvline(max(gp.xipol))
        axvline(min(gp.xipol))
        axvline(gp.dat.rhalf[0], lw=2)
        xlabel('$r/\\rm{pc}$')
        ylabel('$\\sigma_r^2(r)\\nu(r)$')
        legend(loc='lower right')
        savefig('fit_sigr2_'+gp.investigate+'.pdf')

    # project back to LOS values, \sigma_{LOS}^2 * \Sigma(R)
    # -------------------------------------------------------
    sigl2s = np.zeros(len(r0fine))
    for k in range(len(r0fine)):
        bit = 1.e-6
        theta = np.linspace(0, np.pi/2-bit, gp.nfine)
        # work on same radii as data are given
        theta = np.arccos(r0fine[k]/r0fine[k:])
        cth = np.cos(theta)
        cth2 = cth*cth
        ynew = (1-betafine[k:]*cth2)*sigr2nu_model[k:]

        rq = r0fine[k]/cth
        ynewq = np.interp(rq, r0fine[k:], ynew, left=0, right=0)
        sigl2s[k] = 2.*r0fine[k]*simps(ynewq/cth2, theta)
    sigl2s[-1] = sigl2s[-2]/10.
    gh.checkpositive(sigl2s, 'sigl2s')
    if gp.checksig and gp.stopstep <= 9:
        clf()
        anSigsiglos2_hern = ga.Sig_sig_los_2(r0fine, gp)
        loglog(r0fine, sigl2s, 'r.-', label='model')
        loglog(r0fine, anSigsiglos2_hern, 'b--', label='analytic')
        axvline(max(gp.xipol))
        axvline(min(gp.xipol))
        axvline(gp.Xscale[0], lw=2)
        xlabel('$r/\\rm{pc}$')
        ylabel('$\\sigma_{\\rm{LOS}}^2 \Sigma$')
        legend(loc='lower left')
        savefig('fit_Sig_siglos2_'+gp.investigate+'.pdf')
        pdb.set_trace()


    # sigma_LOS^2
    # -------------------------------------------------------
    siglos2 = sigl2s/Sigfine
    if gp.checksig and gp.stopstep <= 10:
        clf()
        #ansiglos = ga.sig_los(r0fine, gp)
        plot(r0fine, siglos2, 'r.-', label='model')
        #plot(r0fine, ansiglos**2, 'b--', label='analytic')
        axvline(max(gp.xipol))
        axvline(min(gp.xipol))
        axvline(gp.Xscale[0], lw=2)
        xscale('log')
        xlabel('$r/\\rm{pc}$')
        ylabel('$\\sigma_{\\rm{LOS}}^2$')
        legend(loc='upper right')
        savefig('fit_siglos2_'+gp.investigate+'.pdf')
        pdb.set_trace()

    # derefine on radii of the input vector
    splpar_sig = splrep(r0fine, np.log(siglos2), k=3, s=0.)
    siglos2_out = np.exp(splev(r0, splpar_sig))
    # gh.checkpositive(siglos2_out, 'siglos2_out')
    if gp.checksig and gp.stopstep <= 11:
        clf()
        #ansiglos = ga.sig_los(r0, gp)
        plot(r0, np.sqrt(siglos2_out), 'r.-', label='model')
        #plot(r0, ansiglos, 'b--', label='analytic')
        plot(gp.xipol, gp.dat.sig[pop], 'g.-', label='data')
        fill_between(gp.xipol, gp.dat.sig[pop]-gp.dat.sigerr[pop], gp.dat.sig[pop]+gp.dat.sigerr[pop], color='g', alpha=0.6)
        xscale('log')
        axvline(max(gp.xipol))
        axvline(min(gp.xipol))
        axvline(gp.Xscale[0], lw=2)
        xlabel('$r/\\rm{pc}$')
        ylabel('$\\sigma_{\\rm{LOS}}$')
        ylim([0,25])
        legend(loc='upper right')
        savefig('fit_siglos_out_'+gp.investigate+'.pdf')
        pdb.set_trace()

    if not gp.usekappa:
        kapl4s_out = np.ones(len(siglos2_out))
    if gp.usekappa:
        kapl4s_out = kappa(r0fine, Mrfine, nufine, sigr2nu_model, intbetasfine, gp)

    zetaa = -1; zetab = -1
    if gp.usezeta:
        zetaa, zetab = zeta(r0fine, nufine, \
                            Sigfine,\
                            Mrfine, betafine,\
                            sigr2nu_model, gp)

    gh.sanitize_vector(siglos2_out, len(r0), 0, 1e30, gp.debug)
    return siglos2_out, kapl4s_out, zetaa, zetab
Beispiel #22
0
def geom_loglike(cube, ndim, nparams, gp):
    tmp_profs = Profiles(gp.pops, gp.nepol)
    off = 0
    offstep = gp.nrho
    if gp.chi2_Sig_converged <= 0:
        rhodmpar = np.array(cube[off:off + offstep])
        tmp_rho0 = phys.rho(gp.xepol, rhodmpar, 0, gp)
        # for J factor calculation (has been deferred to output routine)
        #tmp_rhofine = phys.rho(gp.xfine, rhodmpar, 0, gp)
        #tmp_Jfine = gip.Jpar(gp.xfine, tmp_rhofine, gp) #tmp_rhofine
        #tck = splrep(gp.xfine[:-3], tmp_Jfine)
        #tmp_J = splev(gp.xepol, tck)
        # rhodmpar hold [rho(rhalf), nr to be used for integration
        # from halflight radius, defined on gp.xepol]
        # (only calculate) M, check
        tmp_M0 = gip.rho_SUM_Mr(gp.xepol, tmp_rho0)
        # store profiles
        tmp_profs.set_prof('nr', 1. * rhodmpar[1 + 1:-1], 0, gp)
        tmp_profs.set_prof('rho', tmp_rho0, 0, gp)
        #tmp_profs.set_prof('J', tmp_J, 0, gp)
        tmp_profs.set_prof('M', tmp_M0, 0, gp)
    off += offstep  # anyhow, even if Sig not yet converged

    # get profile for rho*
    if gp.investigate == 'obs':
        offstep = gp.nrho
        lbaryonpar = np.array(cube[off:off + offstep])
        rhostar = phys.rho(gp.xepol, lbaryonpar, 0, gp)
        off += offstep
        Signu = gip.rho_param_INT_Sig(gp.xepol, lbaryonpar, 0,
                                      gp)  # [Munit/pc^2]
        MtoL = cube[off]
        off += 1
        # store these profiles every time
        tmp_profs.set_prof('nu', rhostar, 0, gp)
        tmp_profs.set_prof('Sig', Signu, 0, gp)
        tmp_profs.set_MtoL(MtoL)
    else:
        lbaryonpar = np.zeros(gp.nrho)
        MtoL = 0.
    for pop in np.arange(1, gp.pops + 1):  # [1, 2, ..., gp.pops]
        offstep = gp.nrho
        nupar = np.array(cube[off:off + offstep])
        tmp_nrnu = 1. * nupar[1 + 1:-1]

        tmp_nu = phys.rho(gp.xepol, nupar, pop, gp)
        tmp_Signu = gip.rho_param_INT_Sig(gp.xepol, nupar, pop, gp)
        #tmp_nu = pool.apply_async(phys.rho, [gp.xepol, nupar, pop, gp])
        #tmp_Signu = pool.apply_async(gip.rho_param_INT_Sig, [gp.xepol, nupar, pop, gp])
        off += offstep

        offstep = 1
        tmp_hyperSig = cube[off:off + offstep]
        off += offstep

        offstep = 1
        tmp_hypersig = cube[off:off + offstep]
        off += offstep

        offstep = gp.nbeta
        if gp.chi2_Sig_converged <= 0:
            betapar = np.array(cube[off:off + offstep])
            tmp_beta, tmp_betastar = phys.beta(gp.xepol, betapar, gp)
            if check_beta(tmp_beta, gp):
                gh.LOG(2, 'beta error')
                tmp_profs.chi2 = gh.err(1., gp)
                return tmp_profs
            try:
                #if True:
                if gp.checksig and gp.investigate == 'hern':
                    import gi_analytic as ga
                    anrho = ga.rho(gp.xepol, gp)[0]
                    rhodmpar_half = np.exp(
                        splev(gp.dat.rhalf[0], splrep(gp.xepol,
                                                      np.log(anrho))))
                    nr = -gh.derivipol(np.log(anrho), np.log(gp.xepol))
                    dlr = np.hstack([nr[0], nr, nr[-1]])
                    if gp.investigate == 'gaia':
                        dlr[-1] = 4
                        rhodmpar = np.hstack([rhodmpar_half, dlr])
                    lbaryonpar = 0.0 * rhodmpar
                    MtoL = 0.0
                    betapar = np.array([0, 0, 2,
                                        max(gp.xipol) / 2])  # for hern
                    annu = ga.rho(gp.xepol, gp)[1]
                    nupar_half = np.exp(
                        splev(gp.dat.rhalf[1], splrep(gp.xepol, np.log(annu))))
                    nrnu = -gh.derivipol(np.log(annu), np.log(gp.xepol))
                    dlrnu = np.hstack([nrnu[0], nrnu, nrnu[-1]])
                    if gp.investigate == 'gaia':
                        dlrnu[-1] = 6
                    nupar = np.hstack([nupar_half, dlrnu])
                elif gp.checkbeta and gp.investigate == 'gaia':
                    #                    rhodmpar = np.array([ 0.41586608, 0.38655515, 0.60898657, 0.50936769, 0.52601378, 0.54526758,  0.5755599, 0.57900806, 0.60252357, 0.60668445, 0.62252721, 0.63173754, 0.64555439, 0.65777175, 0.67083556, 0.68506606, 0.69139872, 0.66304763, 0.61462276, 0.70916575, 0.53287872])
                    rhodmpar = np.array([
                        0.18235821, 0.4719348, 0., 0., 0.10029569, 0.11309553,
                        0.25637863, 0.31815175, 0.40621336, 0.46247927,
                        0.53545415, 0.60874961, 0.68978141, 0.79781574,
                        0.91218048, 1.08482356, 1.36074895, 1.88041885,
                        2.31792908, 2.62089078, 3.001
                    ])

                    betapar = np.array([
                        1.23555034e-03, 9.89999994e-01, 2.03722518e+00,
                        5.85640906e+00
                    ])
                    nupar = np.array([
                        0.15649498, 6.65618254, 0.10293663, 0.1087109,
                        0.13849277, 0.24371261, 0.62633345, 1.05913181,
                        1.43774113, 1.82346043, 2.20091446, 2.60007997,
                        2.98745825, 3.423104, 3.80766658, 4.2089698,
                        4.62950843, 4.91166037, 4.97380638, 4.99718073,
                        5.2277589
                    ])
                    gp.dat.nrnu = [
                        np.array([
                            0.15476906, 0.85086798, 0.9342867, 0.88161169,
                            0.83254241, 0.85086798, 0.99930431, 1.22211638,
                            1.47184763, 1.78910057, 2.1987677, 2.51961046,
                            2.80345393, 3.10336133, 3.88504346, 4.52442727,
                            4.88817769, 5.07880404, 4.83455511, 6.32165657,
                            4.88817769
                        ]),
                        np.array([
                            0.15476906, 0.85086798, 0.9342867, 0.88161169,
                            0.83254241, 0.85086798, 0.99930431, 1.22211638,
                            1.47184763, 1.78910057, 2.1987677, 2.51961046,
                            2.80345393, 3.10336133, 3.88504346, 4.52442727,
                            4.88817769, 5.07880404, 4.83455511, 6.32165657,
                            4.88817769
                        ]),
                        np.array([
                            0.15476906, 0.85086798, 0.9342867, 0.88161169,
                            0.83254241, 0.85086798, 0.99930431, 1.22211638,
                            1.47184763, 1.78910057, 2.1987677, 2.51961046,
                            2.80345393, 3.10336133, 3.88504346, 4.52442727,
                            4.88817769, 5.07880404, 4.83455511, 6.32165657,
                            4.88817769
                        ]),
                        np.array([
                            0.15476906, 0.85086798, 0.9342867, 0.88161169,
                            0.83254241, 0.85086798, 0.99930431, 1.22211638,
                            1.47184763, 1.78910057, 2.1987677, 2.51961046,
                            2.80345393, 3.10336133, 3.88504346, 4.52442727,
                            4.88817769, 5.07880404, 4.83455511, 6.32165657,
                            4.88817769
                        ])
                    ]
                    gp.dat.nrnuerr = [
                        np.array([
                            0.05158969, 12.22044422, 2.44408884, 2.44408884,
                            2.44408884, 2.44408884, 0.48881777, 0.48881777,
                            0.48881777, 0.48881777, 0.48881777, 0.48881777,
                            0.48881777, 0.48881777, 0.48881777, 0.48881777,
                            0.48881777, 2.44408884, 2.44408884, 2.44408884,
                            2.44408884
                        ]),
                        np.array([
                            0.05158969, 12.22044422, 2.44408884, 2.44408884,
                            2.44408884, 2.44408884, 0.48881777, 0.48881777,
                            0.48881777, 0.48881777, 0.48881777, 0.48881777,
                            0.48881777, 0.48881777, 0.48881777, 0.48881777,
                            0.48881777, 2.44408884, 2.44408884, 2.44408884,
                            2.44408884
                        ]),
                        np.array([
                            0.05158969, 12.22044422, 2.44408884, 2.44408884,
                            2.44408884, 2.44408884, 0.48881777, 0.48881777,
                            0.48881777, 0.48881777, 0.48881777, 0.48881777,
                            0.48881777, 0.48881777, 0.48881777, 0.48881777,
                            0.48881777, 2.44408884, 2.44408884, 2.44408884,
                            2.44408884
                        ]),
                        np.array([
                            0.05158969, 12.22044422, 2.44408884, 2.44408884,
                            2.44408884, 2.44408884, 0.48881777, 0.48881777,
                            0.48881777, 0.48881777, 0.48881777, 0.48881777,
                            0.48881777, 0.48881777, 0.48881777, 0.48881777,
                            0.48881777, 2.44408884, 2.44408884, 2.44408884,
                            2.44408884
                        ])
                    ]

                    lbaryonpar = 0.0 * rhodmpar
                    MtoL = 0.0

                sig, kap, zetaa, zetab = phys.sig_kap_zet(
                    gp.xepol, rhodmpar, lbaryonpar, MtoL, nupar, betapar, pop,
                    gp)
                #fill_between(gp.xipol, gp.dat.sig[1]-gp.dat.sigerr[1], gp.dat.sig[1]+gp.dat.sigerr[1])
                #plot(gp.xepol, sig, 'r')
                #xscale('log')
                #ylim([0, 30])
                #xlabel('$r$ [pc]')
                #ylabel('$\sigma_{LOS}$ [km/s]')
                #savefig('siglos_gaia_2.pdf')
                #pdb.set_trace()
            except Exception:
                gh.LOG(1, 'sigma error')
                tmp_profs.chi2 = gh.err(2., gp)
                return tmp_profs
            # now store the profiles
            gh.sanitize_vector(tmp_beta, len(tmp_profs.x0), -200, 1, gp.debug)
            tmp_profs.set_prof('beta', tmp_beta, pop, gp)
            gh.sanitize_vector(tmp_betastar, len(tmp_profs.x0), -1, 1,
                               gp.debug)
            tmp_profs.set_prof('betastar', tmp_betastar, pop, gp)
            tmp_profs.set_prof('sig', sig, pop, gp)
            tmp_profs.hypersig = tmp_hypersig
            tmp_profs.set_prof('kap', kap, pop, gp)
            tmp_profs.set_zeta(zetaa, zetab, pop)

        tmp_profs.set_prof('nrnu', tmp_nrnu, pop, gp)
        tmp_profs.set_prof('nu', tmp_nu, pop, gp)  # pool: tmp_nu.get()

        # following profile needs to be stored at all times, to calculate chi
        tmp_profs.set_prof('Sig', tmp_Signu, pop, gp)
        tmp_profs.hyperSig = tmp_hyperSig

        off += offstep  # still do this even if gp.chi2_Sig_converged is False
    if off != gp.ndim:
        gh.LOG(1, 'wrong subscripts in gi_loglike')
        pdb.set_trace()

    # determine log likelihood
    chi2 = calc_chi2(tmp_profs, gp)
    gh.LOG(
        -1, gp.investigate + '/' + str(gp.case) + '/' + gp.files.timestamp +
        ':  ln L = ', gh.pretty(-chi2 / 2.))
    # x=gp.dat.rbin
    # linedat,=ax.loglog(x, gp.dat.Sig[1], 'b')
    # line,=ax.loglog(x, tmp_profs.get_prof("Sig", 1), 'r', alpha=0.1)
    # plt.draw()
    # plt.show()
    tmp_profs.chi2 = chi2

    # after some predefined wallclock time and Sig convergence, plot all profiles
    #if time.time() - gp.last_plot >= gp.plot_after and gp.chi2_Sig_converged <= 0:
    #    gp.last_plot = time.time()
    #    try:
    #        import plotting.plot_profiles
    #        plotting.plot_profiles.run(gp.files.timestamp, gp.files.outdir, gp)
    #    except:
    #        print('plotting error in gi_loglike!')
    # close pool automatically after with clause
    return tmp_profs