Beispiel #1
0
def res (pars, **kwargs):

    A        = pars['A'].value
    B        = pars['B'].value
    C        = pars['C'].value

    # displacing particles
    draw_particles(kwargs['pos'], kwargs['mass'], kwargs['npart'],kwargs['r'], kwargs['theta'], kwargs['phi'], A, B, C, kwargs['z'])
    pos_collapsed = np.repeat(kwargs['pos'], kwargs['npart'], axis=0) \
                  + np.transpose([kwargs['r']*np.sin(kwargs['theta'])*np.cos(kwargs['phi']), \
                                  kwargs['r']*np.sin(kwargs['theta'])*np.sin(kwargs['phi']), \
                                  kwargs['r']*np.cos(kwargs['theta'])])
    pos_collapsed /= params.boxsize
    wrapPositions(pos_collapsed)
    pos_collapsed *= params.boxsize
    # Computing delta
    delta = np.copy(delta_uncollapsed)
    MASL.MA(pos_collapsed, delta, params.boxsize, 'CIC', verbose=False)
    Pk = PKL.Pk(delta, params.boxsize, 0, 'CIC', 1, verbose=False)
    # Getting only half of the values
    size = Pk.Nmodes3D.size//2

    sigma = Pk.Pk[:size,0] * np.sqrt( (2.0/Pk.Nmodes3D[:size]) + kwargs['sigma_target']**2 )

    return np.sum( ((Pk.Pk[:size,0] - kwargs['target']) / sigma)**2 )
Beispiel #2
0
def Pk_comp(snapshot_fname,ptype,dims,do_RSD,axis,cpus,folder_out):

    # read relevant paramaters on the header
    print 'Computing power spectrum...'
    head     = readsnap.snapshot_header(snapshot_fname)
    BoxSize  = head.boxsize/1e3 #Mpc/h
    Masses   = head.massarr*1e10 #Msun/h
    Nall     = head.nall;  Ntotal = np.sum(Nall,dtype=np.int64)
    Omega_m  = head.omega_m
    Omega_l  = head.omega_l
    redshift = head.redshift
    Hubble   = 100.0*np.sqrt(Omega_m*(1.0+redshift)**3+Omega_l)  #km/s/(Mpc/h)
    z        = '%.3f'%redshift
        
    # find output file name
    fout = folder_out+'/Pk_' + name_dict[str(ptype)]
    if do_RSD:  fout += ('_RS_axis=' + str(axis) + '_z=' + z + '.dat')
    else:       fout +=                           ('_z=' + z + '.dat')

    # read the positions of the particles
    pos = readsnap.read_block(snapshot_fname,"POS ",parttype=ptype)/1e3 #Mpc/h
    print '%.3f < X [Mpc/h] < %.3f'%(np.min(pos[:,0]),np.max(pos[:,0]))
    print '%.3f < Y [Mpc/h] < %.3f'%(np.min(pos[:,1]),np.max(pos[:,1]))
    print '%.3f < Z [Mpc/h] < %.3f\n'%(np.min(pos[:,2]),np.max(pos[:,2]))

    # read the velocities of the particles
    if do_RSD:
        print 'moving particles to redshift-space...'
        vel = readsnap.read_block(snapshot_fname,"VEL ",parttype=ptype) #km/s
        RSL.pos_redshift_space(pos,vel,BoxSize,Hubble,redshift,axis)
        del vel;  print 'done'

    # define delta array
    delta = np.zeros((dims,dims,dims),dtype=np.float32)

    # when dealing with all particles take into account their different masses
    if ptype==-1:
        if Nall[0]==0: #if not hydro
            M = np.zeros(Ntotal,dtype=np.float32) #define the mass array
            offset = 0
            for ptype in [0,1,2,3,4,5]:
                M[offset:offset+Nall[ptype]] = Masses[ptype]
                offset += Nall[ptype]
        else:
            M = readsnap.read_block(snapshot_fname,"MASS",parttype=-1)*1e10
        
        mean = np.sum(M,dtype=np.float64)/dims**3
        MASL.MA(pos,delta,BoxSize,'CIC',M); del pos,M

    else:  
        mean = len(pos)*1.0/dims**3
        MASL.MA(pos,delta,BoxSize,'CIC'); del pos

    # compute the P(k) and save results to file
    delta /= mean;  delta -= 1.0
    Pk = PKL.Pk(delta,BoxSize,axis=axis,MAS='CIC',threads=cpus);  del delta
    np.savetxt(fout,np.transpose([Pk.k3D, Pk.Pk[:,0], Pk.Pk[:,1], Pk.Pk[:,2],
                                  Pk.Nmodes3D]))
Beispiel #3
0
def compute_Pk(snapshot, grid, MAS, threads, ptype, root_out):

    # read header
    if not(os.path.exists(snapshot)):  return 0
    head     = readgadget.header(snapshot)
    BoxSize  = head.boxsize/1e3  #Mpc/h  
    Nall     = head.nall         #Total number of particles
    Masses   = head.massarr*1e10 #Masses of the particles in Msun/h                    
    Omega_m  = head.omega_m
    Omega_l  = head.omega_l
    redshift = head.redshift
    Hubble   = 100.0*np.sqrt(Omega_m*(1.0+redshift)**3+Omega_l)#km/s/(Mpc/h)
    h        = head.hubble
    Ntot     = np.sum(Nall[ptype], dtype=np.int64)

    # get the name of the output file
    fout = '%s/Pk_%s_z=%.2f.txt'%(root_out, Pk_suffix(ptype), redshift)
    if os.path.exists(fout):  return 0

    # define the arrays containing the number positions and masses of the particles
    pos  = np.zeros((Ntot,3), dtype=np.float32)
    mass = np.zeros(Ntot,     dtype=np.float32)

    # read data for the different particle types
    f = h5py.File(snapshot, 'r');  offset = 0
    for pt in ptype:
        # sometimes there are not black-holes or stars...
        if 'PartType%d'%pt not in f.keys():  continue

        # read positions
        pos_pt  = f['PartType%d/Coordinates'%pt][:]/1e3  #Mpc/h
        if pos_pt.dtype==np.float64:  pos_pt = pos_pt.astype(np.float32)

        # read masses
        if 'PartType%d/Masses'%pt in f:
            mass_pt = f['PartType%d/Masses'%pt][:]*1e10                    #Msun/h
        else:
            mass_pt = np.ones(pos_pt.shape[0], dtype=np.float32)*Masses[1] #Msun/h

        # fill pos and mass arrays
        length  = len(pos_pt)
        pos[offset:offset+length]  = pos_pt
        mass[offset:offset+length] = mass_pt
        offset += length
    f.close()
    if offset!=Ntot:  raise Exception('Not all particles counted')

    # calculate density field
    delta = np.zeros((grid,grid,grid), dtype=np.float32)
    MASL.MA(pos, delta, BoxSize, MAS, W=mass)
    delta /= np.mean(delta, dtype=np.float64);  delta -= 1.0 

    # compute Pk and save results to file
    axis = 0
    Pk = PKL.Pk(delta, BoxSize, axis, MAS, threads)
    np.savetxt(fout, np.transpose([Pk.k3D, Pk.Pk[:,0]]), delimiter='\t')
Beispiel #4
0
def getG3power(sim, kmax):
    if z == 99:
        snap = sim + "/output/ics"
    elif z == 49:
        snap = sim + "/output/snapdir_000/PART_000"
    elif z == 9:
        snap = sim + "/output/snapdir_001/PART_001"
    elif z == 4:
        snap = sim + "/output/snapdir_002/PART_002"
    elif z == 3:
        snap = sim + "/output/snapdir_003/PART_003"
    elif z == 2:
        snap = sim + "/output/snapdir_005/PART_005"
    else:
        print("Don't have data for that redshift")
        quit()

    head = readsnap.snapshot_header(snap)
    rho_crit = 2.77536627e11
    BoxSize = head.boxsize / 1e3  #Mpc/h
    Nall = head.nall
    Masses = head.massarr * 1e10  #Msun/h
    Omega_m = head.omega_m
    Omega_l = head.omega_l
    redshift = head.redshift

    ## Pylian params
    grid = 512
    ptypes = [1]
    MAS = 'CIC'
    do_RSD = False
    axis = 0
    threads = 1
    assert (z -
            redshift) < 0.001, "Redshift requested: %s, redshift found: %s" % (
                z, redshift)
    Omega_cdm = Nall[1] * Masses[1] / BoxSize**3 / rho_crit
    Omega_b = Omega_m - Omega_cdm

    ## Calculate fractions
    f_b = Omega_b / (Omega_cdm + Omega_b)
    f_c = Omega_cdm / (Omega_cdm + Omega_b)

    ## CDM
    delta = MASL.density_field_gadget(snap, ptypes, grid, MAS, do_RSD, axis)
    delta /= np.mean(delta, dtype=np.float64)
    delta -= 1.0
    print("Mean after normalising = %.2e" % np.mean(delta, dtype=np.float64))
    Pk = PKL.Pk(delta, BoxSize, axis, MAS, threads)
    # Calculate power
    k_sim = Pk.k3D
    Pk_sim = Pk.Pk[:, 0]
    Nmodes1D = Pk.Nmodes1D

    return k_sim[np.where(k_sim < kmax)], Pk_sim[np.where(
        k_sim < kmax)], BoxSize
def find_Pk(snapshot, grid, MAS, do_RSD, axis, threads, ptype, fpk,
            save_multipoles):

    if os.path.exists(fpk): return 0

    # read header
    head = readgadget.header(snapshot)
    BoxSize = head.boxsize / 1e3  #Mpc/h
    Nall = head.nall  #Total number of particles
    Masses = head.massarr * 1e10  #Masses of the particles in Msun/h
    Omega_m = head.omega_m
    Omega_l = head.omega_l
    redshift = head.redshift
    Hubble = 100.0 * np.sqrt(Omega_m *
                             (1.0 + redshift)**3 + Omega_l)  #km/s/(Mpc/h)
    h = head.hubble

    # read snapshot
    pos = readgadget.read_block(snapshot, "POS ", ptype) / 1e3  #Mpc/h

    # move particles to redshift-space
    if do_RSD:
        vel = readgadget.read_block(snapshot, "VEL ", ptype)  #km/s
        RSL.pos_redshift_space(pos, vel, BoxSize, Hubble, redshift, axis)

    # calculate Pk
    delta = np.zeros((grid, grid, grid), dtype=np.float32)
    if len(ptype) > 1:  #for multiple particles read masses
        mass = np.zeros(pos.shape[0], dtype=np.float32)
        offset = 0
        for j in ptype:
            mass[offset:offset + Nall[j]] = Masses[j]
            offset += Nall[j]
        MASL.MA(pos, delta, BoxSize, MAS, W=mass)
    else:
        MASL.MA(pos, delta, BoxSize, MAS)
    delta /= np.mean(delta, dtype=np.float64)
    delta -= 1.0
    Pk = PKL.Pk(delta, BoxSize, axis, MAS, threads)

    # save results to file
    if save_multipoles:
        np.savetxt(fpk,
                   np.transpose(
                       [Pk.k3D, Pk.Pk[:, 0], Pk.Pk[:, 1], Pk.Pk[:, 2]]),
                   delimiter='\t')
    else:
        np.savetxt(fpk, np.transpose([Pk.k3D, Pk.Pk[:, 0]]), delimiter='\t')
Beispiel #6
0
def computePower(delta, realization):
    ''' Measure Powerspectrum. The output is saved in a txt file in the folder
        specified by output in initializeGlobals.

        delta : array_like
            input data, shape = (gridsize, gridsize, gridsize)
        realization: integer

        file format: k | P0(k)
    '''

    filename = OutputDir + 'powerspectrum%i.dat' % realization
    print('\n Computing power, saving at ' + filename)

    Pkpyl = PKL.Pk(delta, BoxSize, axis, MAS, threads, verbose)

    np.savetxt(filename, np.vstack([Pkpyl.k3D, Pkpyl.Pk[:, 0]]).T)
Beispiel #7
0
def find_Pk(folder, snapdir, snapnum, grid, MAS, do_RSD, axis, threads,
            fixed_Mmin, Mmin, Nhalos, fpk, save_multipoles):

    if os.path.exists(fpk):  return 0
    
    # read header
    head     = readgadget.header(snapdir)
    BoxSize  = head.boxsize/1e3  #Mpc/h                      
    Omega_m  = head.omega_m
    Omega_l  = head.omega_l
    redshift = head.redshift
    Hubble   = 100.0*np.sqrt(Omega_m*(1.0+redshift)**3+Omega_l)#km/s/(Mpc/h)
    h        = head.hubble

    # read halo catalogue
    FoF   = readfof.FoF_catalog(folder, snapnum, long_ids=False,
                                swap=False, SFR=False, read_IDs=False)
    pos_h = FoF.GroupPos/1e3            #Mpc/h
    mass  = FoF.GroupMass*1e10          #Msun/h
    vel_h = FoF.GroupVel*(1.0+redshift) #km/s
    if fixed_Mmin:
        indexes = np.where(mass>Mmin)[0]
        pos_h = pos_h[indexes];  vel_h = vel_h[indexes];  del indexes
    else:
        indexes = np.argsort(mass)[-Nhalos:] #take the Nhalos most massive halos
        pos_h = pos_h[indexes];  vel_h = vel_h[indexes];  del indexes

    # move halos to redshift-space
    if do_RSD:  RSL.pos_redshift_space(pos_h, vel_h, BoxSize, Hubble, redshift, axis)

    # calculate Pk
    delta = np.zeros((grid,grid,grid), dtype=np.float32)
    MASL.MA(pos_h, delta, BoxSize, MAS)
    delta /= np.mean(delta, dtype=np.float64);  delta -= 1.0 
    Pk = PKL.Pk(delta, BoxSize, axis, MAS, threads)

    # save results to file
    hdr = ('Nhalos=%i BoxSize=%.3f'%(pos_h.shape[0],BoxSize))    
    if save_multipoles:
        np.savetxt(fpk, np.transpose([Pk.k3D, Pk.Pk[:,0], Pk.Pk[:,1], Pk.Pk[:,2]]),
                   delimiter='\t', header=hdr)
    else:
        np.savetxt(fpk, np.transpose([Pk.k3D, Pk.Pk[:,0]]),
                   delimiter='\t', header=hdr)
Beispiel #8
0
def compute_Pk_ICs(snapshot, grid, MAS, threads, ptype, root_out):

    if not(os.path.exists(snapshot)) and not(os.path.exists(snapshot+'.0')):  return 0

    # read header
    head     = readgadget.header(snapshot)
    BoxSize  = head.boxsize/1e3  #Mpc/h  
    redshift = head.redshift

    # get the name of the file
    fout = '%s/Pk_%s_z=%.2f.txt'%(root_out, Pk_suffix(ptype), redshift)
    if os.path.exists(fout):  return 0
    
    # compute overdensity field
    do_RSD, axis = False, 0
    delta = MASL.density_field_gadget(snapshot, ptype, grid, MAS, do_RSD, axis)
    delta /= np.mean(delta, dtype=np.float64);  delta -= 1.0

    # compute Pk and save results to file
    Pk = PKL.Pk(delta, BoxSize, axis, MAS, threads)
    np.savetxt(fout, np.transpose([Pk.k3D, Pk.Pk[:,0]]), delimiter='\t')
Beispiel #9
0
def Mk(galaxy_pos, Filter, R, p, ds, BoxSize, grid, MAS, threads):
    
    ''' Measure the marked spectrum using the `Pylians3` package  
    Input:
        galaxy_pos: (N,3) array
        FIlter:     'Top-Hat' or 'Gaussian'
        R:          parameter of the mark: scale to define local density
        p:          parameter of the mark
        ds:         parameter of the mark
        BoxSize
        grid:       scalar: size of the grid where we compute the density
        MAS:        'CIC'
        threads:    scalar
    Output:     
        Pk:         object with power spectrum: k = Pk.k3D
                                                P0 = Pk.Pk[:,0]
                                                P2 = Pk.Pk[:,1]
                                                P4 = Pk.Pk[:,2]
    '''
    
    # calculate delta                                                                                                   
    delta = np.zeros((grid,grid,grid), dtype=np.float32)
    MASL.MA(galaxy_pos, delta, BoxSize, MAS)
    delta /= np.mean(delta, dtype=np.float64);  delta -= 1.0
    # smooth delta                                                                                                      
    W_k = SL.FT_filter(BoxSize, R, grid, Filter, threads)
    delta_smoothed = SL.field_smoothing(delta, W_k, threads)
    # marks                                                                                                             
    weight = np.zeros(galaxy_pos.shape[0], dtype=np.float32)
    MASL.CIC_interp(delta_smoothed, BoxSize, galaxy_pos, weight)
    mark = func_mark(weight,ds,p)
    delta_m = np.zeros((grid,grid,grid), dtype=np.float32)
    MASL.MA(galaxy_pos,delta_m,BoxSize,MAS,W=mark)
    delta_m /= np.mean(delta_m,dtype=np.float32);  delta_m -= 1.0
    # compute marked Pk                                                                                                 
    Pk = PKL.Pk(delta_m, BoxSize, axis, MAS, threads)
    return Pk
Beispiel #10
0
def plot_power_spec(real_cube, generated_cube,
                   threads=1, MAS="CIC", axis=0, BoxSize=75.0/2048*128):
    """Takes as input;
    - Real cube: (n x n x n) torch cuda FloatTensor,
    - Generated copy: (n x n x n) torch cuda FloatTensor,
    - constant assignments: threads, MAS, axis, BoxSize.
    
    Returns;
    - Power spectrum plots of both cubes
    in the same figure.
    """
    
    ## Assert same type
    assert ((real_cube.type() == generated_cube.type())&(real_cube.type()=="torch.FloatTensor")),\
    "Both input cubes should be torch.FloatTensor or torch.cuda().FloatTensor. Got real_cube type " + real_cube.type() + ", generated_cube type " + generated_cube.type() +"."
    ## Assert equal dimensions
    assert (real_cube.size() == generated_cube.size()),\
    "Two input cubes must have the same size. Got real_cube size " + str(real_cube.size()) + ", generated cube size " + str(generated_cube.size())
    
    ## if one or both of the cubes are cuda FloatTensors, detach them
    if real_cube.type() == "torch.cuda.FloatTensor":
        ## convert cuda FloatTensor to numpy array
        real_cube = real_cube.cpu().detach().numpy()
    else:
        real_cube = real_cube.numpy()
    
    if generated_cube.type() == "torch.cuda.FloatTensor":
        ## convert cuda FloatTensor to numpy array
        generated_cube = generated_cube.cpu().detach().numpy()
    else:
        generated_cube = generated_cube.numpy()
    
    # constant assignments
    BoxSize = BoxSize
    axis = axis
    MAS = MAS
    threads = threads

    # CALCULATE POWER SPECTRUM OF THE REAL CUBE
    # SHOULD WE DIVIDE BY WHOLE CUBE MEAN OR JUST THE MEAN OF THIS PORTION
    # Ask the Team
#     delta_real_cube /= mean_cube.astype(np.float64)
    
    delta_real_cube = real_cube
    delta_gen_cube = generated_cube
    
    delta_real_cube /= np.mean(delta_real_cube,
                              dtype=np.float64)
    delta_real_cube -= 1.0
    delta_real_cube = delta_real_cube.astype(np.float32)
    
    Pk_real_cube = PKL.Pk(delta_real_cube, BoxSize, axis, MAS, threads)
    
    
    # CALCULATE POWER SPECTRUM OF THE GENERATED CUBE
    delta_gen_cube /= np.mean(delta_gen_cube,
                             dtype=np.float64)
    delta_gen_cube -= 1.0
    delta_gen_cube = delta_gen_cube.astype(np.float32)
    
    Pk_gen_cube = PKL.Pk(delta_gen_cube, BoxSize, axis, MAS, threads)
    
    plt.figure(figsize=(10,5))
    plt.plot(np.log(Pk_real_cube.k3D), np.log(Pk_real_cube.Pk[:,0]), color="b", label="original cube")
    plt.plot(np.log(Pk_gen_cube.k3D), np.log(Pk_gen_cube.Pk[:,0]), color="r", label="jaas")
    plt.rcParams["font.size"] = 12
    plt.title("Power Spectrum Comparison")
    plt.xlabel('log(Pk.k3D)')
    plt.ylabel('log(Pk.k3D)')
    plt.legend()
    
    plt.show()
    return "Power spectrum plot complete!"
        snapshot_root = '%s/output/' % run
        halos = groupcat.loadHalos(
            snapshot_root,
            snapnum,
            fields=['GroupPos', 'GroupMass', 'GroupVel'])
        halo_pos = halos['GroupPos'] / 1e3  #Mpc/h
        halo_mass = halos['GroupMass'] * 1e10  #Msun/h
        halo_vel = halos['GroupVel'] * (1.0 + z)  #km/s
        del halos

        # move halo positions to redshift-space
        RSL.pos_redshift_space(halo_pos, halo_vel, BoxSize, Hubble, z, axis)

        print np.min(halo_pos[:, 0]), np.max(halo_pos[:, 0])
        print np.min(halo_pos[:, 1]), np.max(halo_pos[:, 1])
        print np.min(halo_pos[:, 2]), np.max(halo_pos[:, 2])

        M_HI = M0 * (halo_mass /
                     Mmin)**alpha * np.exp(-(Mmin / halo_mass)**(0.35))

        delta_HI = np.zeros((dims, dims, dims), dtype=np.float32)

        MASL.MA(halo_pos, delta_HI, BoxSize, MAS, W=M_HI)
        delta_HI /= np.mean(delta_HI, dtype=np.float64)
        delta_HI -= 1.0

        Pk = PKL.Pk(delta_HI, BoxSize, axis, MAS, 8)

        np.savetxt('Pk_HI_Nbody_redshift_space_%d_z=%.1f.txt' % (axis, z),
                   np.transpose([Pk.k3D, Pk.Pk[:, 0]]))
Beispiel #12
0
    'Pk_0.0eV_1000_reps_z=0.txt', 'Pk_0.0eV_1000_reps_1_z=0.txt',
    'Pk_0.0eV_512_reps_z=0.txt', 'Pk_0.0eV_512_reps_1_z=0.txt',
    'Pk_0.0eV_1000_2LPT_z=0.txt', 'Pk_0.0eV_1000_2LPT_1_z=0.txt',
    'Pk_0.0eV_512_2LPT_z=0.txt', 'Pk_0.0eV_512_2LPT_1_z=0.txt'
]

grid = 512
ptypes = [1]
MAS = 'CIC'
do_RSD = False
axis = 0
threads = 1
verbose = True

# do a loop over all snapshots
for snapshot, fout in zip(snapshots, fouts):

    # read header
    header = readgadget.header(snapshot)
    BoxSize = header.boxsize / 1e3  #Mpc/h

    delta = MASL.density_field_gadget(snapshot, ptypes, grid, MAS, do_RSD,
                                      axis)
    delta /= np.mean(delta, dtype=np.float64)
    delta -= 1.0

    # compute Pk
    Pk = PKL.Pk(delta, BoxSize, axis, MAS, threads, verbose)

    np.savetxt(fout, np.transpose([Pk.k3D, Pk.Pk[:, 0]]))
grid = 256  #grid size, chose a small one for now because of RAM issues
ptypes = [1]  #we investigate the CDM + baryon power spectrum
MAS = 'CIC'  #Cloud-in-Cell
do_RSD = False  #dont do redshif-space distortions
axis = 0  #axis along which place RSD; not used here
verbose = True  #whether print information on the progress
BoxSize = 512
threads = 4

#calculate Pk for the 0.0eV reference run
ref_delta = MASL.density_field_gadget(ref, ptypes, grid, MAS, do_RSD, axis,
                                      verbose)
ref_delta /= np.mean(ref_delta, dtype=np.float64)
ref_delta -= 1.0
ref_Pk = PKL.Pk(ref_delta, BoxSize, axis, MAS, threads, verbose)
ref_k = ref_Pk.k3D
ref_Pk0 = ref_Pk.Pk[:, 0]

#calculate Pk for the reference run with given neutrino mass
ref_mass_delta = MASL.density_field_gadget(ref_mass, ptypes, grid, MAS, do_RSD,
                                           axis, verbose)
ref_mass_delta /= np.mean(ref_mass_delta, dtype=np.float64)
ref_mass_delta -= 1.0
ref_mass_Pk = PKL.Pk(ref_mass_delta, BoxSize, axis, MAS, threads, verbose)
ref_mass_k = ref_mass_Pk.k3D
ref_mass_Pk0 = ref_mass_Pk.Pk[:, 0]

#set up the figure
fig, ax = plt.subplots(2, 2, figsize=(7, 7))
fig.suptitle(mass[:-1])
Beispiel #14
0
            snapshot = '%s/output/snapdir_%03d/snap_%03d.%d.hdf5'\
                %(run,snapnum,snapnum,i)
            f = h5py.File(snapshot, 'r')

            # read pos, radii, densities, HI/H and masses of gas particles
            pos = (f['PartType1/Coordinates'][:] / 1e3).astype(np.float32)
            vel = f['PartType1/Velocities'][:] * np.sqrt(scale_factor)

            # move gas particles to redshift-space
            RSL.pos_redshift_space(pos, vel, BoxSize, Hubble, redshift, axis)

            ######## delta_c ########
            MASL.MA(pos, delta_c, BoxSize, MAS)

            print 'i = %d' % i

        f = h5py.File(fout, 'w')
        f.create_dataset('delta_c', data=delta_c)
        f.close()

        delta_c /= np.mean(delta_c, dtype=np.float64)
        delta_c -= 1.0

        Pk = PKL.Pk(delta_c, BoxSize, axis, 'CIC', threads=8)

        np.savetxt('Pk_CDM_RS_%d_z=%.1f.txt' % (axis, redshift),
                   np.transpose([Pk.k3D, Pk.Pk[:, 0]]))

        np.savetxt('Pk2D_CDM_RS_%d_z=%.1f.txt' % (axis, redshift),
                   np.transpose([Pk.kpar, Pk.kper, Pk.Pk2D]))
Beispiel #15
0
def Pk_Gadget(snapshot_fname,dims,particle_type,do_RSD,axis,cpus,
              folder_out=None):

    # find folder to place output files. Default is current directory
    if folder_out is None:  folder_out = os.getcwd()

    # for either one single species or all species use this routine
    if len(particle_type)==1:
        Pk_comp(snapshot_fname,particle_type[0],dims,do_RSD,
                axis,cpus,folder_out)
        return None

    # read snapshot head and obtain BoxSize, Omega_m and Omega_L
    print '\nREADING SNAPSHOTS PROPERTIES'
    head     = readsnap.snapshot_header(snapshot_fname)
    BoxSize  = head.boxsize/1e3  #Mpc/h
    Nall     = head.nall
    Masses   = head.massarr*1e10 #Msun/h
    Omega_m  = head.omega_m
    Omega_l  = head.omega_l
    redshift = head.redshift
    Hubble   = 100.0*np.sqrt(Omega_m*(1.0+redshift)**3+Omega_l)  #km/s/(Mpc/h)
    h        = head.hubble
    z        = '%.3f'%redshift
    dims3    = dims**3

    # compute the values of Omega_cdm, Omega_nu, Omega_gas and Omega_s
    Omega_c = Masses[1]*Nall[1]/BoxSize**3/rho_crit
    Omega_n = Masses[2]*Nall[2]/BoxSize**3/rho_crit
    Omega_g, Omega_s = 0.0, 0.0
    if Nall[0]>0:
        if Masses[0]>0:  
            Omega_g = Masses[0]*Nall[0]/BoxSize**3/rho_crit
            Omega_s = Masses[4]*Nall[4]/BoxSize**3/rho_crit
        else:    
            # mass in Msun/h
            mass = readsnap.read_block(snapshot_fname,"MASS",parttype=0)*1e10 
            Omega_g = np.sum(mass,dtype=np.float64)/BoxSize**3/rho_crit
            mass = readsnap.read_block(snapshot_fname,"MASS",parttype=4)*1e10
            Omega_s = np.sum(mass,dtype=np.float64)/BoxSize**3/rho_crit
            del mass

    # some verbose
    print 'Omega_gas    = ',Omega_g
    print 'Omega_cdm    = ',Omega_c
    print 'Omega_nu     = ',Omega_n
    print 'Omega_star   = ',Omega_s
    print 'Omega_m      = ',Omega_g + Omega_c + Omega_n + Omega_s
    print 'Omega_m snap = ',Omega_m

    # dictionary giving the value of Omega for each component
    Omega_dict = {0:Omega_g, 1:Omega_c, 2:Omega_n, 4:Omega_s}
    #####################################################################

    # define the array containing the deltas
    delta = [[],[],[],[]]  #array containing the gas, CDM, NU and stars deltas

    # dictionary among particle type and the index in the delta and Pk arrays
    # delta of stars (ptype=4) is delta[3] not delta[4]
    index_dict = {0:0, 1:1, 2:2, 4:3} 

    # define suffix here
    if do_RSD:  suffix = '_RS_axis=' + str(axis) + '_z=' + z + '.dat'
    else:       suffix =                           '_z=' + z + '.dat'
    #####################################################################

    # do a loop over all particle types and compute the deltas
    for ptype in particle_type:
    
        # read particle positions in #Mpc/h
        pos = readsnap.read_block(snapshot_fname,"POS ",parttype=ptype)/1e3 

        # move particle positions to redshift-space
        if do_RSD:
            vel = readsnap.read_block(snapshot_fname,"VEL ",parttype=ptype)#km/s
            RSL.pos_redshift_space(pos,vel,BoxSize,Hubble,redshift,axis)
            del vel

        # find the index of the particle type in the delta array
        index = index_dict[ptype]

        # compute mean number of particles per grid cell
        mean_number = len(pos)*1.0/dims3

        # compute the deltas
        delta[index] = np.zeros((dims,dims,dims),dtype=np.float32)
        MASL.MA(pos,delta[index],BoxSize,'CIC');  del pos
        delta[index] /= mean_number;  delta[index] -= 1.0
    #####################################################################

    #####################################################################
    # if there are two or more particles compute auto- and cross-power spectra
    for i,ptype1 in enumerate(particle_type):
        for ptype2 in particle_type[i+1:]:

            # find the indexes of the particle types
            index1 = index_dict[ptype1];  index2 = index_dict[ptype2]

            # choose the name of the output files
            fout1  = '/Pk_' + name_dict[str(ptype1)]             + suffix
            fout2  = '/Pk_' + name_dict[str(ptype2)]             + suffix
            fout12 = '/Pk_' + name_dict[str(ptype1)+str(ptype2)] + suffix
            fout1  = folder_out + fout1
            fout2  = folder_out + fout2
            fout12 = folder_out + fout12

            # some verbose
            print '\nComputing the auto- and cross-power spectra of types: '\
                ,ptype1,'-',ptype2
            print 'saving results in:';  print fout1,'\n',fout2,'\n',fout12

            # This routine computes the auto- and cross-power spectra
            data = PKL.XPk([delta[index1],delta[index2]],BoxSize,axis=axis,
                           MAS=['CIC','CIC'],threads=cpus)
                                                        
            k = data.k3D;   Nmodes = data.Nmodes3D

            # save power spectra results in the output files
            np.savetxt(fout12,np.transpose([k,
                                            data.XPk[:,0,0],
                                            data.XPk[:,1,0],
                                            data.XPk[:,2,0],
                                            Nmodes]))
            np.savetxt(fout1, np.transpose([k,
                                            data.Pk[:,0,0],
                                            data.Pk[:,1,0],
                                            data.Pk[:,2,0],
                                            Nmodes]))
            np.savetxt(fout2, np.transpose([k,
                                            data.Pk[:,0,1],
                                            data.Pk[:,1,1],
                                            data.Pk[:,2,1],
                                            Nmodes]))
    #####################################################################

    #####################################################################
    # compute the power spectrum of the sum of all components
    print '\ncomputing P(k) of all components'

    # define delta of all components
    delta_tot = np.zeros((dims,dims,dims),dtype=np.float32)

    Omega_tot = 0.0;  fout = folder_out + '/Pk_'
    for ptype in particle_type:
        index = index_dict[ptype]
        delta_tot += (Omega_dict[ptype]*delta[index])
        Omega_tot += Omega_dict[ptype]
        fout += name_dict[str(ptype)] + '+'

    delta_tot /= Omega_tot;  del delta;  fout = fout[:-1] #avoid '+' in the end
    
    # compute power spectrum
    data = PKL.Pk(delta_tot,BoxSize,axis=axis,MAS='CIC',
                  threads=cpus);  del delta_tot

    # write P(k) to output file
    np.savetxt(fout+suffix, np.transpose([data.k3D,
                                          data.Pk[:,0],
                                          data.Pk[:,1],
                                          data.Pk[:,2],
                                          data.Nmodes3D]))
 def __compute_powerspectrum(self):  #{{{
     Pk = PKL.Pk(self.data, self.BoxSize, 0, self.MAS, ARGS.threads)
     self.powerspectrum = {
         'k': Pk.k1D,
         'P': Pk1D,
     }
Beispiel #17
0
def getG3power(sim, kmax):
    ## Get desired redshift
    if z == 99:
        snap = sim + "/output/ics"
    elif z == 49:
        snap = sim + "/output/snapdir_000/PART_000"
    elif z == 9:
        snap = sim + "/output/snapdir_001/PART_001"
    elif z == 4:
        snap = sim + "/output/snapdir_002/PART_002"
    elif z == 3:
        snap = sim + "/output/snapdir_003/PART_003"
    elif z == 2:
        snap = sim + "/output/snapdir_005/PART_005"
    else:
        print("Don't have data for that redshift")
        quit()

    head = readsnap.snapshot_header(snap)
    rho_crit = 2.77536627e11
    BoxSize = head.boxsize / 1e3  #Mpc/h
    Nall = head.nall
    Masses = head.massarr * 1e10  #Msun/h
    Omega_m = head.omega_m
    Omega_l = head.omega_l
    redshift = head.redshift

    ## Pylian params
    grid = 256
    ptypes = [1]
    MAS = 'CIC'
    do_RSD = False
    axis = 0
    threads = 1
    assert (z -
            redshift) < 0.001, "Redshift requested: %s, redshift found: %s" % (
                z, redshift)
    Omega_cdm = Nall[1] * Masses[1] / BoxSize**3 / rho_crit
    Omega_b = Omega_m - Omega_cdm

    ## Calculate fractions
    f_b = Omega_b / (Omega_cdm + Omega_b)
    f_c = Omega_cdm / (Omega_cdm + Omega_b)

    ## CDM
    delta = MASL.density_field_gadget(snap, ptypes, grid, MAS, do_RSD, axis)
    delta /= np.mean(delta, dtype=np.float64)
    delta -= 1.0
    print("Mean after normalising = %.2e" % np.mean(delta, dtype=np.float64))
    Pk = PKL.Pk(delta, BoxSize, axis, MAS, threads)

    # Calculate power
    k_sim = Pk.k3D
    Pk_sim = Pk.Pk[:, 0]
    Nmodes1D = Pk.Nmodes1D

    ## Baryons
    deltaby = MASL.density_field_gadget(snap, [0], grid, MAS, do_RSD, axis)
    deltaby /= np.mean(deltaby, dtype=np.float64)
    deltaby -= 1.0
    print("Mean after normalising = %.2e" % np.mean(delta, dtype=np.float64))
    Pkby = PKL.Pk(deltaby, BoxSize, axis, MAS, threads)

    # Calculate power
    k_simby = Pkby.k3D
    Pk_simby = Pkby.Pk[:, 0]
    Nmodes1D = Pk.Nmodes1D

    ## Make sure we can find total matter
    assert (np.mean(k_simby - k_sim)
            ) == 0.0, "k-arrays not equal, can't find total matter power"
    Pk_av = Pk_sim * f_c**2 + Pk_simby * f_b**2 + 2 * f_c * f_b * np.sqrt(
        Pk_sim * Pk_simby)

    return k_sim[np.where(k_sim < kmax)], Pk_simby[np.where(
        k_sim < kmax)], Pk_sim[np.where(k_sim < kmax)], Pk_av[np.where(
            k_sim < kmax)], BoxSize
Beispiel #18
0

# read the positions and velocities of the particles
pos = readsnap.read_block(snapshot_fname,"POS ",parttype=1)/1e3 #Mpc/h
vel = readsnap.read_block(snapshot_fname,"VEL ",parttype=1) #km/s

# move particles to redshift-space
RSL.pos_redshift_space(pos, vel, BoxSize, Hubble, redshift, axis)

# compute density field in redshift-space
delta = np.zeros((dims, dims, dims), dtype=np.float32) #this should be your density field
MASL.MA(pos, delta, BoxSize, MAS='CIC') # computes the density in each cell of the grid
delta = delta/np.mean(delta) - 1.0

# compute power spectra
Pk = PKL.Pk(delta, BoxSize, axis, MAS='CIC', threads=cores) #Pk here is a class with all power spectra

# 3D Pk
k = Pk.k3D
Pk0 = Pk.Pk[:,0] #monopole
Pk2 = Pk.Pk[:,1] #quadrupole
Pk4 = Pk.Pk[:,2] #hexadecapole
Nmodes = Pk.Nmodes3D #number of modes in each Pk bin


# 2D Pk
kpar = Pk.kpar
kperp = Pk.kper
Pk2D = Pk.Pk2D
Nmodes2D = Pk.Nmodes2D
Beispiel #19
0
def do_snap(snap):
    #load shapshot
    print('Loading snapshot', snap)

    snapshot_fname = '/cosma6/data/dp004/dc-smit4/Daemmerung/Planck2013-Npart_2048_Box_3000-Fiducial/run1/snapdir_{0:03d}/Planck2013-L3000-N2048-Fiducial_{0:03d}'.format(
        snap)
    density_fname = '/cosma6/data/dp004/dc-boot5/Lightcone/Density/density_{0:03d}.npy'.format(
        snap)
    powerspec_path = '/cosma6/data/dp004/dc-boot5/Lightcone/Power_Spectrum/'
    lightcone_path = "/cosma6/data/dp004/dc-boot5/Lightcone/Galaxy_FullSky/"

    #calculate density delta
    # declare the array hosting the density field
    density = np.zeros((dims, dims, dims), dtype=np.float32)

    # read relevant paramaters on the snapshot
    head = readgadget.header(snapshot_fname)
    BoxSize = head.boxsize / 1e3  #Mpc/h
    Masses = head.massarr * 1e10  #Msun/h
    Nall = head.nall
    filenum = head.filenum
    Omega_m = head.omega_m
    Omega_l = head.omega_l
    redshift = head.redshift
    fformat = head.format
    Hubble = head.Hubble

    Ntotal = np.sum(Nall, dtype=np.int64)

    grid = 2048
    MAS = 'CIC'
    axis = 0
    do_RSD = True
    BoxSize = 3000  #Mpc/h
    ptype = 1  #dark matter

    # do a loop over all files
    num = 0.0

    for i in range(filenum):

        # find the name of the sub-snapshot
        if filenum == 1: snapshot = snapshot_fname
        else: snapshot = snapshot_fname + '.{0:d}'.format(i)
        if fformat == 'hdf5': snapshot = snapshot + '.hdf5'

        # find the local particles in the sub-snapshot
        head = readgadget.header(snapshot)
        npart = head.npart

        if verbose:
            print('Sub-snapshot {0:d}, DM particles = {1:d} \n'.format(
                i, npart[ptype]))
        if (DEBUG > 1 and i % 100 == 0):
            print(
                'Sub-snapshot {0:d}, DM particles = {1:d}, time = {2:%H:%M:%S} \n'
                .format(i, npart[ptype], datetime.datetime.now()))

        # read positions in Mpc/h
        pos = readgadget.read_field(snapshot, "POS ", ptype)

        # read velocities in km/s
        if do_RSD:
            vel = readgadget.read_field(snapshot, "VEL ", ptype)

        # write galaxy data for each redshift bin into its own file
        fname = lightcone_path + 'galaxy_lightcone.snap{0:02d}'.format(snap)

        # open output file
        if (i == 0):
            mode = 'w'  #open file in write mode for first file in snapshot
        else:
            mode = 'r+'  #thereafter open in append mode
        fo = h5py.File(fname, mode)

        for oct in range(8):
            #relocate origin to each corner of the simulation box for each octant
            orig_x = oct % 2 * BoxSize
            orig_y = oct // 2 % 2 * BoxSize
            orig_z = oct // 4 * BoxSize

            # translate particle positions to new origin for each octant
            x = pos[::, 0] - orig_x
            y = pos[::, 1] - orig_y
            z = pos[::, 2] - orig_z

            # calculate comoving radial distance, RA and Dec
            r = np.sqrt(x * x + y * y + z * z)
            dec = np.rad2deg(np.arcsin(z / r))
            ra = np.rad2deg(np.arctan2(y, x))

            # lookup redshift corresponding to this r
            zz = d2z(r)

            if do_RSD:
                # Calculate radial velocity
                vr = np.sqrt(vel[::, 0]**2 + vel[::, 1]**2 +
                             vel[::, 2]**2) * np.sign(vel[::, 0] + vel[::, 1] +
                                                      vel[::, 2])

                # Calculate RSD factor
                # Particle velocities u in internal velocity units (corresponds to km/sec if the default choice for the system of units is adopted).
                # Peculiar velocities v are obtained by multiplying u with sqrt(a), i.e. v = u * sqrt(a). So v = u / sqrt(1+z)
                f_RSD = np.sqrt(1 + zz) * vr / z2H(zz)
            else:
                f_RSD = np.zeros(len(r))

            #Check whether particle within shell max and min
            sn = 63 - snap
            if (sn == 0):
                F = [(r <= Dc_max[sn])]
            else:
                F = [(r > Dc_max[sn - 1]) & (r <= Dc_max[sn])]
            f = tuple(F)

            # create random luminosity value for each particle
            ngal = len(pos)
            L = P2L(np.random.random(ngal) * n)

            # create dataset. Use f to filter only those galaxies within snapshot redshift boundaries
            g = np.array(list(zip(r[f], ra[f], dec[f], zz[f], f_RSD[f], L[f])),
                         dtype=gal)

            ds_name = 'octant_{0:01d}'.format(oct)
            if (DEBUG > 3): print(ds_name)

            # if filenum = 0 then create new datasets for each octant and set dataset atributes
            if (i == 0):
                gals = fo.create_dataset(
                    ds_name, data=g, dtype=gal, maxshape=(None, ), chunks=True
                )  # set maxshape = None to make resizeable and chunks = True to enable chunking
                gals.attrs['max_z'] = z_max[sn]
                if (sn == 0):
                    gals.attrs['min_z'] = 0
                else:
                    gals.attrs['min_z'] = z_max[sn - 1]
                gals.attrs['snap'] = snap
                gals.attrs['octant'] = oct
                gals.attrs['alpha'] = alpha
                gals.attrs['phi_star'] = p_star
            elif (len(g) > 0):
                gals = fo[ds_name]
                gals.resize(gals.shape[0] + len(g), axis=0)
                gals[-len(g):] = g

                # end of processing for this octant

        fo.close()
        if (DEBUG > 2):
            print(fname, " completed, time:", datetime.datetime.now())
        sys.stdout.flush()

        # compute density field.
        MASL.MA(pos, density, BoxSize, MAS)
        num += pos.shape[0]

    # All files read for snapshot
    if (DEBUG > 0): print(fname, " completed, time:", datetime.datetime.now())

    # Write density field to file
    rho_avg = np.mean(density, dtype=np.float64)
    density /= rho_avg
    density -= 1.0
    density.tofile(density_fname)
    if verbose:
        print(
            'Density delta written to file for snap {0:d}, mean density = {1:04f}'
            .format(snap, rho_avg))

    # Calculate power spectrum from density
    threads = 16

    Pk = PKL.Pk(density, BoxSize, axis, MAS, threads)
    print('Pk calculated')

    #Save power spectra	components in hdf5 file
    fname = 'powerspec_{0:03d}.npy'.format(snap)

    # open output file
    fo = h5py.File(powerspec_path + fname, 'w')

    # create datasets
    atts = fo.create_dataset(
        "attribs", dtype="f")  # empty dataset for holding snapshot attributes
    atts.attrs['z'] = redshift
    atts.attrs['Omega_m'] = Omega_m
    atts.attrs['Omega_l'] = Omega_l

    # 1D P(k)
    dset = fo.create_dataset('k1D', data=Pk.k1D)
    dset = fo.create_dataset('Pk1D', data=Pk.Pk1D)
    dset = fo.create_dataset('Nmodes1D', data=Pk.Nmodes1D)

    # 2D P(k)
    dset = fo.create_dataset('kpar', data=Pk.kpar)
    dset = fo.create_dataset('kper', data=Pk.kper)
    dset = fo.create_dataset('Pk2D', data=Pk.Pk2D)
    dset = fo.create_dataset('Nmodes2D', data=Pk.Nmodes2D)

    # 3D P(k)
    dset = fo.create_dataset('k', data=Pk.k3D)
    dset = fo.create_dataset('Pk0', data=Pk.Pk[:, 0])
    dset = fo.create_dataset('Pk2', data=Pk.Pk[:, 1])
    dset = fo.create_dataset('Pk4', data=Pk.Pk[:, 2])
    dset = fo.create_dataset('Nmodes', data=Pk.Nmodes3D)

    fo.close()

    print('Power spectrum data written to file')
Beispiel #20
0
import Pk_library as PKL
import numpy as np
import h5py

test_cube = np.load('../dat/processed/test_cube_target.npy')
pred_cube = np.load('../dat/processed/test_cube_final_prediction.npy')
benchmark_cube = np.load('../dat/processed/benchmark_cube.npy')

BoxSize = 31.82373046875  #Size of the density field in Mpc/h

axis = 0
MAS = None
threads = 32

Pk = PKL.Pk(test_cube, BoxSize, axis, MAS, threads)
k = Pk.k3D
Pk0 = Pk.Pk[:, 0]  #monopole
np.save('../dat/processed/target_k_values.npy', k)
np.save('../dat/processed/target_Pk0_values.npy', Pk0)

Pk = PKL.Pk(pred_cube, BoxSize, axis, MAS, threads)

# 3D P(k)
k = Pk.k3D
Pk0 = Pk.Pk[:, 0]  #monopole
np.save('../dat/processed/' + 'pred_k_values.npy', k)
np.save('../dat/processed/' + 'pred_Pk0_values.npy', Pk0)

Pk = PKL.Pk(benchmark_cube, BoxSize, axis, MAS, threads)
Beispiel #21
0
        #~ fid_file.close()
        #~ else :
        #~ with open(cname, 'a') as fid_file:
        #~ fid_file.write('%.8g %.8g %.8g %.8g\n' % ( np.sum(Hmass_a),np.sum(Hmass_b), np.sum(Hmass_c), np.sum(Hmass_d)))
        #~ fid_file.close()

        ###############################################################
        ######## fourth mass range
        ###############################################################

        delta1d = np.zeros((dims, dims, dims), dtype=np.float32)
        MASL.MA(pos[Hmass_ind_d], delta1d, BoxSize, MAS='CIC', W=None)
        delta1d = delta1d / np.mean(delta1d, dtype=np.float64) - 1.0

        # compute power spectra
        Pk1d = PKL.Pk(delta1d, BoxSize, axis=0, MAS='CIC',
                      threads=4)  #Pk here is a class with all power spectra

        #shot noise
        Pshot_m4 = 1 / (len(Hmass_d) / BoxSize**3)

        # 3D Pk
        k_m4 = Pk1d.k3D
        #~ Pk0_m4 = (Pk1d.Pk[:,0] + Pk2d.Pk[:,0] + Pk3d.Pk[:,0] + Pk5d.Pk[:,0] + Pk6d.Pk[:,0] + Pk7d.Pk[:,0] + Pk8d.Pk[:,0])/7 #monopole
        #~ Pk2_m4 = (Pk1d.Pk[:,1] + Pk2d.Pk[:,1] + Pk3d.Pk[:,1] + Pk5d.Pk[:,1] + Pk6d.Pk[:,1] + Pk7d.Pk[:,1] + Pk8d.Pk[:,1])/7 #quadrupole
        #~ Pk4_m4 = (Pk1d.Pk[:,2] + Pk2d.Pk[:,2] + Pk3d.Pk[:,2] + Pk5d.Pk[:,2] + Pk6d.Pk[:,2] + Pk7d.Pk[:,2] + Pk8d.Pk[:,2])/7 #hexadecapole
        #~ Nmodes_m4 = (Pk1d.Nmodes3D + Pk2d.Nmodes3D + Pk3d.Nmodes3D + Pk5d.Nmodes3D + Pk6d.Nmodes3D + Pk7d.Nmodes3D + Pk8d.Nmodes3D)/7 #number of modes in each Pk bin

        #~ temp4 = np.array([Pk1d.Pk[:,0], Pk2d.Pk[:,0], Pk3d.Pk[:,0], Pk5d.Pk[:,0], Pk6d.Pk[:,0], Pk7d.Pk[:,0], Pk8d.Pk[:,0]])
        #~ std4 = np.std(temp4, axis=0)
        cname = '/home/dvalcin/plots/Phh4_realisation_' + str(
            Mnu) + '_z=' + str(z) + '.txt'
Beispiel #22
0
def plot_power_spec(
        real_cube,  # should be inverse_transformed
        generated_cube,  # should be inverse_transformed
        raw_cube_mean,  # mean of the whole raw data cube (fields=z0.0)
        threads=1,
        MAS="CIC",
        axis=0,
        BoxSize=75.0 / 2048 * 128):
    """Takes as input;
    - Real cube: (batch_size x 1 x n x n x n) torch cuda FloatTensor,
    - Generated copy: (batch_size x 1 x n x n x n) torch cuda FloatTensor,
    - constant assignments: threads, MAS, axis, BoxSize.
    
    Returns;
    - Power spectrum plots of both cubes
    in the same figure.
    """
    print("number of samples of real and generated cubes = " +
          str(real_cube.shape[0]))

    ## Assert same type
    assert ((real_cube.type() == generated_cube.type())&(real_cube.type()=="torch.FloatTensor")),\
    "Both input cubes should be torch.FloatTensor or torch.cuda().FloatTensor. Got real_cube type " + real_cube.type() + ", generated_cube type " + generated_cube.type() +"."
    ## Assert equal dimensions
    assert (real_cube.size() == generated_cube.size()),\
    "Two input cubes must have the same size. Got real_cube size " + str(real_cube.size()) + ", generated cube size " + str(generated_cube.size())

    ## if one or both of the cubes are cuda FloatTensors, detach them
    if real_cube.type() == "torch.cuda.FloatTensor":
        ## convert cuda FloatTensor to numpy array
        real_cube = real_cube.cpu().detach().numpy()
    else:
        real_cube = real_cube.numpy()

    if generated_cube.type() == "torch.cuda.FloatTensor":
        ## convert cuda FloatTensor to numpy array
        generated_cube = generated_cube.cpu().detach().numpy()
    else:
        generated_cube = generated_cube.numpy()

    # constant assignments
    BoxSize = BoxSize
    axis = axis
    MAS = MAS
    threads = threads

    plt.figure(figsize=(10, 5))

    for cube_no in range(real.shape[0]):

        delta_real_cube = real_cube[cube_no]
        delta_gen_cube = generated_cube[cube_no]

        # CALCULATE POWER SPECTRUM OF THE REAL CUBE

        #     delta_real_cube /= np.mean(delta_real_cube,
        #                               dtype=np.float64)
        delta_real_cube /= raw_cube_mean
        delta_real_cube -= 1.0
        delta_real_cube = delta_real_cube.astype(np.float32)

        Pk_real_cube = PKL.Pk(delta_real_cube, BoxSize, axis, MAS, threads)

        # CALCULATE POWER SPECTRUM OF THE GENERATED CUBE
        #     delta_gen_cube /= np.mean(delta_gen_cube,
        #                              dtype=np.float64)
        delta_gen_cube /= raw_cube_mean
        delta_gen_cube -= 1.0
        delta_gen_cube = delta_gen_cube.astype(np.float32)

        Pk_gen_cube = PKL.Pk(delta_gen_cube, BoxSize, axis, MAS, threads)

        plt.plot(np.log(Pk_real_cube.k3D),
                 np.log(Pk_real_cube.Pk[:, 0]),
                 color="b",
                 label="original cube")
        plt.plot(np.log(Pk_gen_cube.k3D),
                 np.log(Pk_gen_cube.Pk[:, 0]),
                 color="r",
                 label="jaas")
        plt.rcParams["font.size"] = 12
        plt.title("Power Spectrum Comparison")
        plt.xlabel('log(Pk.k3D)')
        plt.ylabel('log(Pk.k3D)')
        plt.legend()

    plt.show()

    return "Power spectrum plot complete!"
Beispiel #23
0
import sys

snapshot = sys.argv[1] #'fR5_mnu016_DUSTGRAIN_snap_463'
BoxSize  = float(sys.argv[2]) #2000.0 #Mpc/h
grid     = long(sys.argv[3]) #1024
ptypes   = map(int,sys.argv[4].split(","))
MAS      = 'CIC'
do_RSD   = False
axis     = 0
threads=1

## First do the total Power Spectrum
delta = MASL.density_field_gadget(snapshot, ptypes, grid, MAS, do_RSD, axis)
delta /= np.mean(delta, dtype=np.float64);  delta -= 1.0

Pk = PKL.Pk(delta, BoxSize, axis, MAS, threads)
# 1D P(k)
k1D      = Pk.k1D
Pk1D     = Pk.Pk1D
Nmodes1D = Pk.Nmodes1D

# 2D P(k)
kpar     = Pk.kpar
kper     = Pk.kper
Pk2D     = Pk.Pk2D
Nmodes2D = Pk.Nmodes2D

# 3D P(k)
k      = Pk.k3D
Pk0    = Pk.Pk[:,0] #monopole
Pk2    = Pk.Pk[:,1] #quadrupole
Beispiel #24
0
            #~ plt.yscale('log')
            #~ plt.xscale('log')
            #~ plt.show()
            #~ plt.savefig('/home/dvalcin/plots/cumul_halo_mass_funct_at_z= '+str(z)+'.png', dpi = 500)

            ##~ ##################################################################
            #~ ########## First mass range
            #~ ##################################################################

            delta1a = np.zeros((dims, dims, dims), dtype=np.float32)
            MASL.MA(pos[Hmass_ind_a], delta1a, BoxSize, MAS='CIC', W=None)
            delta1a = delta1a / np.mean(delta1a, dtype=np.float64) - 1.0

            # compute power spectra
            Pk1a = PKL.Pk(
                delta1a, BoxSize, axis=axe, MAS='CIC',
                threads=4)  #Pk here is a class with all power spectra

            #shot noise
            Pshot_m1 = 1 / (len(Hmass_a) / BoxSize**3)

            # 3D Pk
            k_m1 = Pk1a.k3D
            #~ Pk0_m1 = (Pk1a.Pk[:,0] + Pk2a.Pk[:,0] + Pk3a.Pk[:,0] + Pk5a.Pk[:,0] + Pk6a.Pk[:,0] + Pk7a.Pk[:,0] + Pk8a.Pk[:,0])/7 #monopole
            #~ Pk2_m1 = (Pk1a.Pk[:,1] + Pk2a.Pk[:,1] + Pk3a.Pk[:,1] + Pk5a.Pk[:,1] + Pk6a.Pk[:,1] + Pk7a.Pk[:,1] + Pk8a.Pk[:,1])/7 #quadrupole
            #~ Pk4_m1 = (Pk1a.Pk[:,2] + Pk2a.Pk[:,2] + Pk3a.Pk[:,2] + Pk5a.Pk[:,2] + Pk6a.Pk[:,2] + Pk7a.Pk[:,2] + Pk8a.Pk[:,2])/7 #hexadecapole
            #~ Nmodes_m1 = (Pk1a.Nmodes3D + Pk2a.Nmodes3D + Pk3a.Nmodes3D + Pk5a.Nmodes3D + Pk6a.Nmodes3D + Pk7a.Nmodes3D + Pk8a.Nmodes3D)/7 #number of modes in each Pk bin

            #~ temp1 = np.array([Pk1a.Pk[:,0], Pk2a.Pk[:,0], Pk3a.Pk[:,0], Pk5a.Pk[:,0], Pk6a.Pk[:,0], Pk7a.Pk[:,0], Pk8a.Pk[:,0]])
            #~ std1 = np.std(temp1, axis=0)