Example #1
0
def write_analysis_grid():
    """
    Write a P(k,mu) grid for analysis purposes
    """
    from pyRSD.rsd import PkmuGrid
    
    parser = argparse.ArgumentParser()
    parser.formatter_class = argparse.RawTextHelpFormatter
    
    # required arguments
    h = parse_tools.PowerSpectraParser.format_help()
    parser.add_argument('data', type=parse_tools.PowerSpectraParser.data, help=h)
    h = parse_tools.PowerSpectraCallable.format_help()
    parser.add_argument('callable', type=parse_tools.PowerSpectraCallable.data, help=h)
    h = "the (optional) data keys to slice the data on; specified as `a = '0.6452'`"
    parser.add_argument('--key', type=str, nargs='+', action=parse_tools.StoreDataKeys, help=h)
    h = 'the output file name'
    parser.add_argument('-o', '--output', required=True, type=str, help=h)
    args = parser.parse_args()
    
    # get the data from the parent data and function
    data = getattr(args.data, args.callable['name'])(**args.callable['kwargs'])
    
    if args.key is not None:
        coords = data.coords
        for c in coords:
            if c in args.key:
                dt = data.coords[c].dtype.type
                args.key[c] = [dt(x) for x in args.key[c]]
            
    # now slice
    if args.key is not None:
        for k in args.key:
            if len(args.key[k]) != 1:
                raise ValueError("must specify exactly one key for each dimension")
            args.key[k] = args.key[k][0]
        try:
            data = data.sel(**args.key)
            if data.size == 1: data = data.get()
        except Exception as e:
            raise RuntimeError("error slicing data with key %s: %s" %(str(args.key), str(e)))
    
    # now make the grid and save to plaintext file
    grid = PkmuGrid.from_pkmuresult(data)
    grid.to_plaintext(args.output)
Example #2
0
def cutsky_pole_gausscov(pkmu, ells, cosmo, zbins, nbar_spline, P0, fsky, kmin=-np.inf, kmax=np.inf):
    """
    Compute the gaussian covariance for a set of cutsky multipole measurements,
    from the measured P(k,mu) simulation boxes
    
    Parameters
    ----------
    pkmu : nbodykit.PkmuResult
        the mean P(k,mu) periodic measurement, on the finely-binned grid
    ells : array_like, (Nell,)
        the desired multipole numbers
    cosmo : pygcl.Cosmology
        the cosmology instance used in the volume calculation
    zbins : array_like
        bins in redshift, used in the volume calculation
    nbar_spline : callable
        a function returning n(z)
    P0 : float
        the value of P0 used in the FKP weight
    fsky : float
        the fraction of the sky area covered
    kmin : {float, array_like}, optional
        minimum wavenumber to trim by (inclusively), in h/Mpc
    kmax : {float, array_like}, optional
        maximum wavenumber to trim by (inclusively), in h/Mpc
        
    Returns
    -------
    cov : (N, N)
        the covariance matrix for the multipole measurements
    coords : list
        list of the flat coordinates corresponding to the the cov

    """    
    # initialize the grid transfer
    data = pkmu.data.copy()
    grid = PkmuGrid.from_structured([pkmu.coords['k_cen'], pkmu.coords['mu_cen']], data)
    
    # return the Gaussian covariance components
    power = data['power'] - tools.get_Pshot(pkmu)    
    transfer = PolesTransfer(grid, ells, kmin=kmin, kmax=kmax, power=power)

    coords = transfer.coords_flat
    C = transfer.to_cutsky_covariance(cosmo, zbins, nbar_spline, P0, fsky)
    return C, coords
Example #3
0
def data_pole_gausscov(pkmu, ells, kmin=-np.inf, kmax=np.inf, components=False):
    """
    Compute the gaussian covariance for a set of multipole measurements,
    from the measured P(k,mu) observation
    
    Parameters
    ----------
    pkmu : nbodykit.PkmuResult
        the mean P(k,mu) measurement, on the finely-binned grid
    ells : array_like, (Nell,)
        the desired multipole numbers
    kmin : {float, array_like}, optional
        minimum wavenumber to trim by (inclusively), in h/Mpc
    kmax : {float, array_like}, optional
        maximum wavenumber to trim by (inclusively), in h/Mpc
    components : bool, optional
        If `True`, return only the ``mean_power`` and ``modes``
        
    Returns
    -------
    if components == False
        cov : (N, N)
            the covariance matrix for the multipole measurements
    else
        mean_power : (N, N), optional
            the mean power, cov = 2 * mean_power**2 / modes
        modes : (N, N), optional
            the number of modes
    """    
    # initialize the grid transfer
    data = pkmu.data.copy()
    grid = PkmuGrid.from_structured([pkmu.coords['k_cen'], pkmu.coords['mu_cen']], data)
    
    # return the Gaussian covariance components
    kw = {'ells':ells, 'kmin':kmin, 'kmax':kmax, 'power':data['power'], 'components':components}
    return _return_covariance('pole', grid, **kw)
Example #4
0
def data_pkmu_gausscov(pkmu, mu_bounds, kmin=-np.inf, kmax=np.inf, components=False):
    """
    Compute the gaussian covariance for a set of P(k,mu) measurements
    
    Parameters
    ----------
    pkmu : nbodykit.PkmuResult
        the mean P(k,mu) measurement, on the finely-binned grid
    mu_bounds : array_like
        a list of tuples specifying (lower, upper) for each desired
        mu bin, i.e., [(0., 0.2), (0.2, 0.4), (0.4, 0.6), (0.6, 0.8), (0.8, 1.0)]
    kmin : {float, array_like}, optional
        minimum wavenumber to trim by (inclusively), in h/Mpc
    kmax : {float, array_like}, optional
        maximum wavenumber to trim by (inclusively), in h/Mpc
    components : bool, optional
        If `True`, return only the ``mean_power`` and ``modes``
        
    Returns
    -------
    if components == False
        cov : (N, N)
            the covariance matrix for the multipole measurements
    else
        mean_power : (N, N), optional
            the mean power, cov = 2 * mean_power**2 / modes
        modes : (N, N), optional
            the number of modes
    """           
    # initialize the grid transfer
    data = pkmu.data.copy()
    grid = PkmuGrid.from_structured([pkmu.coords['k_cen'], pkmu.coords['mu_cen']], data)
    
    # return the Gaussian covariance components
    kw = {'mu_bounds':mu_bounds, 'kmin':kmin, 'kmax':kmax, 'power':data['power'], 'components':components}
    return _return_covariance('pkmu', grid, **kw)
Example #5
0
def gal_power_discrete(model):

    # set up fake 1D k, mu bins
    k_1d = numpy.arange(0.01, 0.4, 0.005)
    mu_1d = numpy.linspace(0, 1.0, 100)

    # convert to a 2D grid
    # shape is (78, 100)
    k, mu = numpy.meshgrid(k_1d, mu_1d, indexing='ij')

    # assign random weights for each bin for illustration purposes
    modes = numpy.random.random(size=k.shape)

    # simulate missing data
    missing = numpy.random.randint(0, numpy.prod(modes.shape), size=10)
    modes.flat[missing] = numpy.nan

    # initialize the grid
    grid = PkmuGrid([k_1d, mu_1d], k, mu, modes)

    # edges of the mu bins
    mu_bounds = [(0., 0.2), (0.2, 0.4), (0.4, 0.6), (0.6, 0.8), (0.8, 1.0)]

    # the transfer function, with specified valid k range
    transfer = PkmuTransfer(grid, mu_bounds, kmin=0.01, kmax=0.4)

    # evaluate the model with this transfer function
    Pkmu_binned = model.from_transfer(transfer)

    # get the coordinate arrays from the grid
    k, mu = transfer.coords  # this has shape of (Nk, Nmu)

    for i in range(mu.shape[1]):
        plt.loglog(k[:, i],
                   Pkmu_binned[:, i],
                   label=r"$\mu = %.1f$" % mu[:, i].mean())

    plt.legend(loc=0)
    plt.xlabel(r"$k$ $[h \mathrm{Mpc}^{-1}]$", fontsize=10)
    plt.ylabel(r"$P$ $[h^{-3} \mathrm{Mpc}^3]$", fontsize=10)
    savefig("pkmu_binned_plot.png")

    # the multipoles to compute
    ells = [0, 2, 4]

    # the transfer function, with specified valid k range
    transfer = PolesTransfer(grid, ells, kmin=0.01, kmax=0.4)

    # evaluate the model with this transfer function
    poles_binned = model.from_transfer(transfer)  # shape is (78, 3)

    # get the coordinate arrays from the grid
    k, mu = transfer.coords  # this has shape of (Nk, Nmu)

    for i, iell in enumerate(ells):
        plt.loglog(k[:, i], poles_binned[:, i], label=r"$\ell = %d$" % iell)

    plt.legend(loc=0)
    plt.xlabel(r"$k$ $[h \mathrm{Mpc}^{-1}]$", fontsize=10)
    plt.ylabel(r"$P_\ell$ $[h^{-3} \mathrm{Mpc}^3]$", fontsize=10)
    savefig("poles_binned_plot.png")