Commit 24e430d1 authored by Rainer Weinberger's avatar Rainer Weinberger

added example cosmo_box_star_formation_3d and TREECOOL files (Puchwein et al....

added example cosmo_box_star_formation_3d and TREECOOL files (Puchwein et al. 2019MNRAS.485...47 and Faucher-Giguere et al. 2009ApJ...703.1416) in directory ./data
parent 73af73d4
This diff is collapsed.
This diff is collapsed.
......@@ -17,7 +17,7 @@ FileBase ics % Base-filename of output files
OutputDir ../ % Directory for output
GlassFile dummy_glass.dat % File with unperturbed glass or
% Cartesian grid
TileFac 4 % Number of times the glass file is
TileFac 2 % Number of times the glass file is
% tiled in each dimension (must be
% an integer)
......
#!/bin/bash # this line only there to enable syntax highlighting in this file
###################################################
# Config options for cosmo_box_star_formation_3d #
###################################################
#------------------------------------------------ mesh
REGULARIZE_MESH_CM_DRIFT # Mesh regularization; Move mesh generating point towards center of mass to make cells rounder.
REGULARIZE_MESH_CM_DRIFT_USE_SOUNDSPEED # Limit mesh regularization speed by local sound speed
REGULARIZE_MESH_FACE_ANGLE # Use maximum face angle as roundness criterion in mesh regularization
REFINEMENT_SPLIT_CELLS # Refinement
REFINEMENT_MERGE_CELLS # Derefinement
ENFORCE_JEANS_STABILITY_OF_CELLS # this imposes an adaptive floor for the temperature
#------------------------------------------------ Time integration options
TREE_BASED_TIMESTEPS # non-local timestep criterion (take 'signal speed' into account)
#------------------------------------------------ Gravity treatment
SELFGRAVITY # gravitational intraction between simulation particles/cells
HIERARCHICAL_GRAVITY # use hierarchical splitting of the time integration of the gravity
CELL_CENTER_GRAVITY # uses geometric centers to calculate gravity of cells, only possible with HIERARCHICAL_GRAVITY
ALLOW_DIRECT_SUMMATION # Performed direct summation instead of tree-based gravity if number of active particles < DIRECT_SUMMATION_THRESHOLD (= 3000 unless specified differently here)
DIRECT_SUMMATION_THRESHOLD=500 # Overrides maximum number of active particles for which direct summation is performed instead of tree based calculation
#------------------------------------------------ Gravity softening
NSOFTTYPES=2 # Number of different softening values to which particle types can be mapped.
MULTIPLE_NODE_SOFTENING # If a tree node is to be used which is softened, this is done with the softenings of its different mass components
INDIVIDUAL_GRAVITY_SOFTENING=32 # bitmask with particle types where the softenig type should be chosen with that of parttype 1 as a reference type
ADAPTIVE_HYDRO_SOFTENING # Adaptive softening of gas cells depending on their size
#------------------------------------------------ TreePM Options
PMGRID=256 # Enables particle mesh; number of cells used for grid in each dimension
RCUT=5.0 # This can be used to override the maximum radius in which the short-range tree-force is evaluated (in case the TreePM algorithm is used). The default value is 4.5, given in mesh-cells.
#------------------------------------------------ Single/Double Precision
DOUBLEPRECISION=1 # Mode of double precision: not defined: single; 1: full double precision 2: mixed, 3: mixed, fewer single precisions; unless short of memory, use 1.
DOUBLEPRECISION_FFTW # FFTW calculation in double precision
OUTPUT_COORDINATES_IN_DOUBLEPRECISION # will always output coordinates in double precision
NGB_TREE_DOUBLEPRECISION # if this is enabled, double precision is used for the neighbor node extension
#------------------------------------------------ On the fly FOF groupfinder
FOF # enable FoF output
FOF_PRIMARY_LINK_TYPES=2 # 2^type for the primary dark matter type
FOF_SECONDARY_LINK_TYPES=1+16+32 # 2^type for the types linked to nearest primaries
#------------------------------------------------ Subfind
SUBFIND # enables substructure finder
SAVE_HSML_IN_SNAPSHOT # stores hsml, density, and velocity dispersion values in the snapshot files
SUBFIND_CALC_MORE # calculates also the velocity dispersion in the local density estimate (this is automatically enabled by several other options, e.g. SAVE_HSML_IN_SNAPSHOT)
SUBFIND_EXTENDED_PROPERTIES # adds calculation of further quantities related to angular momentum in different components
#------------------------------------------------ Things for special behaviour
PROCESS_TIMES_OF_OUTPUTLIST # goes through times of output list prior to starting the simulaiton to ensure that outputs are written as close to the desired time as possible (as opposed to at next possible time if this flag is not active)
#------------------------------------------------ Output/Input options
REDUCE_FLUSH # only flush output to log-files in predefined intervals
OUTPUT_CPU_CSV # output of a cpu.csv file on top of cpu.txt
HAVE_HDF5 # needed when HDF5 I/O support is desired (recommended)
#------------------------------------------------ Testing and Debugging options
DEBUG # enables core-dumps
GENERATE_GAS_IN_ICS # Generates gas from dark matter only ICs.
#------------------------------------------------ cooling and star formation
COOLING # Simple primordial cooling
USE_SFR # Star formation model, turning dense gas into collisionless partices
This diff is collapsed.
""" @package ./examples/cosmo_box_star_formation_3d/check.py
Code that checks results of structure formation simulation
created by Rainer Weinberger, last modified 28.02.2019
"""
""" load libraries """
import sys ## system calls
import numpy as np ## load numpy
import h5py ## load h5py; needed to read snapshots
import matplotlib.pyplot as plt ## plot stuff
simulation_directory = str(sys.argv[1])
print("examples/cosmo_box_star_formation_3d/check.py: checking simulation output in directory " + simulation_directory)
""" script settings """
createReferenceSolution = False
createFigures = False
CompareToReferenceRun = True
FloatType = np.float64 # double precision: np.float64, for single use np.float32
Boxsize = 7.5 ##Mpc/h
CellsPerDimension = 32 ## 3d sim
NumberOfCells = CellsPerDimension * CellsPerDimension * CellsPerDimension
HubbleParam = 0.6774
UnitMass = 1.0e10/HubbleParam
Volume = (Boxsize/HubbleParam) * (Boxsize/HubbleParam) * (Boxsize/HubbleParam)
""" read in star formation rate output snapshot """
directory = simulation_directory+"/output/"
filename = "sfr.txt"
data = np.loadtxt(directory+filename)
if createReferenceSolution:
np.savetxt("./examples/cosmo_box_star_formation_3d/sfr_ref_L8n32_reduced.txt", data[::50,:])
scalefactor = data[:,0]
redshift_plus_one = 1.0 / data[:,0]
sfrDensity = data[:,3] / Volume
cum_mass_stars = data[:,5] * UnitMass / Volume
""" compare to reference output """
data_ref = np.loadtxt("./examples/cosmo_box_star_formation_3d/sfr_ref_L8n32_reduced.txt")
scalefactor_ref = data_ref[:,0]
redshift_plus_one_ref = 1.0 / data_ref[:,0]
cum_mass_stars_ref = data_ref[:,5]* UnitMass / Volume
scalefactor_to_probe = np.array([0.25,0.3333,0.5,0.66667,1])
delta_mass_stars = np.zeros(scalefactor_to_probe.shape)
avg_mass_stars = np.zeros(scalefactor_to_probe.shape)
if createFigures:
## figure -- dark matter and stellar positions
fig, ax = plt.subplots( 2, 2, figsize=np.array([6.9,6.9]), sharex=True, sharey=True )
fig.subplots_adjust(left = 0.09, bottom = 0.09,right = 0.98, top = 0.98, hspace=0.0, wspace=0.0)
for i, a in enumerate(scalefactor_to_probe):
delta_mass_stars[i] = np.interp(a, scalefactor, cum_mass_stars)
delta_mass_stars[i] -= np.interp(a, scalefactor_ref, cum_mass_stars_ref)
avg_mass_stars[i] = 0.5 * np.interp(a, scalefactor, cum_mass_stars)
avg_mass_stars[i] += 0.5 * np.interp(a, scalefactor_ref, cum_mass_stars_ref)
filename = "snap_%03d.hdf5" % (i)
try:
data = h5py.File(directory+filename, "r")
except:
print("could not open "+directory+filename)
sys.exit(1)
pos = np.array(data["PartType1"]["Coordinates"], dtype = FloatType) / HubbleParam / 1000.
posstars = np.array(data["PartType4"]["Coordinates"], dtype = FloatType) / HubbleParam / 1000.
if(pos.shape[0] > 32**3):
i_select = np.random.uniform(low=0.0, high=pos.shape[0], size=32**3).astype(np.int)
else:
i_select = np.arange(pos.shape[0])
## Try to show the different gas phases and their spatial distribution
z = 1./ a - 1
if i == 0:
continue
ax_col = np.int((i-1)%2)
ax_row = np.int((i-1)/2)
print('col %d, row %d'%(ax_col, ax_row))
print(ax[ax_col][ax_row])
ax[ax_row][ax_col].text(5.5,10.0,'redshift %.1f'%z)
ax[ax_row][ax_col].scatter(pos[i_select, 0], pos[i_select, 1], marker='.', s=0.01, alpha=0.5, rasterized=True)
ax[ax_row][ax_col].scatter(posstars[:, 0], posstars[:, 1], marker='*',c='r', s=0.01, alpha=1.0, rasterized=True)
ax[ax_row][ax_col].set_xlim([0,Boxsize/HubbleParam])
ax[ax_row][ax_col].set_ylim([0,Boxsize/HubbleParam])
ax[0][0].set_ylabel('[Mpc]')
ax[1][0].set_xlabel('[Mpc]')
ax[1][0].set_ylabel('[Mpc]')
ax[1][1].set_xlabel('[Mpc]')
fig.savefig(simulation_directory+'/dark_matter_and_stars_evolution.pdf', dpi=300)
""" figure of stellar mass density """
fig=plt.figure()
ax = plt.axes([0.15,0.15,0.8,0.8])
ax.plot(redshift_plus_one, cum_mass_stars, label="new")
ax.plot(redshift_plus_one_ref, cum_mass_stars_ref, label="ref")
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlim([1,11])
ax.set_xticks([1,2,3,5,9])
ax.set_xticklabels(["0", "1", "2", "4", "8"])
ax.set_xlabel(r"redshift")
ax.set_ylabel(r"Stellar mass denstiy [M$_\odot$ Mpc$^{-3}$]")
fig.savefig(simulation_directory+"/Mstar_redshift.pdf")
if CompareToReferenceRun:
""" check if deviations within tolerance """
abs_tolerance = 5e7 ## depends on box size...
if np.max( np.abs(delta_mass_stars ) ) > abs_tolerance:
print("Error: stellar mass deviaties from reference more than %g (Msun/Mpc^3): "% abs_tolerance )
print("redshifts:")
print(1./scalefactor_to_probe - 1)
print("relative deviation:")
print(delta_mass_stars / avg_mass_stars)
print("absolute deviation (1e6 Msun/Mpc^3):")
print(delta_mass_stars/1.0e6)
sys.exit(1)
""" if everything is ok """
sys.exit(0)
""" @package examples/cosmo_box_star_formation_3d/create.py
Code creates the output list; ICs need to be present already
created by Rainer Weinberger, last modified 28.02.2019
"""
""" load libraries """
import sys # system calls
import numpy as np # scientific computing package
import h5py # hdf5 format
import os # operating system interface
from subprocess import call # execute bash commands
## create new ics with 'music' or 'ngenic' or just 'copy' existing
## ones to the run directory
ic_creation='copy'
""" input """
simulation_directory = str(sys.argv[1])
print("examples/cosmo_box_star_formation_3d/create.py " + simulation_directory)
""" initial conditions: either copy or create with code """
if ic_creation == 'copy':
call(['cp', './examples/cosmo_box_star_formation_3d/L8n32/ics', simulation_directory+'/ics'])
elif ic_creation == 'music':
status = call(['hg', 'clone', 'https://bitbucket.org/ohahn/music', simulation_directory+'/music'])
if status != 0:
print('CREATE: ERROR: hg clone failed!')
sys.exit(status)
cwd = os.getcwd()
os.chdir(simulation_directory+'/music/')
status = call(['make'])
if status != 0:
print('CREATE: ERROR: make failed!')
sys.exit(status)
status = call(['./MUSIC',cwd+'/examples/cosmo_box_star_formation_3d/param_music.txt'])
if status != 0:
print('CREATE: ERROR: execution failed!')
sys.exit(status)
os.chdir(cwd)
elif ic_creation == 'ngenic':
status = call(['git', 'clone', 'https://gitlab.mpcdf.mpg.de/ext-c2c74fbfcdff/ngenic.git', simulation_directory+'/ngenic'])
if status != 0:
print('CREATE: ERROR: git clone failed!')
sys.exit(status)
cwd = os.getcwd()
os.chdir(simulation_directory+'/ngenic/')
status = call(['make'])
if status != 0:
print('CREATE: ERROR: make failed!')
sys.exit(status)
status = call(['mpiexec','-np','1','./N-GenIC',cwd+'/examples/cosmo_box_star_formation_3d/param_ngenic.txt'])
if status != 0:
print('CREATE: ERROR: execution failed!')
sys.exit(status)
os.chdir(cwd)
else:
print("CREATE: ERROR: no valid option for ic creation! choose 'copy', 'music' or 'ngenic'")
exit(1)
""" set output times """
outputTimes = np.array([0.2,0.25,0.33,0.5,0.66,1], dtype=np.float64)
ones = np.ones(outputTimes.shape, dtype=np.int)
""" write output list file """
data = np.array([outputTimes, ones]).T
np.savetxt(simulation_directory+"/output_list.txt",data, fmt="%g %1.f" )
""" normal exit """
sys.exit(0)
%% parameters for cosmo_box_star_formation_3d
%---- Relevant files
InitCondFile run/examples/cosmo_box_star_formation_3d/ics
OutputDir run/examples/cosmo_box_star_formation_3d/output
SnapshotFileBase snap
OutputListFilename run/examples/cosmo_box_star_formation_3d/output_list.txt
%---- File formats
ICFormat 1
SnapFormat 3
%---- CPU-time limits
TimeLimitCPU 90000
CpuTimeBetRestartFile 12000
FlushCpuTimeDiff 120
ResubmitOn 0
ResubmitCommand my-scriptfile
%----- Memory alloction
MaxMemSize 2500
%---- Caracteristics of run
TimeBegin 0.0078125 % Begin of the simulation; z=127
TimeMax 1.0 % End of the simulation z=0
%---- Basic code options that set the type of simulation
ComovingIntegrationOn 1
PeriodicBoundariesOn 1
CoolingOn 1
StarformationOn 1
%---- Cosmological parameters (Planck cosmology)
Omega0 0.3089
OmegaLambda 0.6911
OmegaBaryon 0.0486
HubbleParam 0.6774
BoxSize 7500.0
%---- Output frequency and output parameters
OutputListOn 1
TimeBetSnapshot 0.0
TimeOfFirstSnapshot 0.0
TimeBetStatistics 0.01
NumFilesPerSnapshot 1
NumFilesWrittenInParallel 1
%---- Accuracy of time integration
TypeOfTimestepCriterion 0
ErrTolIntAccuracy 0.012
CourantFac 0.3
MaxSizeTimestep 0.005
MinSizeTimestep 1.0e-9
%---- Treatment of empty space and temperature limits
InitGasTemp 244.8095
MinGasTemp 5.0
MinimumDensityOnStartUp 1.0e-20
LimitUBelowThisDensity 0.0
LimitUBelowCertainDensityToThisValue 0.0
MinEgySpec 0.0
%---- Tree algorithm, force accuracy, domain update frequency
TypeOfOpeningCriterion 1
ErrTolTheta 0.7
ErrTolForceAcc 0.0025
MultipleDomains 8
TopNodeFactor 2.5
ActivePartFracForNewDomainDecomp 0.01
%---- Initial density estimate
DesNumNgb 64
MaxNumNgbDeviation 4
%---- System of units
UnitLength_in_cm 3.085678e21 % 1.0 kpc
UnitMass_in_g 1.989e43 % 1.0e10 solar masses
UnitVelocity_in_cm_per_s 1e5 % 1 km/sec
GravityConstantInternal 0
%---- Gravitational softening lengths
SofteningComovingType0 6.0
SofteningComovingType1 6.0
SofteningMaxPhysType0 3.0
SofteningMaxPhysType1 3.0
GasSoftFactor 2.5
SofteningTypeOfPartType0 0
SofteningTypeOfPartType1 1
SofteningTypeOfPartType2 1
SofteningTypeOfPartType3 1
SofteningTypeOfPartType4 1
SofteningTypeOfPartType5 1
MinimumComovingHydroSoftening 0.25
AdaptiveHydroSofteningSpacing 1.2
%----- Mesh regularization options
CellShapingSpeed 0.5
CellMaxAngleFactor 2.25
ReferenceGasPartMass 0
TargetGasMassFactor 1
RefinementCriterion 1
DerefinementCriterion 1
%----- Subfind
ErrTolThetaSubfind 0.7
DesLinkNgb 20
%---- Parameters for star formation model
CritPhysDensity 0 % critical physical density for star formation (in cm^(-3))
MaxSfrTimescale 2.27 % in internal time units
CritOverDensity 57.7 % overdensity threshold value
TempSupernova 5.73e7 % in Kelvin
TempClouds 1000.0 % in Kelvin
FactorEVP 573.0
TemperatureThresh 1e+06
FactorSN 0.1
TreecoolFile ./data/TREECOOL_ep
[setup]
boxlength = 7.5
zstart = 127
levelmin = 5
levelmin_TF = 5
levelmax = 5
padding = 8
overlap = 4
ref_center = 0.5, 0.5, 0.5
ref_extent = 0.4, 0.4, 0.4
align_top = no
baryons = no
use_2LPT = no
use_LLA = no
periodic_TF = yes
[cosmology]
Omega_m = 0.3089
Omega_L = 0.6911
w0 = -1.0
wa = 0.0
Omega_b = 0.0486
H0 = 67.74
sigma_8 = 0.831
nspec = 0.9645
transfer = eisenstein
[random]
seed[7] = 12345
seed[8] = 23456
seed[9] = 34567
seed[10] = 45678
seed[11] = 56789
seed[12] = 67890
[output]
#Gadget-2 (type=1: high-res particles, type=5: rest)
format = gadget2
filename = ../ics
gadget_coarsetype = 2
gadget_usekpc = yes
[poisson]
fft_fine = yes
accuracy = 1e-5
pre_smooth = 3
post_smooth = 3
smoother = gs
laplace_order = 6
grad_order = 6
Nmesh 128 % This is the size of the FFT grid used to
% compute the displacement field. One
% should have Nmesh >= Nsample.
Nsample 128 % sets the maximum k that the code uses,
% i.e. this effectively determines the
% Nyquist frequency that the code assumes,
% k_Nyquist = 2*PI/Box * Nsample/2
% Normally, one chooses Nsample such that
% Ntot = Nsample^3, where Ntot is the
% total number of particles
Box 7500.0 % Periodic box size of simulation
FileBase ics % Base-filename of output files
OutputDir ../ % Directory for output
GlassFile dummy_glass.dat % File with unperturbed glass or
% Cartesian grid
TileFac 2 % Number of times the glass file is
% tiled in each dimension (must be
% an integer)
Omega 0.3089 % Total matter density (at z=0)
OmegaLambda 0.6911 % Cosmological constant (at z=0)
OmegaBaryon 0.0 % Baryon density (at z=0)
HubbleParam 0.6774 % Hubble paramater (may be used for power spec parameterization)
Redshift 127 % Starting redshift
Sigma8 0.831 % power spectrum normalization
SphereMode 1 % if "1" only modes with |k| < k_Nyquist are
% used (i.e. a sphere in k-space), otherwise modes with
% |k_x|,|k_y|,|k_z| < k_Nyquist are used
% (i.e. a cube in k-space)
WhichSpectrum 1 % "1" selects Eisenstein & Hu spectrum,
% "2" selects a tabulated power spectrum in
% the file 'FileWithInputSpectrum'
% otherwise, Efstathiou parametrization is used
FileWithInputSpectrum input_spectrum.txt % filename of tabulated input
% spectrum (if used)
InputSpectrum_UnitLength_in_cm 3.085678e24 % defines length unit of tabulated
% input spectrum in cm/h.
% Note: This can be chosen different from UnitLength_in_cm
ReNormalizeInputSpectrum 1 % if set to zero, the
% tabulated spectrum is
% assumed to be normalized
% already in its amplitude to
% the starting redshift,
% otherwise this is recomputed
% based on the specified sigma8
ShapeGamma 0.21 % only needed for Efstathiou power spectrum
PrimordialIndex 0.9645 % may be used to tilt the primordial index,
% primordial spectrum is k^PrimordialIndex
Seed 123456 % seed for IC-generator
NumFilesWrittenInParallel 1 % limits the number of files that are
% written in parallel when outputting
UnitLength_in_cm 3.085678e21 % defines length unit of output (in cm/h)
UnitMass_in_g 1.989e43 % defines mass unit of output (in g/cm)
UnitVelocity_in_cm_per_s 1e5 % defines velocity unit of output (in cm/sec)
This diff is collapsed.
......@@ -24,6 +24,7 @@ TESTS+="yee_2d "
## available 3d examples
TESTS+="noh_3d "
TESTS+="cosmo_box_gravity_only_3d "
TESTS+="cosmo_box_star_formation_3d "
## loop over all tests
for TEST in $TESTS
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment