Page MenuHomec4science

No OneTemporary

File Metadata

Created
Fri, Sep 27, 21:23
This document is not UTF8. It was detected as ISO-8859-1 (Latin 1) and converted to UTF8 for display.
diff --git a/Gadget2 b/Gadget2
index 2773014..361a8b6 100755
Binary files a/Gadget2 and b/Gadget2 differ
diff --git a/Makefile b/Makefile
index 1167ff8..bbf4712 100644
--- a/Makefile
+++ b/Makefile
@@ -1,866 +1,868 @@
#----------------------------------------------------------------------
# From the list below, please activate/deactivate the options that
# apply to your run. If you modify any of these options, make sure
# that you recompile the whole code by typing "make clean; make".
#
# Look at end of file for a brief guide to the compile-time options.
#----------------------------------------------------------------------
#--------------------------------------- Basic operation mode of code
#OPT += -DPERIODIC
OPT += -DUNEQUALSOFTENINGS
#--------------------------------------- Things that are always recommended
OPT += -DPEANOHILBERT
OPT += -DWALLCLOCK
#--------------------------------------- TreePM Options
#OPT += -DPMGRID=128
#OPT += -DPLACEHIGHRESREGION=3
#OPT += -DENLARGEREGION=1.2
#OPT += -DASMTH=1.25
#OPT += -DRCUT=4.5
#--------------------------------------- Single/Double Precision
#OPT += -DDOUBLEPRECISION
#OPT += -DDOUBLEPRECISION_FFTW
#--------------------------------------- Time integration options
OPT += -DSYNCHRONIZATION
#OPT += -DFLEXSTEPS
#OPT += -DPSEUDOSYMMETRIC
OPT += -DNOSTOP_WHEN_BELOW_MINTIMESTEP
#OPT += -DNOPMSTEPADJUSTMENT
#--------------------------------------- Output
OPT += -DADVANCEDSTATISTICS
OPT += -DADVANCEDCPUSTATISTICS
OPT += -DSYSTEMSTATISTICS
OPT += -DBLOCK_SKIPPING
#OPT += -DHAVE_HDF5
#OPT += -DOUTPUTPOTENTIAL
#OPT += -DOUTPUTACCELERATION
#OPT += -DOUTPUTCHANGEOFENTROPY
#OPT += -DOUTPUTTIMESTEP
#OPT += -DOUTPUTERADSTICKY
#OPT += -DOUTPUTERADFEEDBACK
#OPT += -DOUTPUTENERGYFLUX
#OPT += -DOUTPUTOPTVAR
OPT += -DOUTPUTSTELLAR_PROP
#--------------------------------------- Things for special behaviour
#OPT += -DNOGRAVITY
#OPT += -DNOTREERND
#OPT += -DNOTYPEPREFIX_FFTW
#OPT += -DLONG_X=60
#OPT += -DLONG_Y=5
#OPT += -DLONG_Z=0.2
#OPT += -DTWODIMS
#OPT += -DSPH_BND_PARTICLES
#OPT += -DNOVISCOSITYLIMITER
OPT += -DCOMPUTE_POTENTIAL_ENERGY
#OPT += -DLONGIDS
#OPT += -DISOTHERM_EQS
#OPT += -DADAPTIVE_GRAVSOFT_FORGAS
#OPT += -DSELECTIVE_NO_GRAVITY=2+4+8+16
#OPT += -DAVOIDNUMNGBPROBLEM
#OPT += -DLIMIT_DVEL=1.0
#OPT += -DOTHERINFO
#OPT += -DDOMAIN_AT_ORIGIN
OPT += -DNO_NEGATIVE_PRESSURE
#OPT += -DCOMPUTE_VELOCITY_DISPERSION
#OPT += -DCYLINDRICAL_SYMMETRY
OPT += -DWRITE_ALL_MASSES
OPT += -DENTROPYPRED
OPT += -DCOUNT_ACTIVE_PARTICLES
OPT += -DRANDOMSEED_AS_PARAMETER
OPT += -DDETAILED_CPU
OPT += -DDETAILED_CPU_GRAVITY
OPT += -DDETAILED_CPU_DOMAIN
OPT += -DDETAILED_OUTPUT_IN_GRAVTREE
#OPT += -DSPLIT_DOMAIN_USING_TIME
OPT += -DCOSMICTIME
OPT += -DONLY_MASTER_READ_EWALD
#OPT += -DPNBODY
#OPT += -DPNBODY_OUTPUT_POS
#OPT += -DPNBODY_OUTPUT_VEL
#OPT += -DPNBODY_OUTPUT_NUM
#OPT += -DPNBODY_OUTPUT_MASS
#OPT += -DPNBODY_OUTPUT_TYPE
#OPT += -DPNBODY_OUTPUT_ENERGY
#OPT += -DPNBODY_OUTPUT_DENSITY
#OPT += -DPNBODY_OUTPUT_HSML
#OPT += -DPNBODY_OUTPUT_METALS
#--------------------------------------- Physical processes
OPT += -DCOOLING
#OPT += -DIMPLICIT_COOLING_INTEGRATION
#OPT += -DDO_NO_USE_HYDROGEN_MASSFRAC_IN_COOLING
#OPT += -DHEATING
#OPT += -DHEATING_PE # photo-electric heating
OPT += -DSFR
OPT += -DCOMPUTE_SFR_ENERGY
OPT += -DSFR_NEG_DIV_ONLY
OPT += -DSTELLAR_PROP
OPT += -DCHIMIE # need stellar prop
OPT += -DCHIMIE_THERMAL_FEEDBACK
OPT += -DCHIMIE_COMPUTE_THERMAL_FEEDBACK_ENERGY
#OPT += -DCHIMIE_KINETIC_FEEDBACK
#OPT += -DCHIMIE_COMPUTE_KINETIC_FEEDBACK_ENERGY
OPT += -DCHIMIE_EXTRAHEADER
+OPT += -DCHIMIE_INPUT_ALL
+
#OPT += -DFEEDBACK
#OPT += -DFEEDBACK_WIND
#--------------------------------------- multiphase
#OPT += -DMULTIPHASE
#OPT += -DNO_HYDRO_FOR_GAS # do not use hydro routine (at all)
#OPT += -DNO_DENSITY_FOR_STICKY # do not compute density in sticky (need to be done in sfr)
#OPT += -DPHASE_MIXING # need MULTIPHASE : enable phase mixing
#OPT += -DCOLDGAS_CYCLE # need MULTIPHASE and PHASE_MIXING
#OPT += -DEXTERNAL_FLUX
#OPT += -DSTELLAR_FLUX
#OPT += -DCOUNT_COLLISIONS # count sticky collisions
#--------------------------------------- Outer potential
#OPT += -DOUTERPOTENTIAL
#OPT += -DNFW
#OPT += -DPISOTHERM
#OPT += -DPLUMMER
OPT += -DMIYAMOTONAGAI
#OPT += -DCORIOLIS
#--------------------------------------- Testing and Debugging options
#OPT += -DFORCETEST=0.1
#OPT += -DWITH_ID_IN_HYDRA
#OPT += -DPARTICLE_FLAG
#OPT += -DOUTPUT_EVERY_TIMESTEP
#OPT += -DOUTPUT_COOLING_FUNCTION
OPT += -DCHECK_BLOCK_ORDER
OPT += -DCHECK_ENTROPY_SIGN
OPT += -DCHECK_TYPE_DURING_IO
OPT += -DCHECK_ID_CORRESPONDENCE
#--------------------------------------- Glass making
#OPT += -DMAKEGLASS=262144
#--------------------------------------- Agn
#OPT += -DBUBBLES
#OPT += -DAGN_ACCRETION
#OPT += -DAGN_FEEDBACK
#OPT += -DAGN_USE_ANGULAR_MOMENTUM
#OPT += -DAGN_HEATING
#OPT += -DBONDI_ACCRETION
#OPT += -DUSE_BONDI_POWER
#----------------------------------------------------------------------
# Here, select compile environment for the target machine. This may need
# adjustment, depending on your local system. Follow the examples to add
# additional target platforms, and to get things properly compiled.
#----------------------------------------------------------------------
#--------------------------------------- Select some defaults
CC = mpicc # sets the C-compiler
OPTIMIZE = -O2 -Wall -g # sets optimization and warning flags
MPICHLIB = -lmpich
#--------------------------------------- Select target computer
SYSTYPE="obscalc"
#SYSTYPE="callisto-intel"
#SYSTYPE="bg1"
#SYSTYPE="obsds"
#SYSTYPE="leo_openmpi"
#SYSTYPE="leo_mpich2shm"
#SYSTYPE="graphor0"
#SYSTYPE="obsrevaz"
#SYSTYPE="regor_openmpigcc"
#SYSTYPE="regor_mvapich2gcc"
#SYSTYPE="meso_mpich2"
#SYSTYPE="meso"
#SYSTYPE="revaz/local"
#SYSTYPE="revaz/local_mpich2"
#SYSTYPE="horizon3_mpich1"
#SYSTYPE="horizon3_mpich2"
#SYSTYPE="horizon3"
#SYSTYPE="LUXOR"
#SYSTYPE="MPA"
#SYSTYPE="Mako"
#SYSTYPE="Regatta"
#SYSTYPE="RZG_LinuxCluster"
#SYSTYPE="RZG_LinuxCluster-gcc"
#SYSTYPE="OpteronMPA"
#SYSTYPE="OPA-Cluster32"
#SYSTYPE="OPA-Cluster64"
#--------------------------------------- Adjust settings for target computer
# module add openmpi-x86_64
ifeq ($(SYSTYPE),"obscalc")
CC = mpicc
OPTIMIZE =
GSL_INCL =
GSL_LIBS =
FFTW_INCL=
FFTW_LIBS=
MPICHLIB =
HDF5INCL =
HDF5LIB =
NO_FFTW_LIB = "yes"
PY_INCL = -I/usr/include/python2.6/
PY_LIB = -lpython2.6
endif
ifeq ($(SYSTYPE),"callisto-intel")
CC = mpicc
OPTIMIZE =
GSL_INCL = -I/u1/yrevaz/local/gsl-intel/include
GSL_LIBS = -L/u1/yrevaz/local/gsl-intel/lib
FFTW_INCL= -I/u1/yrevaz/local/fftw-2.1.5-intel/include
FFTW_LIBS= -L/u1/yrevaz/local/fftw-2.1.5-intel/lib
MPICHLIB =
HDF5INCL =
HDF5LIB =
endif
ifeq ($(SYSTYPE),"bg1")
CC = mpicc
OPTIMIZE = -O3 -Wall -g
GSL_INCL = -I/home/yrevaz/local/include
GSL_LIBS = -L/home/yrevaz/local/lib
FFTW_INCL=
FFTW_LIBS=
MPICHLIB =
HDF5INCL =
HDF5LIB =
NO_FFTW_LIB = "yes"
endif
ifeq ($(SYSTYPE),"obsds")
CC = mpicc
OPTIMIZE = -O3 -Wall -g
GSL_INCL =
GSL_LIBS =
FFTW_INCL=
FFTW_LIBS=
MPICHLIB =
HDF5INCL =
HDF5LIB =
NO_FFTW_LIB = "yes"
endif
ifeq ($(SYSTYPE),"graphor0")
CC = mpicc
OPTIMIZE = -O3 -Wall -g
GSL_INCL = -I/home/epfl/revaz/local/include
GSL_LIBS = -L/home/epfl/revaz/local/lib
FFTW_INCL= -I/home/epfl/revaz/local/include
FFTW_LIBS= -L/home/epfl/revaz/local/lib
MPICHLIB = -L/home/epfl/revaz/local/openmpi/lib -lmpi
HDF5INCL =
HDF5LIB =
endif
ifeq ($(SYSTYPE),"obsrevaz")
CC = mpicc
OPTIMIZE = -O3 -Wall -fpack-struct
GSL_INCL =
GSL_LIBS =
FFTW_INCL= -I/home/revaz/local/include/
FFTW_LIBS= -L/home/revaz/local/lib/
MPICHLIB = -lmpi
HDF5INCL =
HDF5LIB =
endif
ifeq ($(SYSTYPE),"regor_openmpigcc")
CC = mpicc
OPTIMIZE = -O3 -Wall -fpack-struct
GSL_INCL = -I/usr/include
GSL_LIBS = -L/usr/lib64/
FFTW_INCL= -I/home/revaz/local_mvapich2gcc/include/
FFTW_LIBS= -L/home/revaz/local_mvapich2gcc/lib/
MPICHLIB = -lmpi
HDF5INCL =
HDF5LIB =
OPT += -DMESOMACHINE
endif
ifeq ($(SYSTYPE),"regor_mpich2")
CC = mpicc
OPTIMIZE = -O3 -Wall -fpack-struct
GSL_INCL = -I/usr/include
GSL_LIBS = -L/usr/lib64/
FFTW_INCL= -I/home/revaz/local_mvapich2gcc/include/
FFTW_LIBS= -L/home/revaz/local_mvapich2gcc/lib/
MPICHLIB = -L/home/revaz/local/mpich2-1.0.6nemesis/lib/ -lmpich
HDF5INCL =
HDF5LIB =
OPT += -DMESOMACHINE
endif
ifeq ($(SYSTYPE),"regor_mvapich2gcc")
CC = mpicc
OPTIMIZE = -O3 -Wall -fpack-struct
GSL_INCL = -I/usr/include
GSL_LIBS = -L/usr/lib64/
FFTW_INCL= -I/home/revaz/local_mvapich2gcc/include/
FFTW_LIBS= -L/home/revaz/local_mvapich2gcc/lib/
MPICHLIB = -L/cvos/shared/apps/ofed/1.2.5.3/mpi/gcc/mvapich2-0.9.8-15/lib/ -lmpich
HDF5INCL =
HDF5LIB =
OPT += -DMESOMACHINE
endif
ifeq ($(SYSTYPE),"leo_openmpi")
CC = mpicc
OPTIMIZE = -O3 -Wall -fpack-struct
GSL_INCL = -I/export/revaz/local/include
GSL_LIBS = -L/export/revaz/local/lib
FFTW_INCL= -I/export/revaz/local/include
FFTW_LIBS= -L/export/revaz/local/lib
MPICHLIB = -L/usr/local/mpich2-pgi/lib -lmpi
HDF5INCL =
HDF5LIB =
endif
ifeq ($(SYSTYPE),"leo_mpich2shm")
CC = mpicc
OPTIMIZE = -O3 -Wall -g -fpack-struct
GSL_INCL = -I/export/revaz/local/include
GSL_LIBS = -L/export/revaz/local/lib
FFTW_INCL= -I/export/revaz/local/include
FFTW_LIBS= -L/export/revaz/local/lib
MPICHLIB = -L/usr/local/mpich2-pgi/lib -lmpich
HDF5INCL =
HDF5LIB =
endif
ifeq ($(SYSTYPE),"meso_mpich2")
CC = mpicc
OPTIMIZE = -O3 -Wall -g -fpack-struct
GSL_INCL = -I/home/revaz/local/include
GSL_LIBS = -L/home/revaz/local/lib
FFTW_INCL= -I/horizon1/x86_64_sl4/fftw/2.1.5/include/
FFTW_LIBS= -L/horizon1/x86_64_sl4/fftw/2.1.5/lib/
MPICHLIB = -L/home/revaz/local/mpich2-1.0.3/lib -lmpich
HDF5INCL =
HDF5LIB =
endif
ifeq ($(SYSTYPE),"meso")
CC = mpicc
OPTIMIZE = -O3 -g
GSL_INCL =
GSL_LIBS =
FFTW_INCL= -I/horizon1/x86_64_sl4/fftw/2.1.5/include/
FFTW_LIBS= -L/horizon1/x86_64_sl4/fftw/2.1.5/lib/
MPICHLIB =
HDF5INCL =
HDF5LIB =
OPT += -DMESOMACHINE
endif
ifeq ($(SYSTYPE),"revaz/local")
CC = mpicc
OPTIMIZE = -O3 -Wall -g
GSL_INCL = -I/home/revaz/local/include
GSL_LIBS = -L/home/revaz/local/lib
FFTW_INCL= -I/home/revaz/local/include
FFTW_LIBS= -L/home/revaz/local/lib
MPICHLIB = -L/home/revaz/local/mpich-1.2.5/ch_p4/lib -lmpich
HDF5INCL =
HDF5LIB =
endif
ifeq ($(SYSTYPE),"revaz/local_mpich2")
CC = mpicc
OPTIMIZE = -O3 -Wall -g
GSL_INCL = -I/home/revaz/local/include
GSL_LIBS = -L/home/revaz/local/lib
FFTW_INCL= -I/home/revaz/local/include
FFTW_LIBS= -L/home/revaz/local/lib
MPICHLIB = -L/home/revaz/local/mpich2-1.0.3/lib/ -lmpich
HDF5INCL =
HDF5LIB =
endif
ifeq ($(SYSTYPE),"LUXOR")
CC = mpicc
OPTIMIZE = -O3 -Wall -g
#GSL_INCL = -I/home/revaz/local/include
#GSL_LIBS = -L/home/revaz/local/lib
#FFTW_INCL= -I/home/revaz/local/include
#FFTW_LIBS= -L/home/revaz/local/lib
MPICHLIB = -L/home/revaz/local/mpich-1.2.7/ch_p4/lib -lmpich
HDF5INCL =
HDF5LIB =
endif
ifeq ($(SYSTYPE),"horizon3")
CC = mpicc
OPTIMIZE = -O3 -Wall -g -fpack-struct
GSL_INCL = -I/home/revaz/local/include
GSL_LIBS = -L/home/revaz/local/lib
FFTW_INCL= -I/home/revaz/local/include
FFTW_LIBS= -L/home/revaz/local/lib
MPICHLIB = -llam
HDF5INCL =
HDF5LIB =
endif
ifeq ($(SYSTYPE),"horizon3_mpich1")
CC = mpicc
OPTIMIZE = -O3 -Wall -g -fpack-struct
GSL_INCL = -I/home/revaz/local/include
GSL_LIBS = -L/home/revaz/local/lib
FFTW_INCL= -I/home/revaz/local/include
FFTW_LIBS= -L/home/revaz/local/lib
MPICHLIB = -L/home/revaz/local/mpich-1.2.7/lib -lmpich
HDF5INCL =
HDF5LIB =
endif
ifeq ($(SYSTYPE),"horizon3_mpich2")
CC = mpicc
OPTIMIZE = -O3 -Wall -g -fpack-struct
GSL_INCL = -I/home/revaz/local/include
GSL_LIBS = -L/home/revaz/local/lib
FFTW_INCL= -I/home/revaz/local/include
FFTW_LIBS= -L/home/revaz/local/lib
MPICHLIB = -L/usr/local/mpich2-pgi/lib -lmpich
HDF5INCL =
HDF5LIB =
endif
ifeq ($(SYSTYPE),"MPA")
CC = mpicc
OPTIMIZE = -O3 -Wall
GSL_INCL = -I/usr/common/pdsoft/include
GSL_LIBS = -L/usr/common/pdsoft/lib -Wl,"-R /usr/common/pdsoft/lib"
FFTW_INCL=
FFTW_LIBS=
MPICHLIB =
HDF5INCL =
HDF5LIB = -lhdf5 -lz
endif
ifeq ($(SYSTYPE),"OpteronMPA")
CC = mpicc
OPTIMIZE = -O3 -Wall -m64
GSL_INCL = -L/usr/local/include
GSL_LIBS = -L/usr/local/lib
FFTW_INCL=
FFTW_LIBS=
MPICHLIB =
HDF5INCL = -I/opt/hdf5/include
HDF5LIB = -L/opt/hdf5/lib -lhdf5 -lz -Wl,"-R /opt/hdf5/lib"
endif
ifeq ($(SYSTYPE),"OPA-Cluster32")
CC = mpicc
OPTIMIZE = -O3 -Wall
GSL_INCL = -I/afs/rzg/bc-b/vrs/opteron32/include
GSL_LIBS = -L/afs/rzg/bc-b/vrs/opteron32/lib -Wl,"-R /afs/rzg/bc-b/vrs/opteron32/lib"
FFTW_INCL= -I/afs/rzg/bc-b/vrs/opteron32/include
FFTW_LIBS= -L/afs/rzg/bc-b/vrs/opteron32/lib
MPICHLIB =
HDF5INCL =
HDF5LIB = -lhdf5 -lz
endif
ifeq ($(SYSTYPE),"OPA-Cluster64")
CC = mpicc
OPTIMIZE = -O3 -Wall -m64
GSL_INCL = -I/afs/rzg/bc-b/vrs/opteron64/include
GSL_LIBS = -L/afs/rzg/bc-b/vrs/opteron64/lib -Wl,"-R /afs/rzg/bc-b/vrs/opteron64/lib"
FFTW_INCL= -I/afs/rzg/bc-b/vrs/opteron64/include
FFTW_LIBS= -L/afs/rzg/bc-b/vrs/opteron64/lib
MPICHLIB =
HDF5INCL =
HDF5LIB = -lhdf5 -lz
endif
ifeq ($(SYSTYPE),"Mako")
CC = mpicc # sets the C-compiler
OPTIMIZE = -O3 -march=athlon-mp -mfpmath=sse
GSL_INCL =
GSL_LIBS =
FFTW_INCL=
FFTW_LIBS=
MPICHLIB =
HDF5INCL =
HDF5LIB = -lhdf5 -lz
endif
ifeq ($(SYSTYPE),"Regatta")
CC = mpcc_r
OPTIMIZE = -O5 -qstrict -qipa -q64
GSL_INCL = -I/afs/rzg/u/vrs/gsl_psi64/include
GSL_LIBS = -L/afs/rzg/u/vrs/gsl_psi64/lib
FFTW_INCL= -I/afs/rzg/u/vrs/fftw_psi64/include
FFTW_LIBS= -L/afs/rzg/u/vrs/fftw_psi64/lib -q64 -qipa
MPICHLIB =
HDF5INCL = -I/afs/rzg/u/vrs/hdf5_psi64/include
HDF5LIB = -L/afs/rzg/u/vrs/hdf5_psi64/lib -lhdf5 -lz
endif
ifeq ($(SYSTYPE),"RZG_LinuxCluster")
CC = mpicci
OPTIMIZE = -O3 -ip # Note: Don't use the "-rcd" optimization of Intel's compiler! (causes code crashes)
GSL_INCL = -I/afs/rzg/u/vrs/gsl_linux/include
GSL_LIBS = -L/afs/rzg/u/vrs/gsl_linux/lib -Wl,"-R /afs/rzg/u/vrs/gsl_linux/lib"
FFTW_INCL= -I/afs/rzg/u/vrs/fftw_linux/include
FFTW_LIBS= -L/afs/rzg/u/vrs/fftw_linux/lib
HDF5INCL = -I/afs/rzg/u/vrs/hdf5_linux/include
HDF5LIB = -L/afs/rzg/u/vrs/hdf5_linux/lib -lhdf5 -lz -Wl,"-R /afs/rzg/u/vrs/hdf5_linux/lib"
endif
ifeq ($(SYSTYPE),"RZG_LinuxCluster-gcc")
CC = mpiccg
OPTIMIZE = -Wall -g -O3 -march=pentium4
GSL_INCL = -I/afs/rzg/u/vrs/gsl_linux_gcc3.2/include
GSL_LIBS = -L/afs/rzg/u/vrs/gsl_linux_gcc3.2/lib -Wl,"-R /afs/rzg/u/vrs/gsl_linux_gcc3.2/lib"
FFTW_INCL= -I/afs/rzg/u/vrs/fftw_linux_gcc3.2/include
FFTW_LIBS= -L/afs/rzg/u/vrs/fftw_linux_gcc3.2/lib
HDF5INCL = -I/afs/rzg/u/vrs/hdf5_linux/include
HDF5LIB = -L/afs/rzg/u/vrs/hdf5_linux/lib -lhdf5 -lz -Wl,"-R /afs/rzg/u/vrs/hdf5_linux/lib"
endif
ifneq (HAVE_HDF5,$(findstring HAVE_HDF5,$(OPT)))
HDF5INCL =
HDF5LIB =
endif
OPTIONS = $(OPTIMIZE) $(OPT)
EXEC = Gadget2
OBJS = main.o run.o predict.o begrun.o endrun.o global.o \
timestep.o init.o restart.o io.o \
accel.o read_ic.o ngb.o \
system.o allocate.o density.o \
gravtree.o hydra.o driftfac.o \
domain.o allvars.o potential.o \
forcetree.o peano.o gravtree_forcetest.o \
pm_periodic.o pm_nonperiodic.o longrange.o \
cooling.o agn_heating.o phase.o sticky.o outerpotential.o starformation.o \
agn_feedback.o bubbles.o bondi_accretion.o chimie.o stars_density.o cosmictime.o pnbody.o
INCL = allvars.h proto.h tags.h Makefile
CFLAGS = $(OPTIONS) $(GSL_INCL) $(FFTW_INCL) $(HDF5INCL) $(PY_INCL)
ifeq (NOTYPEPREFIX_FFTW,$(findstring NOTYPEPREFIX_FFTW,$(OPT))) # fftw installed with type prefix?
FFTW_LIB = $(FFTW_LIBS) -lrfftw_mpi -lfftw_mpi -lrfftw -lfftw
else
ifeq (DOUBLEPRECISION_FFTW,$(findstring DOUBLEPRECISION_FFTW,$(OPT)))
FFTW_LIB = $(FFTW_LIBS) -ldrfftw_mpi -ldfftw_mpi -ldrfftw -ldfftw
else
FFTW_LIB = $(FFTW_LIBS) -lsrfftw_mpi -lsfftw_mpi -lsrfftw -lsfftw
endif
endif
ifeq ($(NO_FFTW_LIB),"yes")
FFTW_LIB =
endif
LIBS = $(HDF5LIB) -g $(MPICHLIB) $(GSL_LIBS) -lgsl -lgslcblas -lm $(FFTW_LIB) $(PY_LIB)
$(EXEC): $(OBJS)
$(CC) $(OBJS) $(LIBS) -o $(EXEC)
$(OBJS): $(INCL)
clean:
rm -f $(OBJS) $(EXEC)
#-----------------------------------------------------------------------
#
# Brief guide to compile-time options of the code. More information
# can be found in the code documentation.
#
# - PERIODIC:
# Set this if you want to have periodic boundary conditions.
#
# - UNEQUALSOFTENINGS:
# Set this if you use particles with different gravitational
# softening lengths.
#
# - PEANOHILBERT:
# This is a tuning option. When set, the code will bring the
# particles after each domain decomposition into Peano-Hilbert
# order. This improves cache utilization and performance.
#
# - WALLCLOCK:
# If set, a wallclock timer is used by the code to measure internal
# time consumption (see cpu-log file). Otherwise, a timer that
# measures consumed processor ticks is used.
#
# - PMGRID:
# This enables the TreePM method, i.e. the long-range force is
# computed with a PM-algorithm, and the short range force with the
# tree. The parameter has to be set to the size of the mesh that
# should be used, (e.g. 64, 96, 128, etc). The mesh dimensions need
# not necessarily be a power of two. Note: If the simulation is
# not in a periodic box, then a FFT method for vacuum boundaries is
# employed, using an actual mesh with dimension twice(!) that
# specified by PMGRID.
#
# - PLACEHIGHRESREGION:
# If this option is set (will only work together with PMGRID), then
# the long range force is computed in two stages: One Fourier-grid
# is used to cover the whole simulation volume, allowing the
# computation of the longe-range force. A second Fourier mesh is
# placed on the region occupied by "high-resolution" particles,
# allowing the computation of an intermediate scale force. Finally,
# the force on short scales is computed with the tree. This
# procedure can be useful for "zoom-simulations", provided the
# majority of particles (the high-res particles) are occupying only
# a small fraction of the volume. To activate this option, the
# parameter needs to be set to an integer bit mask that encodes the
# particle types that make up the high-res particles.
# For example, if types 0, 1, and 4 form the high-res
# particles, set the parameter to PLACEHIGHRESREGION=19, because
# 2^0 + 2^1 + 2^4 = 19. The spatial region covered by the high-res
# grid is determined automatically from the initial conditions.
# Note: If a periodic box is used, the high-res zone may not intersect
# the box boundaries.
#
# - ENLARGEREGION:
# The spatial region covered by the high-res zone has a fixed size
# during the simulation, which initially is set to the smallest
# region that encompasses all high-res particles. Normally, the
# simulation will be interrupted if high-res particles leave this
# region in the course of the run. However, by setting this
# parameter to a value larger than one, the size of the high-res
# region can be expanded, providing a buffer region. For example,
# setting it to 1.4 will enlarge its side-length by 40% (it remains
# centered on the high-res particles). Hence, with this setting, the
# high-res region may expand or move by a limited amount.
# Note: If SYNCHRONIZATION is activated, the code will be able to
# continue even if high-res particles leave the initial high-res
# grid. In this case, the code will update the size and position of
# the grid that is placed onto the high-resolution region
# automatically. To prevent that this potentially happens every
# single PM step, one should nevertheless assign a value slightly
# larger than 1 to ENLARGEREGION.
#
# - ASMTH:
# This can be used to override the value assumed for the scale that
# defines the long-range/short-range force-split in the TreePM
# algorithm. The default value is 1.25, in mesh-cells.
#
# - RCUT:
# 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.
#
# - DOUBLEPRECISION:
# This makes the code store and compute internal particle data in
# double precision. Note that output files are nevertheless written
# by converting the particle data to single precision.
#
# - DDOUBLEPRECISION_FFTW:
# If this is set, the code will use the double-precision version of
# FTTW, provided the latter has been explicitly installed with a
# "d" prefix, and NOTYPEPREFIX_FFTW is not set. Otherwise the
# single precision version ("s" prefix) is used.
#
# - SYNCHRONIZATION:
# When this is set, particles are kept in a binary hierarchy of
# timesteps and may only increase their timestep if the new
# timestep will put them into synchronization with the higher time
# level.
#
# - FLEXSTEPS:
# This is an alternative to SYNCHRONIZATION. Particle timesteps are
# here allowed to be integer multiples of the minimum timestep that
# occurs among the particles, which in turn is rounded down to the
# nearest power-of-two devision of the total simulated
# timespan. This option distributes particles more evenly over
# individual system timesteps, particularly once a simulation has
# run for a while, and may then result in a reduction of work-load
# imbalance losses.
#
# - PSEUDOSYMMETRIC:
# When this option is set, the code will try to "anticipate"
# timestep changes by extrapolating the change of the acceleration
# into the future. This can in certain idealized cases improve the
# long-term integration behaviour of periodic orbits, but should
# make little or no difference in most real-world applications. May
# only be used together with SYNCHRONIZATION.
#
# - NOSTOP_WHEN_BELOW_MINTIMESTEP:
# If this is activated, the code will not terminate when the
# timestep falls below the value of MinSizeTimestep specified in
# the parameterfile. This is useful for runs where one wants to
# enforce a constant timestep for all particles. This can be done
# by activating this option, and by setting MinSizeTimestep and
# MaxSizeTimestep to an equal value.
#
# - NOPMSTEPADJUSTMENT:
# When this is set, the long-range timestep for the PM-force
# computation (when the TreePM algorithm is used) is always
# determined by MaxSizeTimeStep. Otherwise, it is determined by
# the MaxRMSDisplacement parameter, or MaxSizeTimeStep, whichever
# gives the smaller step.
#
# - HAVE_HDF5:
# If this is set, the code will be compiled with support for input
# and output in the HDF5 format. You need to have the HDF5
# libraries and headers installed on your computer for this option
# to work. The HDF5 format can then be selected as format "3" in
# Gadget's parameterfile.
#
# - OUTPUTPOTENTIAL:
# This will make the code compute gravitational potentials for
# all particles each time a snapshot file is generated. The values
# are then included in the snapshot file. Note that the computation
# of the values of the gravitational potential costs additional CPU.
#
# - OUTPUTACCELERATION:
# This will include the physical acceleration of each particle in
# snapshot files.
#
# - OUTPUTCHANGEOFENTROPY:
# This will include the rate of change of entropy of gas particles
# in snapshot files.
#
# - OUTPUTTIMESTEP:
# This will include the current timesteps of all particles in the
# snapshot files.
#
# - NOGRAVITY
# This switches off gravity. Useful only for pure SPH simulations
# in non-expanding space.
#
# - NOTREERND:
# If this is not set, the tree construction will succeed even when
# there are a few particles at identical locations. This is done by
# `rerouting' particles once the node-size has fallen below 1.0e-3
# of the softening length. When this option is activated, this will
# be surpressed and the tree construction will always fail if there
# are particles at extremely close coordinates.
#
# - NOTYPEPREFIX_FFTW:
# This is an option that signals that FFTW has been compiled
# without the type-prefix option, i.e. no leading "d" or "s"
# characters are used to access the library.
#
# - LONG_X/Y/Z:
# These options can be used together with PERIODIC and NOGRAVITY only.
# When set, the options define numerical factors that can be used to
# distorts the periodic simulation cube into a parallelepiped of
# arbitrary aspect ratio. This can be useful for idealized SPH tests.
#
# - TWODIMS:
# This effectively switches of one dimension in SPH, i.e. the code
# follows only 2d hydrodynamics in the xy-, yz-, or xz-plane. This
# only works with NOGRAVITY, and if all coordinates of the third
# axis are exactly equal. Can be useful for idealized SPH tests.
#
# - SPH_BND_PARTICLES:
# If this is set, particles with a particle-ID equal to zero do not
# receive any SPH acceleration. This can be useful for idealized
# SPH tests, where these particles represent fixed "walls".
#
# - NOVISCOSITYLIMITER:
# If this is set, the code will not try to put an upper limit on
# the viscous force in case an implausibly high pair-wise viscous
# force (which may lead to a particle 'reflection' in case of poor
# timestepping) should arise. Note: For proper settings of the
# timestep parameters, this situation should not arise.
#
# - COMPUTE_POTENTIAL_ENERGY:
# When this option is set, the code will compute the gravitational
# potential energy each time a global statistics is computed. This
# can be useful for testing global energy conservation.
#
# - LONGIDS:
# If this is set, the code assumes that particle-IDs are stored as
# 64-bit long integers. This is only really needed if you want to
# go beyond ~2 billion particles.
#
# - ISOTHERM_EQS:
# This special option makes the gas behave like an isothermal gas
# with equation of state P = cs^2 * rho. The sound-speed cs is set by
# the thermal energy per unit mass in the intial conditions,
# i.e. cs^2=u. If the value for u is zero, then the initial gas
# temperature in the parameter file is used to define the sound speed
# according to cs^2 = 3/2 kT/mp, where mp is the proton mass.
#
# - ADAPTIVE_GRAVSOFT_FORGAS:
# When this option is set, the gravitational softening lengths used for
# gas particles is tied to their SPH smoothing length. This can be useful
# for dissipative collapse simulations. The option requires the setting
# of UNEQUALSOFTENINGS.
#
# - SELECTIVE_NO_GRAVITY:
# This can be used for special computations where one wants to
# exclude certain particle types from receiving gravitational
# forces. The particle types that are excluded in this fashion are
# specified by a bit mask, in the same as for the PLACEHIGHRESREGION
# option.
#
# - FORCETEST:
# This can be set to check the force accuracy of the code. The
# option needs to be set to a number between 0 and 1 (e.g. 0.01),
# which is taken to specify a random fraction of particles for
# which at each timestep forces by direct summation are
# computed. The normal tree-forces and the correct direct
# summation forces are collected in a file. Note that the
# simulation itself is unaffected by this option, but it will of
# course run much(!) slower, especially if
# FORCETEST*NumPart*NumPart >> NumPart. Note: Particle IDs must
# be set to numbers >=1 for this to work.
#
# - MAKEGLASS
# This option can be used to generate a glass-like particle
# configuration. The value assigned gives the particle load,
# which is initially generated as a Poisson sample and then
# evolved towards a glass with the sign of gravity reversed.
#
#-----------------------------------------------------------------------
diff --git a/allvars.h b/allvars.h
index 235aebc..6b09174 100644
--- a/allvars.h
+++ b/allvars.h
@@ -1,1640 +1,1640 @@
/*! \file allvars.h
* \brief declares global variables.
*
* This file declares all global variables. Further variables should be added here, and declared as
* 'extern'. The actual existence of these variables is provided by the file 'allvars.c'. To produce
* 'allvars.c' from 'allvars.h', do the following:
*
* - Erase all #define's, typedef's, and enum's
* - add #include "allvars.h", delete the #ifndef ALLVARS_H conditional
* - delete all keywords 'extern'
* - delete all struct definitions enclosed in {...}, e.g.
* "extern struct global_data_all_processes {....} All;"
* becomes "struct global_data_all_processes All;"
*/
#ifndef ALLVARS_H
#define ALLVARS_H
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_integration.h>
#include "tags.h"
#define GADGETVERSION "2.0" /*!< code version string */
#define TIMEBASE (1<<28) /*!< The simulated timespan is mapped onto the integer interval [0,TIMESPAN],
* where TIMESPAN needs to be a power of 2. Note that (1<<28) corresponds to 2^29
*/
#define MAXTOPNODES 200000 /*!< Maximum number of nodes in the top-level tree used for domain decomposition */
typedef long long peanokey; /*!< defines the variable type used for Peano-Hilbert keys */
#define BITS_PER_DIMENSION 18 /*!< Bits per dimension available for Peano-Hilbert order.
Note: If peanokey is defined as type int, the allowed maximum is 10.
If 64-bit integers are used, the maximum is 21 */
#define PEANOCELLS (((peanokey)1)<<(3*BITS_PER_DIMENSION)) /*!< The number of different Peano-Hilbert cells */
#define RNDTABLE 3000 /*!< gives the length of a table with random numbers, refreshed at every timestep.
This is used to allow application of random numbers to a specific particle
in a way that is independent of the number of processors used. */
#define MAX_REAL_NUMBER 1e37
#define MIN_REAL_NUMBER 1e-37
#define MAXLEN_FILENAME 100 /*!< Maximum number of characters for filenames (including the full path) */
#ifdef ISOTHERM_EQS
#define GAMMA (1.0) /*!< index for isothermal gas */
#else
#define GAMMA (5.0/3) /*!< adiabatic index of simulated gas */
#endif
#define GAMMA_MINUS1 (GAMMA-1)
#define HYDROGEN_MASSFRAC 0.76 /*!< mass fraction of hydrogen, relevant only for radiative cooling */
/* Some physical constants in cgs units */
#define GRAVITY 6.672e-8 /*!< Gravitational constant (in cgs units) */
#define SOLAR_MASS 1.989e33
#define SOLAR_LUM 3.826e33
#define RAD_CONST 7.565e-15
#define AVOGADRO 6.0222e23
#define BOLTZMANN 1.3806e-16
#define GAS_CONST 8.31425e7
#define C 2.9979e10
#define PLANCK 6.6262e-27
#define CM_PER_MPC 3.085678e24
#define PROTONMASS 1.6726e-24
#define ELECTRONMASS 9.10953e-28
#define THOMPSON 6.65245e-25
#define ELECTRONCHARGE 4.8032e-10
#define HUBBLE 3.2407789e-18 /* in h/sec */
#define YEAR_IN_SECOND 31536000.0 /* year in sec */
#define FEH_SOLAR 0.00181 /* used only if cooling with metal is on and chimie is off */
#define PI 3.1415926535897931
#define TWOPI 6.2831853071795862
/* Some conversion factors */
#define SEC_PER_MEGAYEAR 3.155e13
#define SEC_PER_YEAR 3.155e7
#ifndef ASMTH
#define ASMTH 1.25 /*!< ASMTH gives the scale of the short-range/long-range force split in units of FFT-mesh cells */
#endif
#ifndef RCUT
#define RCUT 4.5 /*!< RCUT gives the maximum distance (in units of the scale used for the force split) out to
which short-range forces are evaluated in the short-range tree walk. */
#endif
#define MAX_NGB 20000 /*!< defines maximum length of neighbour list */
#define MAXLEN_OUTPUTLIST 500 /*!< maxmimum number of entries in list of snapshot output times */
#define DRIFT_TABLE_LENGTH 1000 /*!< length of the lookup table used to hold the drift and kick factors */
#ifdef COSMICTIME
#define COSMICTIME_TABLE_LENGTH 1000 /*!< length of the lookup table used for the cosmic time computation */
#endif
#define MAXITER 1000 /*!< maxmimum number of steps for SPH neighbour iteration */
#ifdef DOUBLEPRECISION /*!< If defined, the variable type FLOAT is set to "double", otherwise to FLOAT */
#define FLOAT double
#else
#define FLOAT float
#endif
#ifndef TWODIMS
#define NUMDIMS 3 /*!< For 3D-normalized kernel */
#define KERNEL_COEFF_1 2.546479089470 /*!< Coefficients for SPH spline kernel and its derivative */
#define KERNEL_COEFF_2 15.278874536822
#define KERNEL_COEFF_3 45.836623610466
#define KERNEL_COEFF_4 30.557749073644
#define KERNEL_COEFF_5 5.092958178941
#define KERNEL_COEFF_6 (-15.278874536822)
#define NORM_COEFF 4.188790204786 /*!< Coefficient for kernel normalization. Note: 4.0/3 * PI = 4.188790204786 */
#else
#define NUMDIMS 2 /*!< For 2D-normalized kernel */
#define KERNEL_COEFF_1 (5.0/7*2.546479089470) /*!< Coefficients for SPH spline kernel and its derivative */
#define KERNEL_COEFF_2 (5.0/7*15.278874536822)
#define KERNEL_COEFF_3 (5.0/7*45.836623610466)
#define KERNEL_COEFF_4 (5.0/7*30.557749073644)
#define KERNEL_COEFF_5 (5.0/7*5.092958178941)
#define KERNEL_COEFF_6 (5.0/7*(-15.278874536822))
#define NORM_COEFF M_PI /*!< Coefficient for kernel normalization. */
#endif
#ifdef MULTIPHASE
#define GAS_SPH 0
#define GAS_STICKY 1
#define GAS_DARK 2
#endif
#if defined(SFR) || defined(STELLAR_PROP)
#define ST 1
#endif
#ifdef CHIMIE
-#define NELEMENTS 5
+#define NELEMENTS 4
#define MAXNELEMENTS 64
#define FIRST_ELEMENT "Fe"
#define FE 0
#endif
#ifdef COOLING
#define COOLING_NMETALICITIES 9
#define COOLING_NTEMPERATURES 171
#endif
#ifdef COMPUTE_VELOCITY_DISPERSION
#define VELOCITY_DISPERSION_SIZE 3
#endif
extern int SetMinTimeStepForActives;
extern int ThisTask; /*!< the rank of the local processor */
extern int NTask; /*!< number of processors */
extern int PTask; /*!< smallest integer such that NTask <= 2^PTask */
extern int NumPart; /*!< number of particles on the LOCAL processor */
extern int N_gas; /*!< number of gas particles on the LOCAL processor */
#if defined(SFR) || defined(STELLAR_PROP)
extern int N_stars; /*!< number of stars particle on the LOCAL processor */
#endif
#ifdef MULTIPHASE
extern int N_sph;
extern int N_sticky;
extern int N_stickyflaged;
extern int N_dark;
extern int NumColPotLocal; /*!< local number of potentially collisional particles */
extern int NumColPot; /*!< total number of potentially collisional particles */
extern int NumColLocal; /*!< local number of collisions */
extern int NumCol; /*!< total number of collisions */
extern int NumNoColLocal;
extern int NumNoCol;
#endif
extern long long Ntype[6]; /*!< total number of particles of each type */
extern int NtypeLocal[6]; /*!< local number of particles of each type */
extern int NumForceUpdate; /*!< number of active particles on local processor in current timestep */
extern int NumSphUpdate; /*!< number of active SPH particles on local processor in current timestep */
#ifdef CHIMIE
extern int NumStUpdate;
#endif
extern double CPUThisRun; /*!< Sums the CPU time for the process (current submission only) */
#ifdef SPLIT_DOMAIN_USING_TIME
extern double CPU_Gravity;
#endif
extern int RestartFlag; /*!< taken from command line used to start code. 0 is normal start-up from
initial conditions, 1 is resuming a run from a set of restart files, while 2
marks a restart from a snapshot file. */
extern char *Exportflag; /*!< Buffer used for flagging whether a particle needs to be exported to another process */
extern int *Ngblist; /*!< Buffer to hold indices of neighbours retrieved by the neighbour search routines */
extern int TreeReconstructFlag; /*!< Signals that a new tree needs to be constructed */
#ifdef SFR
extern int RearrangeParticlesFlag;/*!< Signals that particles must be rearanged */
#endif
extern int Flag_FullStep; /*!< This flag signals that the current step involves all particles */
extern gsl_rng *random_generator; /*!< the employed random number generator of the GSL library */
extern double RndTable[RNDTABLE]; /*!< Hold a table with random numbers, refreshed every timestep */
#ifdef SFR
extern double StarFormationRndTable[RNDTABLE]; /*!< Hold a table with random numbers, refreshed every timestep */
#endif
#ifdef FEEDBACK_WIND
extern double FeedbackWindRndTable[RNDTABLE]; /*!< Hold a table with random numbers, refreshed every timestep */
#endif
#ifdef CHIMIE
extern double ChimieRndTable[RNDTABLE]; /*!< Hold a table with random numbers, refreshed every timestep */
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
extern double ChimieKineticFeedbackRndTable[RNDTABLE]; /*!< Hold a table with random numbers, refreshed every timestep */
#endif
extern double DomainCorner[3]; /*!< gives the lower left corner of simulation volume */
extern double DomainCenter[3]; /*!< gives the center of simulation volume */
extern double DomainLen; /*!< gives the (maximum) side-length of simulation volume */
extern double DomainFac; /*!< factor used for converting particle coordinates to a Peano-Hilbert mesh covering the simulation volume */
extern int DomainMyStart; /*!< first domain mesh cell that resides on the local processor */
extern int DomainMyLast; /*!< last domain mesh cell that resides on the local processor */
extern int *DomainStartList; /*!< a table that lists the first domain mesh cell for all processors */
extern int *DomainEndList; /*!< a table that lists the last domain mesh cell for all processors */
extern double *DomainWork; /*!< a table that gives the total "work" due to the particles stored by each processor */
extern int *DomainCount; /*!< a table that gives the total number of particles held by each processor */
extern int *DomainCountSph; /*!< a table that gives the total number of SPH particles held by each processor */
extern int *DomainTask; /*!< this table gives for each leaf of the top-level tree the processor it was assigned to */
extern int *DomainNodeIndex; /*!< this table gives for each leaf of the top-level tree the corresponding node of the gravitational tree */
extern FLOAT *DomainTreeNodeLen; /*!< this table gives for each leaf of the top-level tree the side-length of the corresponding node of the gravitational tree */
extern FLOAT *DomainHmax; /*!< this table gives for each leaf of the top-level tree the maximum SPH smoothing length among the particles of the corresponding node of the gravitational tree */
extern struct DomainNODE
{
FLOAT s[3]; /*!< center-of-mass coordinates */
FLOAT vs[3]; /*!< center-of-mass velocities */
FLOAT mass; /*!< mass of node */
#ifdef STELLAR_FLUX
FLOAT starlum; /*!< star luminosity of node */
#endif
#ifdef UNEQUALSOFTENINGS
#ifndef ADAPTIVE_GRAVSOFT_FORGAS
int bitflags; /*!< this bit-field encodes the particle type with the largest softening among the particles of the nodes, and whether there are particles with different softening in the node */
#else
FLOAT maxsoft; /*!< hold the maximum gravitational softening of particles in the
node if the ADAPTIVE_GRAVSOFT_FORGAS option is selected */
#endif
#endif
}
*DomainMoment; /*!< this table stores for each node of the top-level tree corresponding node data from the gravitational tree */
extern peanokey *DomainKeyBuf; /*!< this points to a buffer used during the exchange of particle data */
extern peanokey *Key; /*!< a table used for storing Peano-Hilbert keys for particles */
extern peanokey *KeySorted; /*!< holds a sorted table of Peano-Hilbert keys for all particles, used to construct top-level tree */
extern int NTopnodes; /*!< total number of nodes in top-level tree */
extern int NTopleaves; /*!< number of leaves in top-level tree. Each leaf can be assigned to a different processor */
extern struct topnode_data
{
int Daughter; /*!< index of first daughter cell (out of 8) of top-level node */
int Pstart; /*!< for the present top-level node, this gives the index of the first node in the concatenated list of topnodes collected from all processors */
int Blocks; /*!< for the present top-level node, this gives the number of corresponding nodes in the concatenated list of topnodes collected from all processors */
int Leaf; /*!< if the node is a leaf, this gives its number when all leaves are traversed in Peano-Hilbert order */
peanokey Size; /*!< number of Peano-Hilbert mesh-cells represented by top-level node */
peanokey StartKey; /*!< first Peano-Hilbert key in top-level node */
long long Count; /*!< counts the number of particles in this top-level node */
}
*TopNodes; /*!< points to the root node of the top-level tree */
extern double TimeOfLastTreeConstruction; /*!< holds what it says, only used in connection with FORCETEST */
/* variables for input/output, usually only used on process 0 */
extern char ParameterFile[MAXLEN_FILENAME]; /*!< file name of parameterfile used for starting the simulation */
extern FILE *FdInfo; /*!< file handle for info.txt log-file. */
extern FILE *FdLog; /*!< file handle for log.txt log-file. */
extern FILE *FdEnergy; /*!< file handle for energy.txt log-file. */
#ifdef SYSTEMSTATISTICS
extern FILE *FdSystem;
#endif
extern FILE *FdTimings; /*!< file handle for timings.txt log-file. */
extern FILE *FdCPU; /*!< file handle for cpu.txt log-file. */
#ifdef FORCETEST
extern FILE *FdForceTest; /*!< file handle for forcetest.txt log-file. */
#endif
#ifdef SFR
extern FILE *FdSfr; /*!< file handle for sfr.txt log-file. */
#endif
#ifdef CHIMIE
extern FILE *FdChimie; /*!< file handle for chimie log-file. */
#endif
#ifdef MULTIPHASE
extern FILE *FdPhase; /*!< file handle for pase.txt log-file. */
extern FILE *FdSticky; /*!< file handle for sticky.txt log-file. */
#endif
#ifdef AGN_ACCRETION
extern FILE *FdAccretion; /*!< file handle for accretion.txt log-file. */
#endif
#ifdef BONDI_ACCRETION
extern FILE *FdBondi; /*!< file handle for bondi.txt log-file. */
#endif
#ifdef BUBBLES
extern FILE *FdBubble; /*!< file handle for bubble.txt log-file. */
#endif
extern double DriftTable[DRIFT_TABLE_LENGTH]; /*!< table for the cosmological drift factors */
extern double GravKickTable[DRIFT_TABLE_LENGTH]; /*!< table for the cosmological kick factor for gravitational forces */
extern double HydroKickTable[DRIFT_TABLE_LENGTH]; /*!< table for the cosmological kick factor for hydrodynmical forces */
#ifdef COSMICTIME
extern double CosmicTimeTable[COSMICTIME_TABLE_LENGTH]; /*!< table for the computation of cosmic time */
#endif
extern void *CommBuffer; /*!< points to communication buffer, which is used in the domain decomposition, the
parallel tree-force computation, the SPH routines, etc. */
/*! This structure contains data which is the SAME for all tasks (mostly code parameters read from the
* parameter file). Holding this data in a structure is convenient for writing/reading the restart file, and
* it allows the introduction of new global variables in a simple way. The only thing to do is to introduce
* them into this structure.
*/
extern struct global_data_all_processes
{
long long TotNumPart; /*!< total particle numbers (global value) */
long long TotN_gas; /*!< total gas particle number (global value) */
#if defined(SFR) || defined(STELLAR_PROP)
long long TotN_stars; /*!< total stars particle number (global value) */
#endif
#ifdef MULTIPHASE
long long TotN_sph; /*!< total sph particle number (global value) */
long long TotN_sticky; /*!< total sticky particle number (global value) */
long long TotN_stickyflaged; /*!< total sticky flaged particle number (global value) */
long long TotN_stickyactive; /*!< total sticky active particle number (global value) */
long long TotN_dark; /*!< total dark particle number (global value) */
#endif
int MaxPart; /*!< This gives the maxmimum number of particles that can be stored on one processor. */
int MaxPartSph; /*!< This gives the maxmimum number of SPH particles that can be stored on one processor. */
#ifdef STELLAR_PROP
int MaxPartStars; /*!< This gives the maxmimum number of Star particles that can be stored on one processor. */
#endif
double BoxSize; /*!< Boxsize in case periodic boundary conditions are used */
int ICFormat; /*!< selects different versions of IC file-format */
int SnapFormat; /*!< selects different versions of snapshot file-formats */
int NumFilesPerSnapshot; /*!< number of files in multi-file snapshot dumps */
int NumFilesWrittenInParallel;/*!< maximum number of files that may be written simultaneously when
writing/reading restart-files, or when writing snapshot files */
int BufferSize; /*!< size of communication buffer in MB */
int BunchSizeForce; /*!< number of particles fitting into the buffer in the parallel tree-force algorithm */
int BunchSizeDensity; /*!< number of particles fitting into the communication buffer in the density computation */
int BunchSizeHydro; /*!< number of particles fitting into the communication buffer in the SPH hydrodynamical force computation */
int BunchSizeDomain; /*!< number of particles fitting into the communication buffer in the domain decomposition */
#ifdef MULTIPHASE
int BunchSizeSticky; /*!< number of particles fitting into the communication buffer in the Chimie computation */
#endif
#ifdef CHIMIE
int BunchSizeChimie; /*!< number of particles fitting into the communication buffer in the Chimie computation */
int BunchSizeStarsDensity; /*!< number of particles fitting into the communication buffer in the star density computation */
#endif
double PartAllocFactor; /*!< in order to maintain work-load balance, the particle load will usually
NOT be balanced. Each processor allocates memory for PartAllocFactor times
the average number of particles to allow for that */
double TreeAllocFactor; /*!< Each processor allocates a number of nodes which is TreeAllocFactor times
the maximum(!) number of particles. Note: A typical local tree for N
particles needs usually about ~0.65*N nodes. */
#ifdef SFR
double StarsAllocFactor; /*!< Estimated fraction of gas particles that will form stars during the simulation
This allow to reduce the memory stored for stellar particles */
#endif
/* some SPH parameters */
double DesNumNgb; /*!< Desired number of SPH neighbours */
double MaxNumNgbDeviation; /*!< Maximum allowed deviation neighbour number */
double ArtBulkViscConst; /*!< Sets the parameter \f$\alpha\f$ of the artificial viscosity */
double InitGasTemp; /*!< may be used to set the temperature in the IC's */
double MinGasTemp; /*!< may be used to set a floor for the gas temperature */
double MinEgySpec; /*!< the minimum allowed temperature expressed as energy per unit mass */
/* Usefull constants */
double Boltzmann;
double ProtonMass;
double mumh;
#ifdef COOLING
/* Cooling parameters */
double *logT;
double *logL;
gsl_interp_accel *acc_cooling_spline;
gsl_spline *cooling_spline;
double CoolingType;
char CoolingFile[MAXLEN_FILENAME]; /*!< cooling file */
double CutofCoolingTemperature;
double InitGasMetallicity;
/*
new metal dependent cooling
*/
double CoolingParameters_zmin;
double CoolingParameters_zmax;
double CoolingParameters_slz;
double CoolingParameters_tmin;
double CoolingParameters_tmax;
double CoolingParameters_slt;
double CoolingParameters_FeHSolar;
double CoolingParameters_cooling_data_max;
double CoolingParameters_cooling_data[COOLING_NMETALICITIES][COOLING_NTEMPERATURES];
int CoolingParameters_p;
int CoolingParameters_q;
#endif
#ifdef CHIMIE
int ChimieNumberOfParameterFiles;
char ChimieParameterFile[MAXLEN_FILENAME]; /*!< chimie parameter file */
double ChimieSupernovaEnergy;
double ChimieKineticFeedbackFraction;
double ChimieWindSpeed;
double ChimieWindTime;
double ChimieThermalTime;
double ChimieMaxSizeTimestep;
#endif
#if !defined (HEATING_PE)
double HeatingPeElectronFraction;
#endif
#if !defined (HEATING_PE) || defined (STELLAR_FLUX) || defined (EXTERNAL_FLUX)
double HeatingPeSolarEnergyDensity;
#endif
#if !defined (HEATING_PE) || defined (STELLAR_FLUX)
double HeatingPeLMRatioGas;
double HeatingPeLMRatioHalo;
double HeatingPeLMRatioDisk;
double HeatingPeLMRatioBulge;
double HeatingPeLMRatioStars;
double HeatingPeLMRatioBndry;
double HeatingPeLMRatio[6];
#endif
#ifdef EXTERNAL_FLUX
double HeatingExternalFLuxEnergyDensity;
#endif
#ifdef MULTIPHASE
double CriticalTemperature;
double CriticalEgySpec;
double CriticalNonCollisionalTemperature;
double CriticalNonCollisionalEgySpec;
#ifdef COLDGAS_CYCLE
double ColdGasCycleTransitionTime;
double ColdGasCycleTransitionParameter;
#endif
#endif
#ifdef MULTIPHASE
/* some STICKY parameters */
int StickyUseGridForCollisions;
double StickyTime; /*!< Cooling time of sticky particle collision */
double StickyCollisionTime;
double StickyLastCollisionTime;
double StickyIdleTime;
double StickyMinVelocity;
double StickyMaxVelocity;
int StickyGridNx;
int StickyGridNy;
int StickyGridNz;
double StickyGridXmin;
double StickyGridXmax;
double StickyGridYmin;
double StickyGridYmax;
double StickyGridZmin;
double StickyGridZmax;
double StickyLambda;
double StickyDensity;
double StickyDensityPower;
double StickyBetaR;
double StickyBetaT;
double StickyRsphFact; /*!< Fraction of the sph radius used in sticky particle */
#endif
#ifdef OUTERPOTENTIAL
#ifdef NFW
double HaloConcentration;
double HaloMass;
double GasMassFraction;
double NFWPotentialCte;
double Rs;
#endif
#ifdef PLUMMER
double PlummerMass;
double PlummerSoftenning;
double PlummerPotentialCte;
#endif
#ifdef MIYAMOTONAGAI
double MiyamotoNagaiMass;
double MiyamotoNagaiHr;
double MiyamotoNagaiHz;
double MiyamotoNagaiPotentialCte;
#endif
#ifdef PISOTHERM
double Rho0;
double Rc;
double PisothermPotentialCte;
double GasMassFraction;
double PotentialInf;
gsl_function PotentialF;
gsl_integration_workspace *Potentialw;
#endif
#ifdef CORIOLIS
double CoriolisOmegaX;
double CoriolisOmegaY;
double CoriolisOmegaZ;
double CoriolisOmegaX0;
double CoriolisOmegaY0;
double CoriolisOmegaZ0;
#endif
#endif
#ifdef SFR
int StarFormationNStarsFromGas;
double StarFormationStarMass;
double StarFormationMgMsFraction;
int StarFormationType;
double StarFormationCstar;
double StarFormationTime;
double StarFormationDensity;
double StarFormationTemperature;
double ThresholdDensity;
#endif
#ifdef FEEDBACK
double SupernovaTime;
#endif
#ifdef FEEDBACK_WIND
double SupernovaWindEgySpecPerMassUnit;
double SupernovaWindFractionInEgyKin;
double SupernovaWindParameter;
double SupernovaWindSpeed;
double SupernovaWindIntAccuracy;
#endif
#ifdef AGN_ACCRETION
double TimeBetAccretion;
double AccretionRadius;
double AGNFactor;
double MinMTotInRa;
double TimeLastAccretion;
double LastMTotInRa;
double MTotInRa;
double dMTotInRa;
#endif
#ifdef BUBBLES
char BubblesInitFile[MAXLEN_FILENAME]; /*!< bubble file */
double *BubblesTime;
double *BubblesD;
double *BubblesR;
double *BubblesE;
double *BubblesA;
double *BubblesB;
int BubblesIndex;
double BubblesAlpha;
double BubblesBeta;
double BubblesDelta;
double BubblesRadiusFactor;
double EnergyBubbles;
#endif
#ifdef AGN_HEATING
double AGNHeatingPower;
double AGNHeatingRmax;
#endif
#ifdef BONDI_ACCRETION
double BondiEfficiency;
double BondiBlackHoleMass;
double BondiHsmlFactor;
double BondiPower;
double BondiTimeBet;
double BondiTimeLast;
#endif
#if defined (AGN_ACCRETION) || defined (BONDI_ACCRETION)
double LightSpeed;
#endif
/* some force counters */
long long TotNumOfForces; /*!< counts total number of force computations */
long long NumForcesSinceLastDomainDecomp; /*!< count particle updates since last domain decomposition */
/* system of units */
double G; /*!< Gravity-constant in internal units */
double UnitTime_in_s; /*!< factor to convert internal time unit to seconds/h */
double UnitMass_in_g; /*!< factor to convert internal mass unit to grams/h */
double UnitVelocity_in_cm_per_s; /*!< factor to convert intqernal velocity unit to cm/sec */
double UnitLength_in_cm; /*!< factor to convert internal length unit to cm/h */
double UnitPressure_in_cgs; /*!< factor to convert internal pressure unit to cgs units (little 'h' still around!) */
double UnitDensity_in_cgs; /*!< factor to convert internal length unit to g/cm^3*h^2 */
double UnitCoolingRate_in_cgs; /*!< factor to convert internal cooling rate to cgs units */
double UnitEnergy_in_cgs; /*!< factor to convert internal energy to cgs units */
double UnitTime_in_Megayears; /*!< factor to convert internal time to megayears/h */
double GravityConstantInternal; /*!< If set to zero in the parameterfile, the internal value of the
gravitational constant is set to the Newtonian value based on the system of
units specified. Otherwise the value provided is taken as internal gravity constant G. */
/* Cosmological parameters */
double Hubble; /*!< Hubble-constant in internal units */
double Omega0; /*!< matter density in units of the critical density (at z=0)*/
double OmegaLambda; /*!< vaccum energy density relative to crictical density (at z=0) */
double OmegaBaryon; /*!< baryon density in units of the critical density (at z=0)*/
double HubbleParam; /*!< little `h', i.e. Hubble constant in units of 100 km/s/Mpc. Only needed to get absolute physical values for cooling physics */
/* Code options */
int ComovingIntegrationOn; /*!< flags that comoving integration is enabled */
int PeriodicBoundariesOn; /*!< flags that periodic boundaries are enabled */
int ResubmitOn; /*!< flags that automatic resubmission of job to queue system is enabled */
int TypeOfOpeningCriterion; /*!< determines tree cell-opening criterion: 0 for Barnes-Hut, 1 for relative criterion */
int TypeOfTimestepCriterion; /*!< gives type of timestep criterion (only 0 supported right now - unlike gadget-1.1) */
int OutputListOn; /*!< flags that output times are listed in a specified file */
/* Parameters determining output frequency */
int SnapshotFileCount; /*!< number of snapshot that is written next */
double TimeBetSnapshot; /*!< simulation time interval between snapshot files */
double TimeOfFirstSnapshot; /*!< simulation time of first snapshot files */
double CpuTimeBetRestartFile; /*!< cpu-time between regularly generated restart files */
double TimeLastRestartFile; /*!< cpu-time when last restart-file was written */
double TimeBetStatistics; /*!< simulation time interval between computations of energy statistics */
double TimeLastStatistics; /*!< simulation time when the energy statistics was computed the last time */
int NumCurrentTiStep; /*!< counts the number of system steps taken up to this point */
/* Current time of the simulation, global step, and end of simulation */
double Time; /*!< current time of the simulation */
double TimeBegin; /*!< time of initial conditions of the simulation */
double TimeStep; /*!< difference between current times of previous and current timestep */
double TimeMax; /*!< marks the point of time until the simulation is to be evolved */
/* variables for organizing discrete timeline */
double Timebase_interval; /*!< factor to convert from floating point time interval to integer timeline */
int Ti_Current; /*!< current time on integer timeline */
int Ti_nextoutput; /*!< next output time on integer timeline */
#ifdef FLEXSTEPS
int PresentMinStep; /*!< If FLEXSTEPS is used, particle timesteps are chosen as multiples of the present minimum timestep. */
int PresentMaxStep; /*!< If FLEXSTEPS is used, this is the maximum timestep in timeline units, rounded down to the next power 2 division */
#endif
#ifdef PMGRID
int PM_Ti_endstep; /*!< begin of present long-range timestep */
int PM_Ti_begstep; /*!< end of present long-range timestep */
#endif
/* Placement of PM grids */
#ifdef PMGRID
double Asmth[2]; /*!< Gives the scale of the long-range/short-range split (in mesh-cells), both for the coarse and the high-res mesh */
double Rcut[2]; /*!< Gives the maximum radius for which the short-range force is evaluated with the tree (in mesh-cells), both for the coarse and the high-res mesh */
double Corner[2][3]; /*!< lower left corner of coarse and high-res PM-mesh */
double UpperCorner[2][3]; /*!< upper right corner of coarse and high-res PM-mesh */
double Xmintot[2][3]; /*!< minimum particle coordinates both for coarse and high-res PM-mesh */
double Xmaxtot[2][3]; /*!< maximum particle coordinates both for coarse and high-res PM-mesh */
double TotalMeshSize[2]; /*!< total extension of coarse and high-res PM-mesh */
#endif
/* Variables that keep track of cumulative CPU consumption */
double TimeLimitCPU; /*!< CPU time limit as defined in parameterfile */
double CPU_TreeConstruction; /*!< time spent for constructing the gravitational tree */
double CPU_TreeWalk; /*!< actual time spent for pure tree-walks */
double CPU_Gravity; /*!< cumulative time used for gravity computation (tree-algorithm only) */
double CPU_Potential; /*!< time used for computing gravitational potentials */
double CPU_Domain; /*!< cumulative time spent for domain decomposition */
double CPU_Snapshot; /*!< time used for writing snapshot files */
double CPU_Total; /*!< cumulative time spent for domain decomposition */
double CPU_CommSum; /*!< accumulated time used for communication, and for collecting partial results, in tree-gravity */
double CPU_Imbalance; /*!< cumulative time lost accross all processors as work-load imbalance in gravitational tree */
double CPU_HydCompWalk; /*!< time used for actual SPH computations, including neighbour search */
double CPU_HydCommSumm; /*!< cumulative time used for communication in SPH, and for collecting partial results */
double CPU_HydImbalance; /*!< cumulative time lost due to work-load imbalance in SPH */
double CPU_Hydro; /*!< cumulative time spent for SPH related computations */
#ifdef SFR
double CPU_StarFormation; /*!< cumulative time spent for star formation computations */
#endif
#ifdef CHIMIE
double CPU_Chimie; /*!< cumulative time spent for chimie computations */
#endif
#ifdef MULTIPHASE
double CPU_Sticky; /*!< cumulative time spent for sticky computations */
#endif
double CPU_EnsureNgb; /*!< time needed to iterate on correct neighbour numbers */
double CPU_Predict; /*!< cumulative time to drift the system forward in time, including dynamic tree updates */
double CPU_TimeLine; /*!< time used for determining new timesteps, and for organizing the timestepping, including kicks of active particles */
double CPU_PM; /*!< time used for long-range gravitational force */
double CPU_Peano; /*!< time required to establish Peano-Hilbert order */
#ifdef DETAILED_CPU_DOMAIN
double CPU_Domain_findExtend;
double CPU_Domain_determineTopTree;
double CPU_Domain_sumCost;
double CPU_Domain_findSplit;
double CPU_Domain_shiftSplit;
double CPU_Domain_countToGo;
double CPU_Domain_exchange;
#endif
#ifdef DETAILED_CPU_GRAVITY
double CPU_Gravity_TreeWalk1;
double CPU_Gravity_TreeWalk2;
double CPU_Gravity_CommSum1;
double CPU_Gravity_CommSum2;
double CPU_Gravity_Imbalance1;
double CPU_Gravity_Imbalance2;
#endif
#ifdef COOLING
double CPU_Cooling;
#endif
#ifdef DETAILED_CPU
double CPU_Leapfrog;
double CPU_Physics;
double CPU_Residual;
double CPU_Accel;
double CPU_Begrun;
#endif
/* tree code opening criterion */
double ErrTolTheta; /*!< BH tree opening angle */
double ErrTolForceAcc; /*!< parameter for relative opening criterion in tree walk */
/* adjusts accuracy of time-integration */
double ErrTolIntAccuracy; /*!< accuracy tolerance parameter \f$ \eta \f$ for timestep criterion. The
timestep is \f$ \Delta t = \sqrt{\frac{2 \eta eps}{a}} \f$ */
double MinSizeTimestep; /*!< minimum allowed timestep. Normally, the simulation terminates if the
timestep determined by the timestep criteria falls below this limit. */
double MaxSizeTimestep; /*!< maximum allowed timestep */
double MaxRMSDisplacementFac; /*!< this determines a global timestep criterion for cosmological simulations
in comoving coordinates. To this end, the code computes the rms velocity
of all particles, and limits the timestep such that the rms displacement
is a fraction of the mean particle separation (determined from the
particle mass and the cosmological parameters). This parameter specifies
this fraction. */
double CourantFac; /*!< SPH-Courant factor */
/* frequency of tree reconstruction/domain decomposition */
double TreeDomainUpdateFrequency; /*!< controls frequency of domain decompositions */
/* Gravitational and hydrodynamical softening lengths (given in terms of an `equivalent' Plummer softening length).
* Five groups of particles are supported 0="gas", 1="halo", 2="disk", 3="bulge", 4="stars", 5="bndry"
*/
double MinGasHsmlFractional; /*!< minimum allowed SPH smoothing length in units of SPH gravitational softening length */
double MinGasHsml; /*!< minimum allowed SPH smoothing length */
double SofteningGas; /*!< comoving gravitational softening lengths for type 0 */
double SofteningHalo; /*!< comoving gravitational softening lengths for type 1 */
double SofteningDisk; /*!< comoving gravitational softening lengths for type 2 */
double SofteningBulge; /*!< comoving gravitational softening lengths for type 3 */
double SofteningStars; /*!< comoving gravitational softening lengths for type 4 */
double SofteningBndry; /*!< comoving gravitational softening lengths for type 5 */
double SofteningGasMaxPhys; /*!< maximum physical softening length for type 0 */
double SofteningHaloMaxPhys; /*!< maximum physical softening length for type 1 */
double SofteningDiskMaxPhys; /*!< maximum physical softening length for type 2 */
double SofteningBulgeMaxPhys; /*!< maximum physical softening length for type 3 */
double SofteningStarsMaxPhys; /*!< maximum physical softening length for type 4 */
double SofteningBndryMaxPhys; /*!< maximum physical softening length for type 5 */
double SofteningTable[6]; /*!< current (comoving) gravitational softening lengths for each particle type */
double ForceSoftening[6]; /*!< the same, but multiplied by a factor 2.8 - at that scale the force is Newtonian */
double MassTable[6]; /*!< Table with particle masses for particle types with equal mass.
If particle masses are all equal for one type, the corresponding entry in MassTable
is set to this value, allowing the size of the snapshot files to be reduced. */
/* some filenames */
char InitCondFile[MAXLEN_FILENAME]; /*!< filename of initial conditions */
char OutputDir[MAXLEN_FILENAME]; /*!< output directory of the code */
char SnapshotFileBase[MAXLEN_FILENAME]; /*!< basename to construct the names of snapshotf files */
char EnergyFile[MAXLEN_FILENAME]; /*!< name of file with energy statistics */
#ifdef SYSTEMSTATISTICS
char SystemFile[MAXLEN_FILENAME];
#endif
char CpuFile[MAXLEN_FILENAME]; /*!< name of file with cpu-time statistics */
char InfoFile[MAXLEN_FILENAME]; /*!< name of log-file with a list of the timesteps taken */
char LogFile[MAXLEN_FILENAME]; /*!< name of log-file with varied info */
#ifdef SFR
char SfrFile[MAXLEN_FILENAME]; /*!< name of file with sfr records */
#endif
#ifdef CHIMIE
char ChimieFile[MAXLEN_FILENAME]; /*!< name of file with chimie records */
#endif
#ifdef MULTIPHASE
char PhaseFile[MAXLEN_FILENAME]; /*!< name of file with phase records */
char StickyFile[MAXLEN_FILENAME]; /*!< name of file with sticky records */
#endif
#ifdef AGN_ACCRETION
char AccretionFile[MAXLEN_FILENAME]; /*!< name of file with accretion records */
#endif
#ifdef BONDI_ACCRETION
char BondiFile[MAXLEN_FILENAME]; /*!< name of file with bondi records */
#endif
#ifdef BUBBLES
char BubbleFile[MAXLEN_FILENAME]; /*!< name of file with bubble records */
#endif
char TimingsFile[MAXLEN_FILENAME]; /*!< name of file with performance metrics of gravitational tree algorithm */
char RestartFile[MAXLEN_FILENAME]; /*!< basename of restart-files */
char ResubmitCommand[MAXLEN_FILENAME]; /*!< name of script-file that will be executed for automatic restart */
char OutputListFilename[MAXLEN_FILENAME]; /*!< name of file with list of desired output times */
double OutputListTimes[MAXLEN_OUTPUTLIST]; /*!< table with desired output times */
int OutputListLength; /*!< number of output times stored in the table of desired output times */
#ifdef RANDOMSEED_AS_PARAMETER
int RandomSeed; /*!< initial random seed >*/
#endif
}
All; /*!< a container variable for global variables that are equal on all processors */
/*! This structure holds all the information that is
* stored for each particle of the simulation.
*/
extern struct particle_data
{
FLOAT Pos[3]; /*!< particle position at its current time */
FLOAT Mass; /*!< particle mass */
FLOAT Vel[3]; /*!< particle velocity at its current time */
FLOAT GravAccel[3]; /*!< particle acceleration due to gravity */
#ifdef PMGRID
FLOAT GravPM[3]; /*!< particle acceleration due to long-range PM gravity force*/
#endif
#ifdef FORCETEST
FLOAT GravAccelDirect[3]; /*!< particle acceleration when computed with direct summation */
#endif
FLOAT Potential; /*!< gravitational potential */
FLOAT OldAcc; /*!< magnitude of old gravitational force. Used in relative opening criterion */
#ifndef LONGIDS
unsigned int ID; /*!< particle identifier */
#else
unsigned long long ID; /*!< particle identifier */
#endif
int Type; /*!< flags particle type. 0=gas, 1=halo, 2=disk, 3=bulge, 4=stars, 5=bndry */
int Ti_endstep; /*!< marks start of current timestep of particle on integer timeline */
int Ti_begstep; /*!< marks end of current timestep of particle on integer timeline */
#ifdef FLEXSTEPS
int FlexStepGrp; /*!< a random 'offset' on the timeline to create a smooth groouping of particles */
#endif
float GravCost; /*!< weight factor used for balancing the work-load */
#ifdef PSEUDOSYMMETRIC
float AphysOld; /*!< magnitude of acceleration in last timestep. Used to make a first order
prediction of the change of acceleration expected in the future, thereby
allowing to guess whether a decrease/increase of the timestep should occur
in the timestep that is started. */
#endif
#ifdef PARTICLE_FLAG
float Flag;
#endif
#ifdef STELLAR_PROP
unsigned int StPIdx; /*!< index to the corresponding StP particle */
#endif
}
*P, /*!< holds particle data on local processor */
*DomainPartBuf; /*!< buffer for particle data used in domain decomposition */
/* the following struture holds data that is stored for each SPH particle in addition to the collisionless
* variables.
*/
extern struct sph_particle_data
{
FLOAT Entropy; /*!< current value of entropy (actually entropic function) of particle */
FLOAT Density; /*!< current baryonic mass density of particle */
FLOAT Hsml; /*!< current smoothing length */
FLOAT Left; /*!< lower bound in iterative smoothing length search */
FLOAT Right; /*!< upper bound in iterative smoothing length search */
FLOAT NumNgb; /*!< weighted number of neighbours found */
#ifdef AVOIDNUMNGBPROBLEM
FLOAT OldNumNgb;
#endif
FLOAT Pressure; /*!< current pressure */
FLOAT DtEntropy; /*!< rate of change of entropy */
#ifdef STELLAR_FLUX
FLOAT EnergyFlux; /*!< current value of local energy flux - Sph particles */
#endif
#ifdef AGN_HEATING
FLOAT EgySpecAGNHeat; /*!< current value of specific energy radiated of particle - Sph particles */
FLOAT DtEgySpecAGNHeat; /*!< rate of change of specific radiated energy - Sph particles */
FLOAT DtEntropyAGNHeat;
#endif
#ifdef MULTIPHASE
FLOAT StickyTime;
int StickyFlag;
#ifdef COUNT_COLLISIONS
float StickyCollisionNumber;
#endif
#endif
#ifdef FEEDBACK
FLOAT EgySpecFeedback;
FLOAT DtEgySpecFeedback;
FLOAT EnergySN;
FLOAT EnergySNrem;
FLOAT TimeSN;
FLOAT FeedbackVel[3]; /*!< kick due to feedback force */
#endif
#ifdef FEEDBACK_WIND
FLOAT FeedbackWindVel[3]; /*!< kick due to feedback force */
#endif
FLOAT HydroAccel[3]; /*!< acceleration due to hydrodynamical force */
FLOAT VelPred[3]; /*!< predicted SPH particle velocity at the current time */
FLOAT DivVel; /*!< local velocity divergence */
FLOAT CurlVel; /*!< local velocity curl */
FLOAT Rot[3]; /*!< local velocity curl */
FLOAT DhsmlDensityFactor; /*!< correction factor needed in the equation of motion of the conservative entropy formulation of SPH */
FLOAT MaxSignalVel; /*!< maximum "signal velocity" occuring for this particle */
#ifdef MULTIPHASE
int Phase;
int StickyIndex;
int StickyNgb;
int StickyMaxID;
float StickyMaxFs;
FLOAT StickyNewVel[3];
#endif
#ifdef OUTPUTOPTVAR
FLOAT OptVar; /*!< optional variable */
#endif
#ifdef COMPUTE_VELOCITY_DISPERSION
FLOAT VelocityDispersion[VELOCITY_DISPERSION_SIZE]; /*!< velocity dispersion */
#endif
#ifdef CHIMIE
FLOAT Metal[NELEMENTS];
FLOAT dMass; /*!< mass variation due to mass transfere */
#ifdef CHIMIE_THERMAL_FEEDBACK
FLOAT DeltaEgySpec;
FLOAT ThermalTime; /*!< flag particles that got energy from SN */
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
FLOAT WindTime; /*!< flag particles that belongs to the wind */
unsigned int WindFlag; /*!< flag particles that will be part of the wind */
#endif
#endif /*CHIMIE*/
#ifdef ENTROPYPRED
FLOAT EntropyPred; /*!< predicted entropy at the current time */
#endif
}
*SphP, /*!< holds SPH particle data on local processor */
*DomainSphBuf; /*!< buffer for SPH particle data in domain decomposition */
#ifdef STELLAR_PROP
/* the following struture holds data that is stored for each SPH particle in addition to the collisionless
* variables.
*/
extern struct st_particle_data
{
#ifdef CHECK_ID_CORRESPONDENCE
unsigned int ID; /*!< particle identifier (must be the same as P[].ID) only used to check ID correspondance */
#endif
FLOAT FormationTime; /*!< star formation time of particle */
FLOAT InitialMass; /*!< initial stellar mass */
#ifndef LONGIDS
unsigned int IDProj; /*!< id of projenitor particle */
#else
unsigned long long IDProj; /*!< id of projenitor particle */
#endif
FLOAT Metal[NELEMENTS];
FLOAT Density; /*!< current baryonic mass density of particle */
FLOAT Volume; /*!< current volume of particle */
FLOAT Hsml; /*!< current smoothing length */
FLOAT Left; /*!< lower bound in iterative smoothing length search */
FLOAT Right; /*!< upper bound in iterative smoothing length search */
FLOAT NumNgb; /*!< weighted number of neighbours found */
unsigned int PIdx; /*!< index to the corresponding particle */
#ifdef AVOIDNUMNGBPROBLEM
FLOAT OldNumNgb;
#endif
FLOAT DhsmlDensityFactor; /*!< correction factor needed in the equation of motion of the conservative entropy formulation of SPH */
double TotalEjectedGasMass;
double TotalEjectedEltMass[NELEMENTS];
double TotalEjectedEgySpec;
#ifdef CHIMIE_KINETIC_FEEDBACK
double NgbMass; /*!< mass of neighbours */
#endif
#ifdef CHIMIE
unsigned int Flag;
#endif
}
*StP, /*!< holds ST particle data on local processor */
*DomainStBuf; /*!< buffer for ST particle data in domain decomposition */
#endif
/* Variables for Tree
*/
extern int MaxNodes; /*!< maximum allowed number of internal nodes */
extern int Numnodestree; /*!< number of (internal) nodes in each tree */
extern struct NODE
{
FLOAT len; /*!< sidelength of treenode */
FLOAT center[3]; /*!< geometrical center of node */
#ifdef ADAPTIVE_GRAVSOFT_FORGAS
FLOAT maxsoft; /*!< hold the maximum gravitational softening of particles in the
node if the ADAPTIVE_GRAVSOFT_FORGAS option is selected */
#endif
#ifdef STELLAR_FLUX
FLOAT starlum ; /*!< star luminosity of node */
#endif
union
{
int suns[8]; /*!< temporary pointers to daughter nodes */
struct
{
FLOAT s[3]; /*!< center of mass of node */
FLOAT mass; /*!< mass of node */
int bitflags; /*!< a bit-field with various information on the node */
int sibling; /*!< this gives the next node in the walk in case the current node can be used */
int nextnode; /*!< this gives the next node in case the current node needs to be opened */
int father; /*!< this gives the parent node of each node (or -1 if we have the root node) */
}
d;
}
u;
}
*Nodes_base, /*!< points to the actual memory allocted for the nodes */
*Nodes; /*!< this is a pointer used to access the nodes which is shifted such that Nodes[All.MaxPart]
gives the first allocated node */
extern int *Nextnode; /*!< gives next node in tree walk */
extern int *Father; /*!< gives parent node in tree */
extern struct extNODE /*!< this structure holds additional tree-node information which is not needed in the actual gravity computation */
{
FLOAT hmax; /*!< maximum SPH smoothing length in node. Only used for gas particles */
FLOAT vs[3]; /*!< center-of-mass velocity */
}
*Extnodes_base, /*!< points to the actual memory allocted for the extended node information */
*Extnodes; /*!< provides shifted access to extended node information, parallel to Nodes/Nodes_base */
/*! Header for the standard file format.
*/
extern struct io_header
{
int npart[6]; /*!< number of particles of each type in this file */
double mass[6]; /*!< mass of particles of each type. If 0, then the masses are explicitly
stored in the mass-block of the snapshot file, otherwise they are omitted */
double time; /*!< time of snapshot file */
double redshift; /*!< redshift of snapshot file */
int flag_sfr; /*!< flags whether the simulation was including star formation */
int flag_feedback; /*!< flags whether feedback was included (obsolete) */
unsigned int npartTotal[6]; /*!< total number of particles of each type in this snapshot. This can be
different from npart if one is dealing with a multi-file snapshot. */
int flag_cooling; /*!< flags whether cooling was included */
int num_files; /*!< number of files in multi-file snapshot */
double BoxSize; /*!< box-size of simulation in case periodic boundaries were used */
double Omega0; /*!< matter density in units of critical density */
double OmegaLambda; /*!< cosmological constant parameter */
double HubbleParam; /*!< Hubble parameter in units of 100 km/sec/Mpc */
int flag_stellarage; /*!< flags whether the file contains formation times of star particles */
int flag_metals; /*!< flags whether the file contains metallicity values for gas and star particles */
unsigned int npartTotalHighWord[6]; /*!< High word of the total number of particles of each type */
int flag_entropy_instead_u; /*!< flags that IC-file contains entropy instead of u */
int flag_chimie_extraheader; /*!< flags that IC-file contains extra-header for chimie */
#ifdef MULTIPHASE
double critical_energy_spec;
#ifdef MESOMACHINE
char fill[38];
#else
char fill[48]; /* use 42 with regor... */
#endif
#else
char fill[56]; /*!< fills to 256 Bytes */
#endif
}
header; /*!< holds header for snapshot files */
#ifdef CHIMIE_EXTRAHEADER
/*! Header for the chimie part.
*/
extern struct io_chimie_extraheader
{
int nelts; /*!< number of chemical element followed */
float SolarAbundances[NELEMENTS];
char labels[256-4-4*(NELEMENTS)];
}
chimie_extraheader;
#endif
#define IO_NBLOCKS 23 /*!< total number of defined information blocks for snapshot files.
Must be equal to the number of entries in "enum iofields" */
enum iofields /*!< this enumeration lists the defined output blocks in snapshot files. Not all of them need to be present. */
{
IO_POS,
IO_VEL,
IO_ID,
IO_MASS,
IO_U,
IO_RHO,
IO_HSML,
IO_POT,
IO_ACCEL,
IO_DTENTR,
IO_TSTP,
IO_ERADSPH,
IO_ERADSTICKY,
IO_ERADFEEDBACK,
IO_ENERGYFLUX,
IO_OPTVAR,
IO_METALS,
IO_STAR_FORMATIONTIME,
IO_INITIAL_MASS,
IO_STAR_IDPROJ,
IO_STAR_RHO,
IO_STAR_HSML,
IO_STAR_METALS
};
extern char Tab_IO_Labels[IO_NBLOCKS][4]; /*<! This table holds four-byte character tags used for fileformat 2 */
/* global state of system, used for global statistics
*/
extern struct state_of_system
{
double Mass;
double EnergyKin;
double EnergyPot;
double EnergyInt;
#ifdef COOLING
double EnergyRadSph;
#endif
#ifdef AGN_HEATING
double EnergyAGNHeat;
#endif
#ifdef MULTIPHASE
double EnergyRadSticky;
#endif
#ifdef FEEDBACK_WIND
double EnergyFeedbackWind;
#endif
#ifdef BUBBLES
double EnergyBubbles;
#endif
#ifdef CHIMIE_THERMAL_FEEDBACK
double EnergyThermalFeedback;
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
double EnergyKineticFeedback;
#endif
double EnergyTot;
double Momentum[4];
double AngMomentum[4];
double CenterOfMass[4];
double MassComp[6];
double EnergyKinComp[6];
double EnergyPotComp[6];
double EnergyIntComp[6];
#ifdef COOLING
double EnergyRadSphComp[6];
#endif
#ifdef AGN_HEATING
double EnergyAGNHeatComp[6];
#endif
#ifdef MULTIPHASE
double EnergyRadStickyComp[6];
#endif
#ifdef FEEDBACK_WIND
double EnergyFeedbackWindComp[6];
#endif
#ifdef BUBBLES
double EnergyBubblesComp[6];
#endif
#ifdef CHIMIE_THERMAL_FEEDBACK
double EnergyThermalFeedbackComp[6];
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
double EnergyKineticFeedbackComp[6];
#endif
double EnergyTotComp[6];
double MomentumComp[6][4];
double AngMomentumComp[6][4];
double CenterOfMassComp[6][4];
}
SysState; /*<! Structure for storing some global statistics about the simulation. */
/*! This structure contains data related to the energy budget.
These values are different for each task. It need to be stored
in the restart flag.
*/
extern struct local_state_of_system
{
double EnergyTest;
double EnergyInt1;
double EnergyInt2;
double EnergyKin1;
double EnergyKin2;
#ifdef COOLING
double RadiatedEnergy;
#endif
#ifdef SFR
double StarEnergyInt;
#ifdef FEEDBACK
double StarEnergyFeedback;
#endif
#endif
#ifdef CHIMIE_THERMAL_FEEDBACK
double EnergyThermalFeedback;
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
double EnergyKineticFeedback;
#endif
#ifdef MULTIPHASE
double EnergyRadSticky;
#endif
#ifdef FEEDBACK_WIND
double EnergyFeedbackWind;
#endif
}
LocalSysState; /*<! Structure for storing some local statistics about the simulation. */
/* Various structures for communication
*/
extern struct gravdata_in
{
union
{
FLOAT Pos[3];
FLOAT Acc[3];
FLOAT Potential;
}
u;
#if defined(UNEQUALSOFTENINGS) || defined(STELLAR_FLUX)
int Type;
#ifdef ADAPTIVE_GRAVSOFT_FORGAS
FLOAT Soft;
#endif
#endif
#ifdef STELLAR_FLUX
FLOAT EnergyFlux;
#endif
union
{
FLOAT OldAcc;
int Ninteractions;
}
w;
}
*GravDataIn, /*!< holds particle data to be exported to other processors */
*GravDataGet, /*!< holds particle data imported from other processors */
*GravDataResult, /*!< holds the partial results computed for imported particles. Note: We use GravDataResult = GravDataGet, such that the result replaces the imported data */
*GravDataOut; /*!< holds partial results received from other processors. This will overwrite the GravDataIn array */
extern struct gravdata_index
{
int Task;
int Index;
int SortIndex;
}
*GravDataIndexTable; /*!< the particles to be exported are grouped by task-number. This table allows the results to be disentangled again and to be assigned to the correct particle */
extern struct densdata_in
{
FLOAT Pos[3];
FLOAT Vel[3];
FLOAT Hsml;
#ifdef MULTIPHASE
int Phase;
#endif
int Index;
int Task;
}
*DensDataIn, /*!< holds particle data for SPH density computation to be exported to other processors */
*DensDataGet; /*!< holds imported particle data for SPH density computation */
extern struct densdata_out
{
FLOAT Rho;
FLOAT Div, Rot[3];
FLOAT DhsmlDensity;
FLOAT Ngb;
}
*DensDataResult, /*!< stores the locally computed SPH density results for imported particles */
*DensDataPartialResult; /*!< imported partial SPH density results from other processors */
extern struct hydrodata_in
{
FLOAT Pos[3];
FLOAT Vel[3];
FLOAT Hsml;
#ifdef FEEDBACK
FLOAT EnergySN;
#endif
#ifdef MULTIPHASE
int Phase;
FLOAT Entropy;
int StickyFlag;
#endif
FLOAT Mass;
FLOAT Density;
FLOAT Pressure;
FLOAT F1;
FLOAT DhsmlDensityFactor;
int Timestep;
int Task;
int Index;
#ifdef WITH_ID_IN_HYDRA
int ID;
#endif
}
*HydroDataIn, /*!< holds particle data for SPH hydro-force computation to be exported to other processors */
*HydroDataGet; /*!< holds imported particle data for SPH hydro-force computation */
extern struct hydrodata_out
{
FLOAT Acc[3];
FLOAT DtEntropy;
#ifdef FEEDBACK
FLOAT DtEgySpecFeedback;
FLOAT FeedbackAccel[3]; /*!< acceleration due to feedback force */
#endif
FLOAT MaxSignalVel;
#ifdef COMPUTE_VELOCITY_DISPERSION
FLOAT VelocityDispersion[VELOCITY_DISPERSION_SIZE];
#endif
#ifdef MULTIPHASE
FLOAT StickyDVel[3]; /*!< differences in velocities induced by sticky collisions */
#endif
}
*HydroDataResult, /*!< stores the locally computed SPH hydro results for imported particles */
*HydroDataPartialResult; /*!< imported partial SPH hydro-force results from other processors */
#ifdef MULTIPHASE
extern struct stickydata_in
{
FLOAT Pos[3];
FLOAT Vel[3];
FLOAT Mass;
FLOAT Hsml;
int ID;
int StickyMaxID;
int StickyNgb;
float StickyMaxFs;
int Task;
int Index;
}
*StickyDataIn, /*!< holds particle data for sticky computation to be exported to other processors */
*StickyDataGet; /*!< holds imported particle data for sticky computation */
extern struct stickydata_out
{
int StickyMaxID;
int StickyNgb;
float StickyMaxFs;
FLOAT StickyNewVel[3];
}
*StickyDataResult, /*!< stores the locally computed sticky results for imported particles */
*StickyDataPartialResult; /*!< imported partial sticky results from other processors */
extern struct Sticky_index
{
int Index;
int CellIndex;
int Flag;
}
*StickyIndex;
#endif
#ifdef CHIMIE
extern struct chimiedata_in
{
FLOAT Pos[3];
FLOAT Vel[3];
#ifndef LONGIDS
unsigned int ID; /*!< particle identifier */
#else
unsigned long long ID; /*!< particle identifier */
#endif
FLOAT Hsml;
#ifdef FEEDBACK
FLOAT EnergySN;
#endif
#ifdef MULTIPHASE
int Phase;
FLOAT Entropy;
int StickyFlag;
#endif
FLOAT Density;
FLOAT Volume;
FLOAT Pressure;
FLOAT F1;
FLOAT DhsmlDensityFactor;
int Timestep;
int Task;
int Index;
#ifdef WITH_ID_IN_HYDRA
int ID;
#endif
double TotalEjectedGasMass;
double TotalEjectedEltMass[NELEMENTS];
double TotalEjectedEgySpec;
#ifdef CHIMIE_KINETIC_FEEDBACK
FLOAT NgbMass;
#endif
}
*ChimieDataIn, /*!< holds particle data for Chimie computation to be exported to other processors */
*ChimieDataGet; /*!< holds imported particle data for Chimie computation */
extern struct chimiedata_out
{
FLOAT Acc[3];
FLOAT DtEntropy;
#ifdef FEEDBACK
FLOAT DtEgySpecFeedback;
FLOAT FeedbackAccel[3]; /*!< acceleration due to feedback force */
#endif
FLOAT MaxSignalVel;
#ifdef COMPUTE_VELOCITY_DISPERSION
FLOAT VelocityDispersion[VELOCITY_DISPERSION_SIZE];
#endif
#ifdef MULTIPHASE
FLOAT StickyDVel[3]; /*!< differences in velocities induced by sticky collisions */
#endif
}
*ChimieDataResult, /*!< stores the locally computed Chimie results for imported particles */
*ChimieDataPartialResult; /*!< imported partial Chimie results from other processors */
extern struct starsdensdata_in
{
FLOAT Pos[3];
FLOAT Hsml;
int Index;
int Task;
}
*StarsDensDataIn, /*!< holds particle data for SPH density computation to be exported to other processors */
*StarsDensDataGet; /*!< holds imported particle data for SPH density computation */
extern struct starsdensdata_out
{
FLOAT Rho;
FLOAT Volume;
FLOAT DhsmlDensity;
FLOAT Ngb;
#ifdef CHIMIE_KINETIC_FEEDBACK
FLOAT NgbMass;
#endif
}
*StarsDensDataResult, /*!< stores the locally computed SPH density results for imported particles */
*StarsDensDataPartialResult; /*!< imported partial SPH density results from other processors */
#endif
#endif
diff --git a/chimie.c b/chimie.c
index e8009fa..4488ab9 100644
--- a/chimie.c
+++ b/chimie.c
@@ -1,2720 +1,2723 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <mpi.h>
#include <gsl/gsl_math.h>
#include "allvars.h"
#include "proto.h"
#ifdef CHIMIE
/*! \file hydra.c
* \brief Computation of SPH forces and rate of entropy generation
*
* This file contains the "second SPH loop", where the SPH forces are
* computed, and where the rate of change of entropy due to the shock heating
* (via artificial viscosity) is computed.
*/
static double hubble_a, atime, hubble_a2, fac_mu, fac_vsic_fix, a3inv, fac_egy;
#ifdef FEEDBACK
static double fac_pow;
#endif
#ifdef PERIODIC
static double boxSize, boxHalf;
#ifdef LONG_X
static double boxSize_X, boxHalf_X;
#else
#define boxSize_X boxSize
#define boxHalf_X boxHalf
#endif
#ifdef LONG_Y
static double boxSize_Y, boxHalf_Y;
#else
#define boxSize_Y boxSize
#define boxHalf_Y boxHalf
#endif
#ifdef LONG_Z
static double boxSize_Z, boxHalf_Z;
#else
#define boxSize_Z boxSize
#define boxHalf_Z boxHalf
#endif
#endif
/****************************************************************************************/
/*
/*
/*
/* GADGET CHIMIE PART
/*
/*
/*
/****************************************************************************************/
#define MAXPTS 10
#define MAXDATASIZE 200
#define KPC_IN_CM 3.085e+21
static int verbose=0;
static double *MassFracSNII;
static double *SingleMassFracSNII;
static double *EjectedMass;
static double *SingleEjectedMass;
static double **MassFracSNIIs;
static double **SingleMassFracSNIIs;
static double **EjectedMasss;
static double **SingleEjectedMasss;
/* intern global variables */
static struct local_params_chimie
{
float coeff_z[3][3];
float Mmin,Mmax;
int n;
float ms[MAXPTS];
float as[MAXPTS+1];
float bs[MAXPTS+1];
float fs[MAXPTS];
double imf_Ntot;
float SNII_Mmin;
float SNII_Mmax;
float SNII_cte;
float SNII_a;
float SNIa_Mpl;
float SNIa_Mpu;
float SNIa_a;
float SNIa_cte;
float SNIa_Mdl1;
float SNIa_Mdu1;
float SNIa_a1;
float SNIa_b1;
float SNIa_cte1;
float SNIa_bb1;
float SNIa_Mdl2;
float SNIa_Mdu2;
float SNIa_a2;
float SNIa_b2;
float SNIa_cte2;
float SNIa_bb2;
float Mco;
int npts;
int nelts;
}
*Cps,*Cp;
static struct local_elts_chimie
{
float Mmin; /* minimal mass */
float Step; /* log of mass step */
float Array[MAXDATASIZE]; /* data */
float Metal[MAXDATASIZE]; /* data */
float MSNIa;
float SolarAbundance;
char label[72];
}
**Elts,*Elt;
void allocate_chimie()
{
int j;
/* allocate Cp */
Cps = malloc((All.ChimieNumberOfParameterFiles) * sizeof(struct local_params_chimie));
/* allocate elts */
Elts = malloc((All.ChimieNumberOfParameterFiles) * sizeof(struct local_elts_chimie));
//for (j=0;j<All.ChimieNumberOfParameterFiles;j++)
// Elt[j] = malloc((nelts) * sizeof(struct local_elts_chimie));
MassFracSNIIs = malloc((All.ChimieNumberOfParameterFiles) * sizeof(double));
EjectedMasss = malloc((All.ChimieNumberOfParameterFiles) * sizeof(double));
SingleMassFracSNIIs= malloc((All.ChimieNumberOfParameterFiles) * sizeof(double));
SingleEjectedMasss = malloc((All.ChimieNumberOfParameterFiles) * sizeof(double));
}
void allocate_Elts(int it)
{
/* allocate memory for elts */
if (Cps[it].npts<=MAXDATASIZE)
{
Elts[it] = malloc((Cps[it].nelts+2) * sizeof(struct local_elts_chimie));
}
else
{
printf("\n Cps[it].npts = %d > MAXDATASIZE = %d !!!\n\n",Cps[it].npts,MAXDATASIZE);
endrun(88800);
}
}
void set_table(int i)
{
if (i>=All.ChimieNumberOfParameterFiles)
{
printf("\n set_table : i>= %d !!!\n\n",All.ChimieNumberOfParameterFiles);
endrun(88809);
}
else
{
Cp = &Cps[i];
Elt = Elts[i];
MassFracSNII = MassFracSNIIs[i];
SingleMassFracSNII = SingleMassFracSNIIs[i];
EjectedMass = EjectedMasss[i];
SingleEjectedMass = SingleEjectedMasss[i];
}
}
void read_chimie(char * filename,int it)
{
char line[72],buffer[72];
FILE *fd;
int i,j;
if (ThisTask==0)
{
printf("reading %s ...\n",filename);
fd = fopen(filename,"r");
/* read Lifetime */
fgets(line, sizeof(line), fd);
fgets(line, sizeof(line), fd);
fscanf(fd, "%g %g %g\n", &Cps[it].coeff_z[0][0],&Cps[it].coeff_z[0][1],&Cps[it].coeff_z[0][2]);
fscanf(fd, "%g %g %g\n", &Cps[it].coeff_z[1][0],&Cps[it].coeff_z[1][1],&Cps[it].coeff_z[1][2]);
fscanf(fd, "%g %g %g\n", &Cps[it].coeff_z[2][0],&Cps[it].coeff_z[2][1],&Cps[it].coeff_z[2][2]);
fgets(line, sizeof(line), fd);
/* IMF Parameters */
fgets(line, sizeof(line), fd);
fscanf(fd, "%g %g\n",&Cps[it].Mmin,&Cps[it].Mmax);
fscanf(fd, "%d\n",&Cps[it].n);
if (Cps[it].n>0)
for (i=0;i<Cps[it].n;i++)
fscanf(fd,"%g",&Cps[it].ms[i]);
else
fgets(line, sizeof(line), fd);
for (i=0;i<Cps[it].n+1;i++)
fscanf(fd,"%g",&Cps[it].as[i]);
fgets(line, sizeof(line), fd);
/* Parameters for SNII Rates */
fgets(line, sizeof(line), fd);
fgets(line, sizeof(line), fd);
fscanf(fd, "%g \n",&Cps[it].SNII_Mmin);
fgets(line, sizeof(line), fd);
/* Parameters for SNIa Rates */
fgets(line, sizeof(line), fd);
fscanf(fd, "%g %g\n",&Cps[it].SNIa_Mpl,&Cps[it].SNIa_Mpu);
fscanf(fd, "%g \n",&Cps[it].SNIa_a);
fscanf(fd, "%g %g %g\n",&Cps[it].SNIa_Mdl1,&Cps[it].SNIa_Mdu1,&Cps[it].SNIa_bb1);
fscanf(fd, "%g %g %g\n",&Cps[it].SNIa_Mdl2,&Cps[it].SNIa_Mdu2,&Cps[it].SNIa_bb2);
fgets(line, sizeof(line), fd);
/* Metal injection SNII */
fgets(line, sizeof(line), fd);
fgets(line, sizeof(line), fd);
fscanf(fd, "%d %d\n",&Cps[it].npts,&Cps[it].nelts);
/* allocate memory for elts */
allocate_Elts(it);
/* injected metals */
for (i=0;i<Cps[it].nelts+2;i++)
{
fgets(line, sizeof(line), fd);
/* strip trailing line */
for (j = 0; j < strlen(line); j++)
if ( line[j] == '\n' || line[j] == '\r' )
line[j] = '\0';
/* copy labels */
strcpy(Elts[it][i].label,line);
strcpy(buffer,&Elts[it][i].label[2]);
strcpy(Elts[it][i].label,buffer);
fgets(line, sizeof(line), fd);
fscanf(fd, "%g %g\n",&Elts[it][i].Mmin,&Elts[it][i].Step);
for (j=0;j<Cps[it].npts;j++)
{
fscanf(fd, "%g\n",&Elts[it][i].Metal[j]);
}
}
/* integrals of injected metals */
fgets(line, sizeof(line), fd);
fgets(line, sizeof(line), fd);
fscanf(fd, "%d %d\n",&Cps[it].npts,&Cps[it].nelts);
fgets(line, sizeof(line), fd);
fgets(line, sizeof(line), fd);
/* integrals of injected metals */
for (i=0;i<Cps[it].nelts+2;i++)
{
fgets(line, sizeof(line), fd);
fgets(line, sizeof(line), fd);
fscanf(fd, "%g %g\n",&Elts[it][i].Mmin,&Elts[it][i].Step);
for (j=0;j<Cps[it].npts;j++)
{
fscanf(fd, "%g\n",&Elts[it][i].Array[j]);
}
}
/* Metal injection SNIa */
fgets(line, sizeof(line), fd);
fgets(line, sizeof(line), fd);
fscanf(fd, "%g\n",&Cps[it].Mco);
fgets(line, sizeof(line), fd);
fgets(line, sizeof(line), fd);
fgets(line, sizeof(line), fd);
int nelts;
char label[72];
fscanf(fd, "%d\n",&nelts);
/* check */
if (nelts != Cps[it].nelts)
{
printf("\nThe number of elements in SNII (=%d) is not identical to the on of SNIa (=%d) !!!\n\n",Cps[it].nelts,nelts);
printf("This is not supported by the current implementation !!!\n");
endrun(88805);
}
for (i=0;i<Cps[it].nelts+2;i++)
{
fgets(line, sizeof(line), fd); /* label */
/* check label */
/* strip trailing line */
for (j = 0; j < strlen(line); j++)
if ( line[j] == '\n' || line[j] == '\r' )
line[j] = '\0';
strcpy(label,line);
strcpy(buffer,&label[2]);
strcpy(label,buffer);
if (strcmp(label,Elts[it][i].label)!=0)
{
printf("\nLabel of SNII element %d (=%s) is different from the SNIa one (=%s) !!!\n\n",i,Elts[it][i].label,label);
endrun(88806);
}
//fgets(line, sizeof(line), fd);
fscanf(fd, "%g\n",&Elts[it][i].MSNIa);
}
/* Solar Abundances */
fgets(line, sizeof(line), fd);
fgets(line, sizeof(line), fd);
fgets(line, sizeof(line), fd);
fgets(line, sizeof(line), fd);
fscanf(fd, "%d\n",&nelts);
/* check */
if (nelts != Cps[it].nelts)
{
printf("\nThe number of elements in SolarAbundances (=%d) is not identical to the on of SNIa (=%d) !!!\n\n",Cps[it].nelts,nelts);
printf("This is not supported by the current implementation !!!\n");
endrun(88805);
}
for (i=0;i<Cps[it].nelts;i++)
{
fgets(line, sizeof(line), fd); /* label */
/* check label */
/* strip trailing line */
for (j = 0; j < strlen(line); j++)
if ( line[j] == '\n' || line[j] == '\r' )
line[j] = '\0';
strcpy(label,line);
strcpy(buffer,&label[2]);
strcpy(label,buffer);
if (strcmp(label,Elts[it][i+2].label)!=0)
{
printf("\nLabel of SNII element %d (=%s) is different from the SNIa one (=%s) !!!\n\n",i,Elts[it][i+2].label,label);
endrun(88806);
}
//fgets(line, sizeof(line), fd);
fscanf(fd, "%g\n",&Elts[it][i+2].SolarAbundance);
}
fclose(fd);
}
/* send Cps */
MPI_Bcast(Cps, (All.ChimieNumberOfParameterFiles) * sizeof(struct local_params_chimie), MPI_BYTE, 0, MPI_COMM_WORLD);
/* slaves allocate Elts */
if (ThisTask!=0)
allocate_Elts(it);
MPI_Bcast(Elts[it], (Cps[it].nelts+2) * sizeof(struct local_elts_chimie), MPI_BYTE, 0, MPI_COMM_WORLD);
/* allocate memory */
MassFracSNIIs[it] = malloc((Cps[it].nelts+2) * sizeof(double));
EjectedMasss[it] = malloc((Cps[it].nelts+2) * sizeof(double));
SingleMassFracSNIIs[it] = malloc((Cps[it].nelts+2) * sizeof(double));
SingleEjectedMasss[it] = malloc((Cps[it].nelts+2) * sizeof(double));
if (verbose && ThisTask==0)
{
printf("%g %g %g\n", Cps[it].coeff_z[0][0],Cps[it].coeff_z[0][1],Cps[it].coeff_z[0][2]);
printf("%g %g %g\n", Cps[it].coeff_z[1][0],Cps[it].coeff_z[1][1],Cps[it].coeff_z[1][2]);
printf("%g %g %g\n", Cps[it].coeff_z[2][0],Cps[it].coeff_z[2][1],Cps[it].coeff_z[2][2]);
printf("\n");
printf("\nIMF\n");
printf("%g %g\n",Cps[it].Mmin,Cps[it].Mmax);
printf("%d\n",Cps[it].n);
for (i=0;i<Cps[it].n;i++)
printf( "ms : %g ",Cps[it].ms[i]);
printf("\n");
for (i=0;i<Cps[it].n+1;i++)
printf( "as : %g ",Cps[it].as[i]);
printf("\n");
printf("\nRate SNII\n");
printf("%g ",Cps[it].SNII_Mmin);
printf("\n");
printf("\nRate SNIa\n");
printf("%g %g\n",Cps[it].SNIa_Mpl,Cps[it].SNIa_Mpu);
printf("%g \n",Cps[it].SNIa_a);
printf("%g %g %g\n",Cps[it].SNIa_Mdl1,Cps[it].SNIa_Mdu1,Cps[it].SNIa_b1);
printf("%g %g %g\n",Cps[it].SNIa_Mdl2,Cps[it].SNIa_Mdu2,Cps[it].SNIa_b2);
printf("\n");
for (i=0;i<Cps[it].nelts+2;i++)
{
printf("> %g %g\n",Elts[it][i].Mmin,Elts[it][i].Step);
for (j=0;j<Cps[it].npts;j++)
{
printf(" %g\n",Elts[it][i].Array[j]);
}
}
printf("\n");
printf("%g\n",Cps[it].Mco);
for (i=0;i<Cps[it].nelts+2;i++)
printf("%g\n",Elts[it][i].MSNIa);
printf("\n");
}
}
/*
This function returns the mass fraction of a star of mass m
using the current IMF
*/
static double get_imf(double m)
{
int i;
int n;
n = Cp->n;
/* convert m in msol */
m = m*All.UnitMass_in_g / SOLAR_MASS;
if (n==0)
return Cp->bs[0]* pow(m,Cp->as[0]);
else
{
for (i=0;i<n;i++)
if (m < Cp->ms[i])
return Cp->bs[i]* pow(m,Cp->as[i]);
return Cp->bs[n]* pow(m,Cp->as[n]);
}
}
/*
This function returns the mass fraction between m1 and m2
per mass unit, using the current IMF
*/
static double get_imf_M(double m1, double m2)
{
int i;
int n;
double p;
double integral=0;
double mmin,mmax;
n = Cp->n;
/* convert m in msol */
m1 = m1*All.UnitMass_in_g / SOLAR_MASS;
m2 = m2*All.UnitMass_in_g / SOLAR_MASS;
if (n==0)
{
p = Cp->as[0]+1;
integral = (Cp->bs[0]/p) * ( pow(m2,p) - pow(m1,p) );
//printf("--> %g %g %g %g int=%g\n",m1,m2,pow(m2,p), pow(m1,p),integral);
}
else
{
integral = 0;
/* first */
if (m1<Cp->ms[0])
{
mmin = m1;
mmax = dmin(Cp->ms[0],m2);
p = Cp->as[0] + 1;
integral += (Cp->bs[0]/p) * ( pow(mmax,p) - pow(mmin,p) );
}
/* last */
if (m2>Cp->ms[n-1])
{
mmin = dmax(Cp->ms[n-1],m1);
mmax = m2;
p = Cp->as[n] + 1;
integral += (Cp->bs[n]/p) * ( pow(mmax,p) - pow(mmin,p) );
}
/* loop over other segments */
for (i=0;i<n-1;i++)
{
mmin = dmax(Cp->ms[i ],m1);
mmax = dmin(Cp->ms[i+1],m2);
if (mmin<mmax)
{
p = Cp->as[i+1] + 1;
integral += (Cp->bs[i+1]/p) * ( pow(mmax,p) - pow(mmin,p) );
}
}
}
/* convert into mass unit mass unit */
/* integral = integral * SOLAR_MASS/All.UnitMass_in_g;*/
return integral;
}
/*
This function returns the number fraction between m1 and m2
per mass unit, using the current IMF
*/
static double get_imf_N(double m1, double m2)
{
int i;
int n;
double p;
double integral=0;
double mmin,mmax;
n = Cp->n;
/* convert m in msol */
m1 = m1*All.UnitMass_in_g / SOLAR_MASS;
m2 = m2*All.UnitMass_in_g / SOLAR_MASS;
if (n==0)
{
p = Cp->as[0];
integral = (Cp->bs[0]/p) * ( pow(m2,p) - pow(m1,p) );
}
else
{
integral = 0;
/* first */
if (m1<Cp->ms[0])
{
mmin = m1;
mmax = dmin(Cp->ms[0],m2);
p = Cp->as[0];
integral += (Cp->bs[0]/p) * ( pow(mmax,p) - pow(mmin,p) );
}
/* last */
if (m2>Cp->ms[n-1])
{
mmin = dmax(Cp->ms[n-1],m1);
mmax = m2;
p = Cp->as[n];
integral += (Cp->bs[n]/p) * ( pow(mmax,p) - pow(mmin,p) );
}
/* loop over other segments */
for (i=0;i<n-1;i++)
{
mmin = dmax(Cp->ms[i ],m1);
mmax = dmin(Cp->ms[i+1],m2);
if (mmin<mmax)
{
p = Cp->as[i+1];
integral += (Cp->bs[i+1]/p) * ( pow(mmax,p) - pow(mmin,p) );
}
}
}
/* convert into mass unit mass unit */
integral = integral / SOLAR_MASS*All.UnitMass_in_g;
return integral;
}
/*
This function returns the number fraction between m1 and m2
per mass unit, using the current IMF
*/
static double imf_sampling()
{
int i;
int n;
double m;
double f;
double pmin,pmax;
n = Cp->n;
/* init random */
//srandom(irand);
f = (double)random()/(double)RAND_MAX;
if (n==0)
{
pmin = pow(Cp->Mmin,Cp->as[0]);
pmax = pow(Cp->Mmax,Cp->as[0]);
m = pow(f*(pmax - pmin) + pmin ,1./Cp->as[0]);
return m* SOLAR_MASS/All.UnitMass_in_g;
}
else
{
if (f<Cp->fs[0])
{
pmin = pow(Cp->Mmin ,Cp->as[0]);
m = pow(Cp->imf_Ntot*Cp->as[0]/Cp->bs[0]* (f-0) + pmin ,1./Cp->as[0]);
return m* SOLAR_MASS/All.UnitMass_in_g;
}
for (i=0;i<n-1;i++)
{
if (f<Cp->fs[i+1])
{
pmin = pow(Cp->ms[i] ,Cp->as[i+1]);
m = pow(Cp->imf_Ntot*Cp->as[i+1]/Cp->bs[i+1]* (f-Cp->fs[i]) + pmin ,1./Cp->as[i+1]);
return m* SOLAR_MASS/All.UnitMass_in_g;
}
}
/* last portion */
pmin = pow(Cp->ms[n-1] ,Cp->as[n]);
m = pow(Cp->imf_Ntot*Cp->as[n]/Cp->bs[n]* (f-Cp->fs[n-1]) + pmin ,1./Cp->as[n]);
return m* SOLAR_MASS/All.UnitMass_in_g;
}
}
/*
This function initialized the imf parameters
defined in the chimie file
*/
void init_imf(void)
{
float integral = 0;
float p;
float cte;
int i,n;
double mmin,mmax;
n = Cp->n;
if (n==0)
{
p = Cp->as[0]+1;
integral = integral + ( pow(Cp->Mmax,p)-pow(Cp->Mmin,p))/(p) ;
Cp->bs[0] = 1./integral ;
}
else
{
cte = 1.0;
if (Cp->Mmin < Cp->ms[0])
{
p = Cp->as[0]+1;
integral = integral + (pow(Cp->ms[0],p) - pow(Cp->Mmin,p))/p;
}
for (i=0;i<n-1;i++)
{
cte = cte* pow( Cp->ms[i],( Cp->as[i] - Cp->as[i+1] ));
p = Cp->as[i+1]+1;
integral = integral + cte*(pow(Cp->ms[i+1],p) - pow(Cp->ms[i],p))/p;
}
if (Cp->Mmax > Cp->ms[-1])
{
cte = cte* pow( Cp->ms[n-1] , ( Cp->as[n-1] - Cp->as[n] ) );
p = Cp->as[n]+1;
integral = integral + cte*(pow(Cp->Mmax,p) - pow(Cp->ms[n-1],p))/p;
}
/* compute all b */
Cp->bs[0] = 1./integral;
for (i=0;i<n;i++)
{
Cp->bs[i+1] = Cp->bs[i] * pow( Cp->ms[i],( Cp->as[i] - Cp->as[i+1] ));
}
}
if (verbose && ThisTask==0)
{
printf("-- bs -- \n");
for (i=0;i<n+1;i++)
printf("%g ",Cp->bs[i]);
printf("\n");
}
mmin = Cp->Mmin / All.UnitMass_in_g * SOLAR_MASS; /* in mass unit */
mmax = Cp->Mmax / All.UnitMass_in_g * SOLAR_MASS; /* in mass unit */
Cp->imf_Ntot = get_imf_N(mmin,mmax) *SOLAR_MASS/All.UnitMass_in_g;
/* init fs : mass fraction at ms */
if (n>0)
{
for (i=0;i<n+1;i++)
{
mmax = Cp->ms[i] / All.UnitMass_in_g * SOLAR_MASS; /* in mass unit */
Cp->fs[i] = SOLAR_MASS/All.UnitMass_in_g*get_imf_N(mmin,mmax)/Cp->imf_Ntot;
}
}
}
/*
This function init the chime parameters
*/
void init_chimie(void)
{
int i,nf;
double u_lt;
double UnitLength_in_kpc;
double UnitMass_in_Msol;
char filename[500];
char ext[100];
/* check some flags */
#ifndef COSMICTIME
if (All.ComovingIntegrationOn)
{
if(ThisTask == 0)
printf("Code wasn't compiled with COSMICTIME support enabled!\n");
endrun(-88800);
}
#endif
UnitLength_in_kpc = All.UnitLength_in_cm / KPC_IN_CM;
UnitMass_in_Msol = All.UnitMass_in_g / SOLAR_MASS;
//u_lt = -log10( 4.7287e11*sqrt(pow(UnitLength_in_kpc,3)/UnitMass_in_Msol));
/*Sat Dec 25 23:27:10 CET 2010 */
u_lt = -log10(All.UnitTime_in_Megayears*1e6);
allocate_chimie();
for (nf=0;nf<All.ChimieNumberOfParameterFiles;nf++)
{
if (All.ChimieNumberOfParameterFiles==1)
sprintf(filename,"%s",All.ChimieParameterFile);
else
sprintf(filename,"%s.%d",All.ChimieParameterFile,nf);
read_chimie(filename,nf);
/* set the table */
set_table(nf);
/* Conversion into program time unit */
Cp->coeff_z[2][2] = Cp->coeff_z[2][2] + u_lt;
for (i=0;i<3;i++)
Cp->coeff_z[1][i] = Cp->coeff_z[1][i]/2.0;
/* init imf parameters */
init_imf();
/* init SNII parameters */
if (Cp->n==0)
{
//Cp->SNII_cte[0] = Cp->bs[0]/Cp->as[0];
Cp->SNII_cte = Cp->bs[0]/Cp->as[0];
Cp->SNII_a = Cp->as[0];
}
else
{
//for (i=0;i<Cp->n+1;i++) /* if multiple power law in the SNII mass range */
// Cp->SNII_cte[i] = Cp->bs[i]/Cp->as[i];
Cp->SNII_cte = Cp->bs[Cp->n]/Cp->as[Cp->n];
Cp->SNII_a = Cp->as[Cp->n];
}
/* init SNIa parameters */
Cp->SNIa_a1 = Cp->SNIa_a;
Cp->SNIa_b1 = (Cp->SNIa_a1+1)/(pow(Cp->SNIa_Mdu1,Cp->SNIa_a1+1)-pow(Cp->SNIa_Mdl1,Cp->SNIa_a1+1));
Cp->SNIa_cte1 = Cp->SNIa_b1/Cp->SNIa_a1;
Cp->SNIa_a2 = Cp->SNIa_a;
Cp->SNIa_b2 = (Cp->SNIa_a2+1)/(pow(Cp->SNIa_Mdu2,Cp->SNIa_a2+1)-pow(Cp->SNIa_Mdl2,Cp->SNIa_a2+1));
Cp->SNIa_cte2 = Cp->SNIa_b2/Cp->SNIa_a2;
/* init SNII parameters */
if (Cp->n==0)
{
Cp->SNIa_cte = Cp->bs[0]/Cp->as[0];
Cp->SNIa_a = Cp->as[0];
}
else
{
Cp->SNIa_cte = Cp->bs[Cp->n]/Cp->as[Cp->n];
Cp->SNIa_a = Cp->as[Cp->n];
}
Cp->SNII_Mmax = Cp->Mmax;
for (i=0;i<Cp->nelts+2;i++)
Elt[i].Mmin = log10(Elt[i].Mmin);
/* output info */
if (verbose && ThisTask==0)
{
printf("-- SNII_cte -- \n");
//for (i=0;i<Cp->n+1;i++)
// printf("%g ",Cp->SNII_cte[i]);
printf("%g ",Cp->SNII_cte);
printf("\n");
}
/* check that the masses are higher than the last IMF elbow */
if (Cp->n>0)
{
if (Cp->SNIa_Mpl < Cp->ms[Cp->n-1])
{
printf("\nSNIa_Mpl = %g < ms[n-1] = %g !!!\n\n",Cp->SNIa_Mpl,Cp->ms[Cp->n-1]);
printf("This is not supported by the current implementation !!!\n");
endrun(88801);
}
if (Cp->SNIa_Mpu < Cp->ms[Cp->n-1])
{
printf("\nSNIa_Mpu = %g < ms[n-1] = %g !!!\n\n",Cp->SNIa_Mpu,Cp->ms[Cp->n-1]);
printf("This is not supported by the current implementation !!!\n");
endrun(88802);
}
if (Cp->SNII_Mmin < Cp->ms[Cp->n-1])
{
printf("\nSNII_Mmin = %g < ms[n-1] = %g !!!\n\n",Cp->SNII_Mmin,Cp->ms[Cp->n-1]);
printf("This is not supported by the current implementation !!!\n");
endrun(88803);
}
if (Cp->SNII_Mmax < Cp->ms[Cp->n-1])
{
printf("\nSNII_Mmax = %g < ms[n-1] = %g !!!\n\n",Cp->SNII_Mmax,Cp->ms[Cp->n-1]);
printf("This is not supported by the current implementation !!!\n");
endrun(88804);
}
}
}
}
void check_chimie(void)
{
int i;
printf("(Taks=%d) Number of elts : %d\n",ThisTask,Cp->nelts);
for(i=2;i<Cp->nelts+2;i++)
printf("%s ",&Elt[i].label);
printf("\n");
/* check number of elements */
if (NELEMENTS != Cp->nelts)
{
- printf("(Taks=%d) NELEMENTS (=%d) != Cp->nelts (=%d) : please check !!!\n\n",ThisTask,NELEMENTS,Cp->nelts);
+ printf("\n(Taks=%d) NELEMENTS (=%d) != Cp->nelts (=%d)!!!\n\n",ThisTask,NELEMENTS,Cp->nelts);
+ printf("This means that the number of chemical elements defined in the chimie parameter file is\n");
+ printf("different from the one defined by the variable NELEMENTS.\n");
+ printf("You can either change NELEMENTS and recompile the code or change the chimie parameter file.\n");
endrun(88807);
}
/* check that iron is the first element */
if ((strcmp("Fe",Elt[2].label))!=0)
{
printf("(Taks=%d) first element (=%s) is not %s !!!\n\n",ThisTask,Elt[2].label,FIRST_ELEMENT);
endrun(88808);
}
}
int get_nelts()
{
return Cp->nelts;
}
float get_SolarAbundance(i)
{
return Elt[i+2].SolarAbundance;
}
char* get_Element(i)
{
return Elt[i+2].label;
}
double star_lifetime(double z,double m)
{
/* z is the mass fraction of metals, ie, the metallicity */
/* m is the stellar mass in code unit */
/* Return t in code time unit */
int i;
double a,b,c;
double coeff[3];
double logm,twologm,logm2,time;
/* convert m in msol */
m = m*All.UnitMass_in_g / SOLAR_MASS;
for (i=0;i<3;i++)
coeff[i] = ( Cp->coeff_z[i][0]*z+Cp->coeff_z[i][1] )*z+Cp->coeff_z[i][2];
a = coeff[0];
b = coeff[1];
c = coeff[2];
logm = log10(m);
twologm = 2.0 * logm;
logm2 = logm*logm;
time = pow(10.,(a*logm2+b*twologm+c));
return time;
}
double star_mass_from_age(double z,double t)
{
/* z is the mass fraction of metals, ie, the metallicity */
/* t is the star life time */
/* return the stellar mass (in code unit) that has a lifetime equal to t */
/* this is the inverse of star_lifetime */
int i;
double a,b,c;
double coeff[3];
double m;
for (i=0;i<3;i++)
coeff[i] = ( Cp->coeff_z[i][0]*z+Cp->coeff_z[i][1] )*z+Cp->coeff_z[i][2];
a = coeff[0];
b = coeff[1];
c = coeff[2];
m = -(b+sqrt(b*b-a*(c-log10(t))))/a;
m = pow(10,m); /* here, m is in solar mass */
m = m*SOLAR_MASS/All.UnitMass_in_g; /* Msol to mass unit */
return m;
}
/****************************************************************************************/
/*
/* Supernova rate : number of supernova per mass unit
/*
/****************************************************************************************/
double SNII_rate(double m1,double m2)
{
/*
masses in code unit
*/
double RSNII;
double md,mu;
RSNII = 0.0;
/* convert m in msol */
m1 = m1*All.UnitMass_in_g / SOLAR_MASS;
m2 = m2*All.UnitMass_in_g / SOLAR_MASS;
/* (1) find md, mu */
md = dmax(m1,Cp->SNII_Mmin);
mu = dmin(m2,Cp->SNII_Mmax);
if (mu<=md) /* no SNII in that mass range */
return 0.0;
RSNII = Cp->SNII_cte * (pow(mu,Cp->SNII_a)-pow(md,Cp->SNII_a)); /* number per solar mass */
/* convert in number per solar mass to number per mass unit */
RSNII = RSNII *All.UnitMass_in_g / SOLAR_MASS;
return RSNII;
}
double SNIa_rate(double m1,double m2)
{
/*
masses in code unit
*/
double RSNIa;
double md,mu;
RSNIa = 0.0;
/* convert m in msol */
m1 = m1*All.UnitMass_in_g / SOLAR_MASS;
m2 = m2*All.UnitMass_in_g / SOLAR_MASS;
/* RG contribution */
md = dmax(m1,Cp->SNIa_Mdl1);
mu = dmin(m2,Cp->SNIa_Mdu1);
if (md<mu)
RSNIa = RSNIa + Cp->SNIa_bb1 * Cp->SNIa_cte1 * (pow(mu,Cp->SNIa_a1)-pow(md,Cp->SNIa_a1));
/* MS contribution */
md = dmax(m1,Cp->SNIa_Mdl2);
mu = dmin(m2,Cp->SNIa_Mdu2);
if (md<mu)
RSNIa = RSNIa + Cp->SNIa_bb2 * Cp->SNIa_cte2 * (pow(mu,Cp->SNIa_a2)-pow(md,Cp->SNIa_a2));
/* WD contribution */
md = dmax(m1,Cp->SNIa_Mpl); /* select stars that have finished their life -> WD */
mu = Cp->SNIa_Mpu; /* no upper bond */
if (mu<=md) /* no SNIa in that mass range */
return 0.0;
RSNIa = RSNIa * Cp->SNIa_cte * (pow(mu,Cp->SNIa_a)-pow(md,Cp->SNIa_a)); /* number per solar mass */
/* convert in number per solar mass to number per mass unit */
RSNIa = RSNIa *All.UnitMass_in_g / SOLAR_MASS;
return RSNIa;
}
void SNII_mass_ejection(double m1,double m2)
{
double l1,l2;
int i1,i2,i1p,i2p,j;
double f1,f2;
double v1,v2;
/* convert m in msol */
m1 = m1*All.UnitMass_in_g / SOLAR_MASS;
m2 = m2*All.UnitMass_in_g / SOLAR_MASS;
j = 0;
l1 = ( log10(m1) - Elt[j].Mmin) / Elt[j].Step ;
l2 = ( log10(m2) - Elt[j].Mmin) / Elt[j].Step ;
if (l1 < 0.0) l1 = 0.0;
if (l2 < 0.0) l2 = 0.0;
i1 = (int)l1;
i2 = (int)l2;
i1p = i1 + 1;
i2p = i2 + 1;
f1 = l1 - i1;
f2 = l2 - i2;
/* check (yr) */
if (i1<0) i1=0;
if (i2<0) i2=0;
/* --------- TOTAL GAS ---------- */
j = 0;
v1 = f1 * ( Elt[j].Array[i1p] - Elt[j].Array[i1] ) + Elt[j].Array[i1];
v2 = f2 * ( Elt[j].Array[i2p] - Elt[j].Array[i2] ) + Elt[j].Array[i2];
MassFracSNII[j] = v2-v1;
/* --------- He core therm ---------- */
j = 1;
v1 = f1 * ( Elt[j].Array[i1p] - Elt[j].Array[i1] ) + Elt[j].Array[i1];
v2 = f2 * ( Elt[j].Array[i2p] - Elt[j].Array[i2] ) + Elt[j].Array[i2];
MassFracSNII[j] = v2-v1;
/* ---------------------------- */
/* --------- Metals ---------- */
/* ---------------------------- */
j = 2;
l1 = ( log10(m1) - Elt[j].Mmin) / Elt[j].Step ;
l2 = ( log10(m2) - Elt[j].Mmin) / Elt[j].Step ;
if (l1 < 0.0) l1 = 0.0;
if (l2 < 0.0) l2 = 0.0;
i1 = (int)l1;
i2 = (int)l2;
i1p = i1 + 1;
i2p = i2 + 1;
f1 = l1 - i1;
f2 = l2 - i2;
/* check (yr) */
if (i1<0) i1=0;
if (i2<0) i2=0;
for (j=2;j<Cp->nelts+2;j++)
{
v1 = f1 * ( Elt[j].Array[i1p] - Elt[j].Array[i1] ) + Elt[j].Array[i1];
v2 = f2 * ( Elt[j].Array[i2p] - Elt[j].Array[i2] ) + Elt[j].Array[i2];
MassFracSNII[j] = v2-v1;
}
}
void SNII_single_mass_ejection(double m1)
{
double l1;
int i1,i1p,j;
double f1;
double v1;
/* convert m in msol */
m1 = m1*All.UnitMass_in_g / SOLAR_MASS;
j = 0;
l1 = ( log10(m1) - Elt[j].Mmin) / Elt[j].Step ;
if (l1 < 0.0) l1 = 0.0;
i1 = (int)l1;
i1p = i1 + 1;
f1 = l1 - i1;
/* check (yr) */
if (i1<0) i1=0;
/* --------- TOTAL GAS ---------- */
j = 0;
v1 = f1 * ( Elt[j].Metal[i1p] - Elt[j].Metal[i1] ) + Elt[j].Metal[i1];
SingleMassFracSNII[j] = v1;
/* --------- He core therm ---------- */
j = 1;
v1 = f1 * ( Elt[j].Metal[i1p] - Elt[j].Metal[i1] ) + Elt[j].Metal[i1];
SingleMassFracSNII[j] = v1;
/* ---------------------------- */
/* --------- Metals ---------- */
/* ---------------------------- */
j = 2;
l1 = ( log10(m1) - Elt[j].Mmin) / Elt[j].Step ;
if (l1 < 0.0) l1 = 0.0;
i1 = (int)l1;
i1p = i1 + 1;
f1 = l1 - i1;
/* check (yr) */
if (i1<0) i1=0;
for (j=2;j<Cp->nelts+2;j++)
{
v1 = f1 * ( Elt[j].Metal[i1p] - Elt[j].Metal[i1] ) + Elt[j].Metal[i1];
SingleMassFracSNII[j] = v1;
}
}
void Total_mass_ejection(double m1,double m2,double M0,double *z)
{
int j;
double NSNIa;
/* compute SNII mass ejection -> MassFracSNII */
SNII_mass_ejection(m1,m2);
/* number of SNIa per mass unit between time and time+dt */
NSNIa = SNIa_rate(m1,m2)*M0;
/* number of SNII per mass unit between time and time+dt */
//NSNII = SNII_rate(m1,m2)*M0; /* useless (only for energy) */
/* total ejected gas mass */
EjectedMass[0] = M0 * MassFracSNII[0] + Cp->Mco/All.UnitMass_in_g*SOLAR_MASS * NSNIa;
/* ejected mass per element */
for (j=2;j<Cp->nelts+2;j++)
EjectedMass[j] = M0*(MassFracSNII[j] +z[j-2]*MassFracSNII[1]) + NSNIa* Elt[j].MSNIa/All.UnitMass_in_g*SOLAR_MASS;
/* not used */
EjectedMass[1] = -1;
}
void Total_single_mass_ejection(double m1,double *z)
{
/*
!!! we do not take into account SNIa
*/
int j;
float M0;
M0 = m1;
/* compute SNII mass ejection -> SingleMassFracSNII */
SNII_single_mass_ejection(m1);
/* total ejected gas mass */
SingleEjectedMass[0] = M0 * SingleMassFracSNII[0]; /* + Cp->Mco/All.UnitMass_in_g*SOLAR_MASS * NSNIa; */
/* ejected mass per element */
for (j=2;j<Cp->nelts+2;j++)
SingleEjectedMass[j] = M0*(SingleMassFracSNII[j] +z[j-2]*SingleMassFracSNII[1]); /* + NSNIa* Elt[j].MSNIa/All.UnitMass_in_g*SOLAR_MASS; */
/* not used */
SingleEjectedMass[1] = -1;
}
/**********************************************************************************************
END OF CHIMIE FUNCTIONS
**********************************************************************************************/
#if defined(CHIMIE_THERMAL_FEEDBACK) && defined(CHIMIE_COMPUTE_THERMAL_FEEDBACK_ENERGY)
void chimie_compute_energy_int(int mode)
{
int i;
double DeltaEgyInt;
double Tot_DeltaEgyInt;
DeltaEgyInt = 0;
Tot_DeltaEgyInt = 0;
if (mode==1)
{
LocalSysState.EnergyInt1 = 0;
LocalSysState.EnergyInt2 = 0;
}
for(i = 0; i < N_gas; i++)
{
if (P[i].Type==0)
{
if (mode==1)
LocalSysState.EnergyInt1 += P[i].Mass * SphP[i].EntropyPred / (GAMMA_MINUS1) * pow(SphP[i].Density*a3inv, GAMMA_MINUS1);
else
LocalSysState.EnergyInt2 += P[i].Mass * SphP[i].EntropyPred / (GAMMA_MINUS1) * pow(SphP[i].Density*a3inv, GAMMA_MINUS1);
}
}
if (mode==2)
{
DeltaEgyInt = LocalSysState.EnergyInt2 - LocalSysState.EnergyInt1;
MPI_Reduce(&DeltaEgyInt, &Tot_DeltaEgyInt, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
LocalSysState.EnergyThermalFeedback -= DeltaEgyInt;
}
}
#endif
#if defined(CHIMIE_KINETIC_FEEDBACK) && defined(CHIMIE_COMPUTE_KINETIC_FEEDBACK_ENERGY)
void chimie_compute_energy_kin(int mode)
{
int i;
double DeltaEgyKin;
double Tot_DeltaEgyKin;
DeltaEgyKin = 0;
Tot_DeltaEgyKin = 0;
if (mode==1)
{
LocalSysState.EnergyKin1 = 0;
LocalSysState.EnergyKin2 = 0;
}
for(i = 0; i < N_gas; i++)
{
if (P[i].Type==0)
{
if (mode==1)
LocalSysState.EnergyKin1 += 0.5 * P[i].Mass * (P[i].Vel[0]*P[i].Vel[0]+P[i].Vel[1]*P[i].Vel[1]+P[i].Vel[2]*P[i].Vel[2]);
else
LocalSysState.EnergyKin2 += 0.5 * P[i].Mass * (P[i].Vel[0]*P[i].Vel[0]+P[i].Vel[1]*P[i].Vel[1]+P[i].Vel[2]*P[i].Vel[2]);
}
}
if (mode==2)
{
DeltaEgyKin = LocalSysState.EnergyKin2 - LocalSysState.EnergyKin1;
MPI_Reduce(&DeltaEgyKin, &Tot_DeltaEgyKin, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
LocalSysState.EnergyKineticFeedback -= DeltaEgyKin;
}
}
#endif
#ifdef CHIMIE_THERMAL_FEEDBACK
void chimie_apply_thermal_feedback(void)
{
int i;
double EgySpec,NewEgySpec,DeltaEntropy;
for(i = 0; i < N_gas; i++)
{
if (P[i].Type==0)
{
if (SphP[i].DeltaEgySpec > 0)
{
/* spec energy at current step */
EgySpec = SphP[i].EntropyPred / GAMMA_MINUS1 * pow(SphP[i].Density*a3inv, GAMMA_MINUS1);
/* new egyspec */
NewEgySpec = EgySpec + SphP[i].DeltaEgySpec;
LocalSysState.EnergyThermalFeedback -= SphP[i].DeltaEgySpec*P[i].Mass;
/* new entropy */
DeltaEntropy = GAMMA_MINUS1*NewEgySpec/pow(SphP[i].Density*a3inv, GAMMA_MINUS1) - SphP[i].EntropyPred;
SphP[i].EntropyPred += DeltaEntropy;
SphP[i].Entropy += DeltaEntropy;
/* reset variable */
SphP[i].DeltaEgySpec = 0;
/* recode time */
SphP[i].ThermalTime = All.Time;
}
}
}
}
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
void chimie_apply_wind(void)
{
/* apply wind */
int i;
double e1,e2;
double phi,costh,sinth,vx,vy,vz;
for(i = 0; i < N_gas; i++)
{
if (P[i].Type==0)
{
if (SphP[i].WindFlag)
{
phi = get_ChimieKineticFeedback_random_number(P[i].ID)*PI*2.;
costh = 1.-2.*get_ChimieKineticFeedback_random_number(P[i].ID+1);
sinth = sqrt(1.-pow(costh,2));
vx = All.ChimieWindSpeed*sinth*cos(phi);
vy = All.ChimieWindSpeed*sinth*sin(phi);
vz = All.ChimieWindSpeed*costh;
e1 = 0.5*P[i].Mass * ( SphP[i].VelPred[0]*SphP[i].VelPred[0] + SphP[i].VelPred[1]*SphP[i].VelPred[1] + SphP[i].VelPred[2]*SphP[i].VelPred[2]);
P[i].Vel[0] += vx;
P[i].Vel[1] += vy;
P[i].Vel[2] += vz;
SphP[i].VelPred[0] += vx;
SphP[i].VelPred[1] += vy;
SphP[i].VelPred[2] += vz;
e2 = 0.5*P[i].Mass * ( SphP[i].VelPred[0]*SphP[i].VelPred[0] + SphP[i].VelPred[1]*SphP[i].VelPred[1] + SphP[i].VelPred[2]*SphP[i].VelPred[2]);
LocalSysState.EnergyKineticFeedback -= e2-e1;
SphP[i].WindFlag = 0;
}
}
}
}
#endif
/*! This function is the driver routine for the calculation of chemical evolution
*/
void chimie(void)
{
double t0, t1;
t0 = second(); /* measure the time for the full chimie computation */
if (ThisTask==0)
printf("Start Chimie computation.\n");
if(All.ComovingIntegrationOn)
{
/* Factors for comoving integration of hydro */
hubble_a = All.Omega0 / (All.Time * All.Time * All.Time)
+ (1 - All.Omega0 - All.OmegaLambda) / (All.Time * All.Time) + All.OmegaLambda;
hubble_a = All.Hubble * sqrt(hubble_a);
hubble_a2 = All.Time * All.Time * hubble_a;
fac_mu = pow(All.Time, 3 * (GAMMA - 1) / 2) / All.Time;
fac_egy = pow(All.Time, 3 * (GAMMA - 1));
fac_vsic_fix = hubble_a * pow(All.Time, 3 * GAMMA_MINUS1);
a3inv = 1 / (All.Time * All.Time * All.Time);
atime = All.Time;
#ifdef FEEDBACK
fac_pow = fac_egy*atime*atime;
#endif
}
else
{
hubble_a = hubble_a2 = atime = fac_mu = fac_vsic_fix = a3inv = fac_egy = 1.0;
#ifdef FEEDBACK
fac_pow = 1.0;
#endif
}
/* apply thermal feedback on selected particles */
#ifdef CHIMIE_THERMAL_FEEDBACK
chimie_apply_thermal_feedback();
#endif
/* apply wind on selected particles */
#ifdef CHIMIE_KINETIC_FEEDBACK
chimie_apply_wind();
#endif
stars_density(); /* compute density */
do_chimie(); /* chimie */
if (ThisTask==0)
printf("Chimie computation done.\n");
t1 = second();
All.CPU_Chimie += timediff(t0, t1);
}
/*! This function is the driver routine for the calculation of chemical evolution
*/
void do_chimie(void)
{
long long ntot, ntotleft;
int i, j, k, n, m, ngrp, maxfill, source, ndone;
int *nbuffer, *noffset, *nsend_local, *nsend, *numlist, *ndonelist;
int level, sendTask, recvTask, nexport, place;
double tstart, tend, sumt, sumcomm;
double timecomp = 0, timecommsumm = 0, timeimbalance = 0, sumimbalance;
int flag_chimie;
MPI_Status status;
int do_it;
int Ti0,Ti1,Ti2;
double t1,t2,t01,t02;
double tmin,tmax;
double minlivetime,maxlivetime;
double m1,m2,M0;
double NSNIa,NSNII;
double NSNIa_tot,NSNII_tot,NSNIa_totlocal,NSNII_totlocal;
double EgySN,EgySNlocal;
double EgySNThermal,EgySNKinetic;
int Nchim,Nchimlocal;
int Nwind,Nwindlocal;
int Nflag,Nflaglocal;
int Noldwind,Noldwindlocal;
double metals[NELEMENTS];
double FeH;
float MinRelMass=1e-3;
#ifdef PERIODIC
boxSize = All.BoxSize;
boxHalf = 0.5 * All.BoxSize;
#ifdef LONG_X
boxHalf_X = boxHalf * LONG_X;
boxSize_X = boxSize * LONG_X;
#endif
#ifdef LONG_Y
boxHalf_Y = boxHalf * LONG_Y;
boxSize_Y = boxSize * LONG_Y;
#endif
#ifdef LONG_Z
boxHalf_Z = boxHalf * LONG_Z;
boxSize_Z = boxSize * LONG_Z;
#endif
#endif
#ifdef COMPUTE_VELOCITY_DISPERSION
double v1m,v2m;
#endif
/* `NumStUpdate' gives the number of particles on this processor that want a chimie computation */
for(n = 0, NumStUpdate = 0; n < N_gas+N_stars; n++)
{
if(P[n].Ti_endstep == All.Ti_Current)
if(P[n].Type == ST)
{
m = P[n].StPIdx;
if ( (P[n].Mass/StP[m].InitialMass) > MinRelMass)
NumStUpdate++;
}
if(P[n].Type == 0)
SphP[n].dMass = 0.;
}
numlist = malloc(NTask * sizeof(int) * NTask);
MPI_Allgather(&NumStUpdate, 1, MPI_INT, numlist, 1, MPI_INT, MPI_COMM_WORLD);
for(i = 0, ntot = 0; i < NTask; i++)
ntot += numlist[i];
free(numlist);
noffset = malloc(sizeof(int) * NTask); /* offsets of bunches in common list */
nbuffer = malloc(sizeof(int) * NTask);
nsend_local = malloc(sizeof(int) * NTask);
nsend = malloc(sizeof(int) * NTask * NTask);
ndonelist = malloc(sizeof(int) * NTask);
i = 0; /* first gas particle, because stars may be hidden among gas particles */
ntotleft = ntot; /* particles left for all tasks together */
NSNIa_tot = 0;
NSNII_tot = 0;
NSNIa_totlocal = 0;
NSNII_totlocal = 0;
EgySN = 0;
EgySNlocal =0;
Nchimlocal = 0;
Nchim = 0;
Nwindlocal = 0;
Nwind = 0;
Noldwindlocal = 0;
Noldwind = 0;
Nflaglocal = 0;
Nflag = 0;
while(ntotleft > 0)
{
for(j = 0; j < NTask; j++)
nsend_local[j] = 0;
/* do local particles and prepare export list */
tstart = second();
for(nexport = 0, ndone = 0; i < N_gas+N_stars && nexport < All.BunchSizeChimie - NTask; i++)
{
/* only active particles and stars */
if((P[i].Ti_endstep == All.Ti_Current)&&(P[i].Type == ST))
{
if(P[i].Type != ST)
{
printf("P[i].Type != ST, we better stop.\n");
printf("N_gas=%d (type=%d) i=%d (type=%d)\n",N_gas,P[N_gas].Type,i,P[i].Type);
printf("Please, check that you do not use PEANOHILBERT\n");
endrun(777001);
}
m = P[i].StPIdx;
if ( (P[i].Mass/StP[m].InitialMass) > MinRelMass)
{
flag_chimie = 0;
/******************************************/
/* do chimie */
/******************************************/
/*****************************************************/
/* look if a SN may have explode during the last step
/*****************************************************/
/***********************************************/
/***********************************************/
/* set the right table base of the metallicity */
set_table(0);
//FeH = log10( (StP[m].Metal[FE]/get_SolarAbundance(FE)) + 1.e-20 );
//if (FeH<-3)
// set_table(1);
//else
// set_table(0);
//if (P[i].ID==65546)
// {
// printf("(%d) %g the particle 65546 FeH=%g metalFe=%g Mmin=%g Mmax=%g n=%d\n",ThisTask,All.Time,FeH,StP[m].Metal[FE],Cp->Mmin,Cp->Mmax,Cp->n);
// }
/*
Cp->Mmin
Cp->Mmax
Cp->n
Cp->ms[]
Cp->as[]
Cp->SNIa_cte
Cp->SNIa_a
Cp->SNIa_Mdl1
Cp->SNIa_Mdu1
Cp->SNIa_bb1
Cp->SNIa_cte1
Cp->SNIa_a1
Cp->SNIa_Mdl2
Cp->SNIa_Mdu2
Cp->SNIa_bb2
Cp->SNIa_cte2
Cp->SNIa_a2
*/
/***********************************************/
/***********************************************/
/* minimum live time for a given metallicity */
minlivetime = star_lifetime(StP[m].Metal[NELEMENTS-1],Cp->Mmax*SOLAR_MASS/All.UnitMass_in_g)*All.HubbleParam;
/* maximum live time for a given metallicity */
maxlivetime = star_lifetime(StP[m].Metal[NELEMENTS-1],Cp->Mmin*SOLAR_MASS/All.UnitMass_in_g)*All.HubbleParam;
//if (P[i].ID==65546)
// printf("(%d) %g the particle 65546 has a max livetime of %g (metal=%g Mmin=%g)\n",ThisTask,All.Time,maxlivetime,StP[m].Metal[NELEMENTS-1],Cp->Mmin);
if (All.ComovingIntegrationOn)
{
/* FormationTime on the time line */
Ti0 = log(StP[m].FormationTime/All.TimeBegin) / All.Timebase_interval;
/* Beginning of time step on the time line */
Ti1 = P[i].Ti_begstep;
/* End of time step on the time line */
Ti2 = All.Ti_Current;
#ifdef COSMICTIME
t01 = get_cosmictime_difference(Ti0,Ti1);
t02 = get_cosmictime_difference(Ti0,Ti2);
#endif
}
else
{
t1 = All.TimeBegin + (P[i].Ti_begstep * All.Timebase_interval);
t2 = All.TimeBegin + (All.Ti_Current * All.Timebase_interval);
t01 = t1-StP[m].FormationTime;
t02 = t2-StP[m].FormationTime;
}
/* now treat all cases */
do_it=1;
/* beginning of interval */
if (t01>=minlivetime)
if (t01>=maxlivetime)
do_it=0; /* nothing to do */
else
m2 = star_mass_from_age(StP[m].Metal[NELEMENTS-1],t01/All.HubbleParam)*All.HubbleParam;
else
m2 = Cp->Mmax*SOLAR_MASS/All.UnitMass_in_g*All.HubbleParam;
/* end of interval */
if (t02<=maxlivetime)
if (t02<=minlivetime)
do_it=0; /* nothing to do */
else
m1 = star_mass_from_age(StP[m].Metal[NELEMENTS-1],t02/All.HubbleParam)*All.HubbleParam;
else
m1 = Cp->Mmin*SOLAR_MASS/All.UnitMass_in_g*All.HubbleParam;
//printf("Time=%g t01=%g t02=%g id=%d minlivetime=%g maxlivetime=%g \n",All.Time,t01,t02,P[i].ID,minlivetime,maxlivetime);
/* if some of the stars in the SSP explode between t1 and t2 */
if (do_it)
{
Nchimlocal++;
StP[m].Flag = 1; /* mark it as active */
if (m1>m2)
{
printf("m1=%g (%g Msol) > m2=%g (%g Msol) !!!\n\n",m1,m1*All.UnitMass_in_g/SOLAR_MASS,m2,m2*All.UnitMass_in_g/SOLAR_MASS);
endrun(777002);
}
M0 = StP[m].InitialMass;
for (k=0;k<NELEMENTS;k++)
metals[k] = StP[m].Metal[k];
/* number of SNIa */
NSNIa = SNIa_rate(m1/All.HubbleParam,m2/All.HubbleParam)*M0/All.HubbleParam;
/* number of SNII */
NSNII = SNII_rate(m1/All.HubbleParam,m2/All.HubbleParam)*M0/All.HubbleParam;
NSNIa_totlocal += NSNIa;
NSNII_totlocal += NSNII;
/* compute ejectas */
Total_mass_ejection(m1/All.HubbleParam,m2/All.HubbleParam,M0/All.HubbleParam,metals);
StP[m].TotalEjectedGasMass = EjectedMass[0]*All.HubbleParam; /* gas mass */
for (k=0;k<NELEMENTS;k++)
StP[m].TotalEjectedEltMass[k] = EjectedMass[k+2]*All.HubbleParam; /* metal mass */
if (StP[m].TotalEjectedGasMass>0)
flag_chimie=1;
/* compute injected energy */
StP[m].TotalEjectedEgySpec = All.ChimieSupernovaEnergy* (NSNIa + NSNII) /StP[m].TotalEjectedGasMass;
EgySNlocal += All.ChimieSupernovaEnergy* (NSNIa + NSNII);
/* correct mass particle */
if (P[i].Mass-StP[m].TotalEjectedGasMass<0)
{
printf("mass wants to be less than zero...\n");
printf("P[i].Mass=%g StP[m].TotalEjectedGasMass=%g\n",P[i].Mass,StP[m].TotalEjectedGasMass);
endrun(777100);
}
//if (P[i].ID==65546)
// printf("(%d) %g the particle 65546 is here, mass=%g TotalEjectedEltMass=%g m1=%g m2=%g\n",ThisTask,All.Time,P[i].Mass,StP[m].TotalEjectedGasMass,m1,m2);
P[i].Mass = P[i].Mass-StP[m].TotalEjectedGasMass;
//float Fe,Mg;
//Fe = StP[m].TotalEjectedEltMass[0];
//Mg = StP[m].TotalEjectedEltMass[1];
}
/******************************************/
/* end do chimie */
/******************************************/
ndone++;
if (flag_chimie)
{
for(j = 0; j < NTask; j++)
Exportflag[j] = 0;
chimie_evaluate(i, 0);
for(j = 0; j < NTask; j++)
{
if(Exportflag[j])
{
for(k = 0; k < 3; k++)
{
ChimieDataIn[nexport].Pos[k] = P[i].Pos[k];
ChimieDataIn[nexport].Vel[k] = P[i].Vel[k];
}
ChimieDataIn[nexport].ID = P[i].ID;
ChimieDataIn[nexport].Timestep = P[i].Ti_endstep - P[i].Ti_begstep;
ChimieDataIn[nexport].Hsml = StP[m].Hsml;
ChimieDataIn[nexport].Density = StP[m].Density;
ChimieDataIn[nexport].Volume = StP[m].Volume;
#ifdef CHIMIE_KINETIC_FEEDBACK
ChimieDataIn[nexport].NgbMass = StP[m].NgbMass;
#endif
ChimieDataIn[nexport].TotalEjectedGasMass = StP[m].TotalEjectedGasMass;
for(k = 0; k < NELEMENTS; k++)
ChimieDataIn[nexport].TotalEjectedEltMass[k] = StP[m].TotalEjectedEltMass[k];
ChimieDataIn[nexport].TotalEjectedEgySpec = StP[m].TotalEjectedEgySpec;
#ifdef WITH_ID_IN_HYDRA
ChimieDataIn[nexport].ID = P[i].ID;
#endif
ChimieDataIn[nexport].Index = i;
ChimieDataIn[nexport].Task = j;
nexport++;
nsend_local[j]++;
}
}
}
}
}
}
tend = second();
timecomp += timediff(tstart, tend);
qsort(ChimieDataIn, nexport, sizeof(struct chimiedata_in), chimie_compare_key);
for(j = 1, noffset[0] = 0; j < NTask; j++)
noffset[j] = noffset[j - 1] + nsend_local[j - 1];
tstart = second();
MPI_Allgather(nsend_local, NTask, MPI_INT, nsend, NTask, MPI_INT, MPI_COMM_WORLD);
tend = second();
timeimbalance += timediff(tstart, tend);
/* now do the particles that need to be exported */
for(level = 1; level < (1 << PTask); level++)
{
tstart = second();
for(j = 0; j < NTask; j++)
nbuffer[j] = 0;
for(ngrp = level; ngrp < (1 << PTask); ngrp++)
{
maxfill = 0;
for(j = 0; j < NTask; j++)
{
if((j ^ ngrp) < NTask)
if(maxfill < nbuffer[j] + nsend[(j ^ ngrp) * NTask + j])
maxfill = nbuffer[j] + nsend[(j ^ ngrp) * NTask + j];
}
if(maxfill >= All.BunchSizeChimie)
break;
sendTask = ThisTask;
recvTask = ThisTask ^ ngrp;
if(recvTask < NTask)
{
if(nsend[ThisTask * NTask + recvTask] > 0 || nsend[recvTask * NTask + ThisTask] > 0)
{
/* get the particles */
MPI_Sendrecv(&ChimieDataIn[noffset[recvTask]],
nsend_local[recvTask] * sizeof(struct chimiedata_in), MPI_BYTE,
recvTask, TAG_CHIMIE_A,
&ChimieDataGet[nbuffer[ThisTask]],
nsend[recvTask * NTask + ThisTask] * sizeof(struct chimiedata_in), MPI_BYTE,
recvTask, TAG_CHIMIE_A, MPI_COMM_WORLD, &status);
}
}
for(j = 0; j < NTask; j++)
if((j ^ ngrp) < NTask)
nbuffer[j] += nsend[(j ^ ngrp) * NTask + j];
}
tend = second();
timecommsumm += timediff(tstart, tend);
/* now do the imported particles */
tstart = second();
for(j = 0; j < nbuffer[ThisTask]; j++)
chimie_evaluate(j, 1);
tend = second();
timecomp += timediff(tstart, tend);
/* do a block to measure imbalance */
tstart = second();
MPI_Barrier(MPI_COMM_WORLD);
tend = second();
timeimbalance += timediff(tstart, tend);
/* get the result */
tstart = second();
for(j = 0; j < NTask; j++)
nbuffer[j] = 0;
for(ngrp = level; ngrp < (1 << PTask); ngrp++)
{
maxfill = 0;
for(j = 0; j < NTask; j++)
{
if((j ^ ngrp) < NTask)
if(maxfill < nbuffer[j] + nsend[(j ^ ngrp) * NTask + j])
maxfill = nbuffer[j] + nsend[(j ^ ngrp) * NTask + j];
}
if(maxfill >= All.BunchSizeChimie)
break;
sendTask = ThisTask;
recvTask = ThisTask ^ ngrp;
if(recvTask < NTask)
{
if(nsend[ThisTask * NTask + recvTask] > 0 || nsend[recvTask * NTask + ThisTask] > 0)
{
/* send the results */
MPI_Sendrecv(&ChimieDataResult[nbuffer[ThisTask]],
nsend[recvTask * NTask + ThisTask] * sizeof(struct chimiedata_out),
MPI_BYTE, recvTask, TAG_CHIMIE_B,
&ChimieDataPartialResult[noffset[recvTask]],
nsend_local[recvTask] * sizeof(struct chimiedata_out),
MPI_BYTE, recvTask, TAG_CHIMIE_B, MPI_COMM_WORLD, &status);
/* add the result to the particles */
for(j = 0; j < nsend_local[recvTask]; j++)
{
source = j + noffset[recvTask];
place = ChimieDataIn[source].Index;
// for(k = 0; k < 3; k++)
// SphP[place].HydroAccel[k] += HydroDataPartialResult[source].Acc[k];
//
// SphP[place].DtEntropy += HydroDataPartialResult[source].DtEntropy;
//#ifdef FEEDBACK
// SphP[place].DtEgySpecFeedback += HydroDataPartialResult[source].DtEgySpecFeedback;
//#endif
// if(SphP[place].MaxSignalVel < HydroDataPartialResult[source].MaxSignalVel)
// SphP[place].MaxSignalVel = HydroDataPartialResult[source].MaxSignalVel;
//#ifdef COMPUTE_VELOCITY_DISPERSION
// for(k = 0; k < VELOCITY_DISPERSION_SIZE; k++)
// SphP[place].VelocityDispersion[k] += HydroDataPartialResult[source].VelocityDispersion[k];
//#endif
}
}
}
for(j = 0; j < NTask; j++)
if((j ^ ngrp) < NTask)
nbuffer[j] += nsend[(j ^ ngrp) * NTask + j];
}
tend = second();
timecommsumm += timediff(tstart, tend);
level = ngrp - 1;
}
MPI_Allgather(&ndone, 1, MPI_INT, ndonelist, 1, MPI_INT, MPI_COMM_WORLD);
for(j = 0; j < NTask; j++)
ntotleft -= ndonelist[j];
}
free(ndonelist);
free(nsend);
free(nsend_local);
free(nbuffer);
free(noffset);
/* do final operations on results */
tstart = second();
for(i = 0; i < N_gas; i++)
{
if (P[i].Type==0)
{
P[i].Mass += SphP[i].dMass;
SphP[i].dMass = 0.;
}
}
tend = second();
timecomp += timediff(tstart, tend);
/* collect some timing information */
MPI_Reduce(&timecomp, &sumt, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(&timecommsumm, &sumcomm, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(&timeimbalance, &sumimbalance, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
// if(ThisTask == 0)
// {
// All.CPU_HydCompWalk += sumt / NTask;
// All.CPU_HydCommSumm += sumcomm / NTask;
// All.CPU_HydImbalance += sumimbalance / NTask;
// }
/* collect some chimie informations */
MPI_Reduce(&NSNIa_totlocal, &NSNIa_tot, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(&NSNII_totlocal, &NSNII_tot, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(&EgySNlocal, &EgySN, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(&Nchimlocal, &Nchim, 1, MPI_INT , MPI_SUM, 0, MPI_COMM_WORLD);
#ifdef CHIMIE_THERMAL_FEEDBACK
EgySNThermal = EgySN*(1-All.ChimieKineticFeedbackFraction);
#else
EgySNThermal = 0;
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
EgySNKinetic = EgySN*All.ChimieKineticFeedbackFraction;
/* count number of wind particles */
for(i = 0; i < N_gas; i++)
{
if (P[i].Type==0)
{
if (SphP[i].WindTime >= (All.Time-All.ChimieWindTime))
Nwindlocal++;
//else
// if (SphP[i].WindTime > All.TimeBegin-2*All.ChimieWindTime)
// Noldwindlocal++;
if (SphP[i].WindFlag)
Nflaglocal++;
}
}
MPI_Reduce(&Nwindlocal, &Nwind, 1, MPI_INT , MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(&Noldwindlocal, &Noldwind, 1, MPI_INT , MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Allreduce(&Nflaglocal, &Nflag, 1, MPI_INT , MPI_SUM, MPI_COMM_WORLD);
#else
EgySNKinetic = 0;
#endif
/* write some info */
if (ThisTask==0)
{
fprintf(FdChimie, "%15g %10d %15g %15g %15g %15g %15g %10d %10d %10d\n",All.Time,Nchim,NSNIa_tot,NSNII_tot,EgySN,EgySNThermal,EgySNKinetic,Nwind,Noldwind,Nflag);
fflush(FdChimie);
}
if (Nflag>0)
{
SetMinTimeStepForActives=1;
if (ThisTask==0)
fprintf(FdLog,"%g : !!! set min timestep for active particles !!!\n",All.Time);
}
}
/*! This function is the 'core' of the Chemie computation. A target
* particle is specified which may either be local, or reside in the
* communication buffer.
*/
void chimie_evaluate(int target, int mode)
{
int j, n, startnode, numngb,numngb_inbox,k;
FLOAT *pos,*vel;
//FLOAT *vel;
//FLOAT mass;
double h, h2;
double acc[3];
double dx, dy, dz;
double wk, r, r2, u=0;
double hinv=1, hinv3;
int target_stp;
double density;
double volume;
#ifdef CHIMIE_KINETIC_FEEDBACK
double ngbmass;
double p;
#endif
double aij;
double ejectedGasMass;
double ejectedEltMass[NELEMENTS];
double ejectedEgySpec;
double mass_k;
double NewMass;
double fv,vi2,vj2;
double EgySpec,NewEgySpec;
double DeltaEntropy;
double DeltaVel[3];
#ifndef LONGIDS
unsigned int id; /*!< particle identifier */
#else
unsigned long long id; /*!< particle identifier */
#endif
if(mode == 0)
{
pos = P[target].Pos;
vel = P[target].Vel;
id = P[target].ID;
target_stp = P[target].StPIdx;
h = StP[target_stp].Hsml;
density = StP[target_stp].Density;
volume = StP[target_stp].Volume;
#ifdef CHIMIE_KINETIC_FEEDBACK
ngbmass = StP[target_stp].NgbMass;
#endif
ejectedGasMass = StP[target_stp].TotalEjectedGasMass;
for(k=0;k<NELEMENTS;k++)
ejectedEltMass[k] = StP[target_stp].TotalEjectedEltMass[k];
ejectedEgySpec = StP[target_stp].TotalEjectedEgySpec;
}
else
{
pos = ChimieDataGet[target].Pos;
vel = ChimieDataGet[target].Vel;
id = ChimieDataGet[target].ID;
h = ChimieDataGet[target].Hsml;
density = ChimieDataGet[target].Density;
volume = ChimieDataGet[target].Volume;
#ifdef CHIMIE_KINETIC_FEEDBACK
ngbmass = ChimieDataGet[target].NgbMass;
#endif
ejectedGasMass = ChimieDataGet[target].TotalEjectedGasMass;
for(k=0;k<NELEMENTS;k++)
ejectedEltMass[k] = ChimieDataGet[target].TotalEjectedEltMass[k];
ejectedEgySpec = ChimieDataGet[target].TotalEjectedEgySpec;
}
/* initialize variables before SPH loop is started */
acc[0] = acc[1] = acc[2] = 0;
vi2 = 0;
for(k=0;k<3;k++)
vi2 += vel[k]*vel[k];
h2 = h * h;
hinv = 1.0 / h;
#ifndef TWODIMS
hinv3 = hinv * hinv * hinv;
#else
hinv3 = hinv * hinv / boxSize_Z;
#endif
/* Now start the actual SPH computation for this particle */
startnode = All.MaxPart;
numngb = 0;
do
{
numngb_inbox = ngb_treefind_variable_for_chimie(&pos[0], h, &startnode);
for(n = 0; n < numngb_inbox; n++)
{
j = Ngblist[n];
dx = pos[0] - P[j].Pos[0];
dy = pos[1] - P[j].Pos[1];
dz = pos[2] - P[j].Pos[2];
#ifdef PERIODIC /* now find the closest image in the given box size */
if(dx > boxHalf_X)
dx -= boxSize_X;
if(dx < -boxHalf_X)
dx += boxSize_X;
if(dy > boxHalf_Y)
dy -= boxSize_Y;
if(dy < -boxHalf_Y)
dy += boxSize_Y;
if(dz > boxHalf_Z)
dz -= boxSize_Z;
if(dz < -boxHalf_Z)
dz += boxSize_Z;
#endif
r2 = dx * dx + dy * dy + dz * dz;
if(r2 < h2)
{
numngb++;
r = sqrt(r2);
u = r * hinv;
if(u < 0.5)
{
wk = hinv3 * (KERNEL_COEFF_1 + KERNEL_COEFF_2 * (u - 1) * u * u);
}
else
{
wk = hinv3 * KERNEL_COEFF_5 * (1.0 - u) * (1.0 - u) * (1.0 - u);
}
/* normalisation using mass */
aij = P[j].Mass*wk/density;
/* normalisation using volume */
/* !!! si on utilise, il faut stoquer une nouvelle variable : OldDensity, car density est modifié plus bas... */
//aij = P[j].Mass/SphP[j].Density*wk/volume;
/* metal injection */
for(k=0;k<NELEMENTS;k++)
{
mass_k = SphP[j].Metal[k]*P[j].Mass; /* mass of elt k */
SphP[j].Metal[k] = ( mass_k + aij*ejectedEltMass[k] )/( P[j].Mass + aij*ejectedGasMass );
}
/* new mass */
NewMass = P[j].Mass + aij*ejectedGasMass;
/* new velocity */
vj2 = 0;
for(k=0;k<3;k++)
vj2 += SphP[j].VelPred[k]*SphP[j].VelPred[k];
fv = sqrt( (P[j].Mass/NewMass) + aij*(ejectedGasMass/NewMass) * (vi2/vj2) );
for(k=0;k<3;k++)
{
DeltaVel[k] = fv*SphP[j].VelPred[k] - SphP[j].VelPred[k];
SphP[j].VelPred[k] += DeltaVel[k];
P[j].Vel [k] += DeltaVel[k];
}
/* spec energy at current step */
EgySpec = SphP[j].EntropyPred / GAMMA_MINUS1 * pow(SphP[j].Density*a3inv, GAMMA_MINUS1);
/* new egyspec */
NewEgySpec = (EgySpec )*(P[j].Mass/NewMass);
/* new density */
SphP[j].Density = SphP[j].Density*NewMass/P[j].Mass;
/* new entropy */
DeltaEntropy = GAMMA_MINUS1*NewEgySpec/pow(SphP[j].Density*a3inv, GAMMA_MINUS1) - SphP[j].EntropyPred;
SphP[j].EntropyPred += DeltaEntropy;
SphP[j].Entropy += DeltaEntropy;
#ifdef CHIMIE_THERMAL_FEEDBACK
SphP[j].DeltaEgySpec += (1.-All.ChimieKineticFeedbackFraction)*(ejectedGasMass*ejectedEgySpec)* aij/NewMass;
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
p = (All.ChimieKineticFeedbackFraction*ejectedEgySpec*ejectedGasMass)/(0.5*ngbmass*All.ChimieWindSpeed*All.ChimieWindSpeed);
double r;
r = get_Chimie_random_number(P[j].ID+id);
if ( r < p) /* we should maybe have a 2d table here... */
{
if (SphP[j].WindTime < (All.Time-All.ChimieWindTime)) /* not a wind particle */
{
SphP[j].WindFlag = 1;
SphP[j].WindTime = All.Time;
}
}
#endif
#ifdef CHECK_ENTROPY_SIGN
if ((SphP[j].EntropyPred < 0)||(SphP[j].Entropy < 0))
{
printf("\ntask=%d: entropy less than zero in chimie_evaluate !\n", ThisTask);
printf("ID=%d Entropy=%g EntropyPred=%g DeltaEntropy=%g\n",P[j].ID,SphP[j].Entropy,SphP[j].EntropyPred,DeltaEntropy);
fflush(stdout);
endrun(777003);
}
#endif
/* store mass diff. */
SphP[j].dMass += NewMass-P[j].Mass;
}
}
}
while(startnode >= 0);
/* Now collect the result at the right place */
if(mode == 0)
{
// for(k = 0; k < 3; k++)
// SphP[target].HydroAccel[k] = acc[k];
// SphP[target].DtEntropy = dtEntropy;
//#ifdef FEEDBACK
// SphP[target].DtEgySpecFeedback = dtEgySpecFeedback;
//#endif
// SphP[target].MaxSignalVel = maxSignalVel;
//#ifdef COMPUTE_VELOCITY_DISPERSION
// for(k = 0; k < VELOCITY_DISPERSION_SIZE; k++)
// SphP[target].VelocityDispersion[k] = VelocityDispersion[k];
//#endif
}
else
{
// for(k = 0; k < 3; k++)
// HydroDataResult[target].Acc[k] = acc[k];
// HydroDataResult[target].DtEntropy = dtEntropy;
//#ifdef FEEDBACK
// HydroDataResult[target].DtEgySpecFeedback = dtEgySpecFeedback;
//#endif
// HydroDataResult[target].MaxSignalVel = maxSignalVel;
//#ifdef COMPUTE_VELOCITY_DISPERSION
// for(k = 0; k < VELOCITY_DISPERSION_SIZE; k++)
// HydroDataResult[target].VelocityDispersion[k] = VelocityDispersion[k];
//#endif
}
}
/*! This is a comparison kernel for a sort routine, which is used to group
* particles that are going to be exported to the same CPU.
*/
int chimie_compare_key(const void *a, const void *b)
{
if(((struct chimiedata_in *) a)->Task < (((struct chimiedata_in *) b)->Task))
return -1;
if(((struct chimiedata_in *) a)->Task > (((struct chimiedata_in *) b)->Task))
return +1;
return 0;
}
#endif
diff --git a/init.c b/init.c
index 7f52397..210bf14 100644
--- a/init.c
+++ b/init.c
@@ -1,587 +1,597 @@
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <mpi.h>
#include "allvars.h"
#include "proto.h"
/*! \file init.c
* \brief Code for initialisation of a simulation from initial conditions
*/
/*! This function reads the initial conditions, and allocates storage for the
* tree. Various variables of the particle data are initialised and An intial
* domain decomposition is performed. If SPH particles are present, the inial
* SPH smoothing lengths are determined.
*/
void init(void)
{
int i, j;
double a3;
#ifdef SFR
double Mgas=0,sum_Mgas=0;
int nstars=0;
int *numlist;
#endif
All.Time = All.TimeBegin;
switch (All.ICFormat)
{
case 1:
#if (MAKEGLASS > 1)
seed_glass();
#else
read_ic(All.InitCondFile);
#endif
break;
case 2:
case 3:
read_ic(All.InitCondFile);
break;
default:
if(ThisTask == 0)
printf("ICFormat=%d not supported.\n", All.ICFormat);
endrun(0);
}
All.Time = All.TimeBegin;
All.Ti_Current = 0;
if(All.ComovingIntegrationOn)
{
All.Timebase_interval = (log(All.TimeMax) - log(All.TimeBegin)) / TIMEBASE;
a3 = All.Time * All.Time * All.Time;
}
else
{
All.Timebase_interval = (All.TimeMax - All.TimeBegin) / TIMEBASE;
a3 = 1;
}
if (ThisTask==0)
printf("\nMinimum Time Step (Timebase_interval) = %g \n\n", All.Timebase_interval);
set_softenings();
All.NumCurrentTiStep = 0; /* setup some counters */
All.SnapshotFileCount = 0;
if(RestartFlag == 2)
All.SnapshotFileCount = atoi(All.InitCondFile + strlen(All.InitCondFile) - 3) + 1;
All.TotNumOfForces = 0;
All.NumForcesSinceLastDomainDecomp = 0;
if(All.ComovingIntegrationOn)
if(All.PeriodicBoundariesOn == 1)
check_omega();
All.TimeLastStatistics = All.TimeBegin - All.TimeBetStatistics;
#ifdef AGN_ACCRETION
All.TimeLastAccretion = All.TimeBegin - All.TimeBetAccretion;
All.LastMTotInRa = 0;
#endif
#ifdef BONDI_ACCRETION
All.BondiTimeLast = All.TimeBegin - All.BondiTimeBet;
#endif
#ifdef BUBBLES
All.EnergyBubbles=0;
#endif
if(All.ComovingIntegrationOn) /* change to new velocity variable */
{
for(i = 0; i < NumPart; i++)
for(j = 0; j < 3; j++)
P[i].Vel[j] *= sqrt(All.Time) * All.Time;
}
for(i = 0; i < NumPart; i++) /* start-up initialization */
{
for(j = 0; j < 3; j++)
P[i].GravAccel[j] = 0;
#ifdef PMGRID
for(j = 0; j < 3; j++)
P[i].GravPM[j] = 0;
#endif
P[i].Ti_endstep = 0;
P[i].Ti_begstep = 0;
P[i].OldAcc = 0;
P[i].GravCost = 1;
P[i].Potential = 0;
#ifdef PARTICLE_FLAG
P[i].Flag = 0;
#endif
}
#ifdef PMGRID
All.PM_Ti_endstep = All.PM_Ti_begstep = 0;
#endif
#ifdef FLEXSTEPS
All.PresentMinStep = TIMEBASE;
for(i = 0; i < NumPart; i++) /* start-up initialization */
{
P[i].FlexStepGrp = (int) (TIMEBASE * get_random_number(P[i].ID));
}
#endif
for(i = 0; i < N_gas; i++) /* initialize sph_properties */
{
for(j = 0; j < 3; j++)
{
SphP[i].VelPred[j] = P[i].Vel[j];
SphP[i].HydroAccel[j] = 0;
}
SphP[i].DtEntropy = 0;
#ifdef STELLAR_FLUX
SphP[i].EnergyFlux = 0.;
#endif
#ifdef AGN_HEATING
SphP[i].EgySpecAGNHeat = 0.;
SphP[i].DtEgySpecAGNHeat = 0.;
#endif
#ifdef MULTIPHASE
#ifdef COUNT_COLLISIONS
SphP[i].StickyCollisionNumber = 0;
#endif
#endif
#ifdef FEEDBACK
SphP[i].EgySpecFeedback = 0.;
SphP[i].DtEgySpecFeedback = 0.;
SphP[i].EnergySN = 0.;
SphP[i].EnergySNrem = 0.;
SphP[i].TimeSN = 0.;
for(j = 0; j < 3; j++)
{
SphP[i].FeedbackVel[j] = 0;
}
#endif
#ifdef FEEDBACK_WIND
for(j = 0; j < 3; j++)
{
SphP[i].FeedbackWindVel[j] = 0;
}
#endif
#ifdef OUTPUTOPTVAR
SphP[i].OptVar = 0.;
#endif
#ifdef COMPUTE_VELOCITY_DISPERSION
for(j = 0; j < VELOCITY_DISPERSION_SIZE; j++)
SphP[i].VelocityDispersion[j] = 0.;
#endif
if(RestartFlag == 0)
{
SphP[i].Hsml = 0;
SphP[i].Density = -1;
}
#ifdef MULTIPHASE
/* here, we set the Phase, according to the SpecificEnergy and not Entropy */
if (SphP[i].Entropy > All.CriticalEgySpec)
SphP[i].Phase = GAS_SPH; /* warmer phase */
else
{
if (SphP[i].Entropy >= All.CriticalNonCollisionalEgySpec)
SphP[i].Phase = GAS_STICKY;
else
SphP[i].Phase = GAS_DARK;
}
SphP[i].StickyFlag = 0;
SphP[i].StickyTime = All.Time;
//SphP[i].StickyTime = All.Time + All.StickyIdleTime*get_random_number(P[i].ID);
#endif
#ifdef SFR
Mgas += P[i].Mass;
#endif
}
#ifdef SFR
RearrangeParticlesFlag=0;
if (All.StarFormationStarMass==0)
{
/* compute the mean gas mass */
MPI_Allreduce(&Mgas, &sum_Mgas, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
All.StarFormationStarMass = (sum_Mgas/All.TotN_gas) / All.StarFormationNStarsFromGas;
}
for(i = 0; i < NumPart; i++) /* initialize st_properties */
{
if (P[i].Type==ST)
nstars++;
#ifdef STELLAR_PROP
if (P[i].Type==ST)
{
if (RestartFlag==0) /* only if starting from scratch */
{
+
+#ifndef CHIMIE_INPUT_ALL
P[i].StPIdx = i;
StP[P[i].StPIdx].FormationTime = 0; /* bad */
StP[P[i].StPIdx].InitialMass = 0; /* bad */
StP[P[i].StPIdx].IDProj = P[i].ID;
StP[P[i].StPIdx].Hsml = 0;
StP[P[i].StPIdx].Density = -1;
for(j = 0; j < NELEMENTS; j++)
StP[P[i].StPIdx].Metal[j] = 0.;
StP[P[i].StPIdx].Flag = 0; /*obsolete*/
+#else /* here, we restart for a file already processed by gadget */
+ P[i].StPIdx = i-N_gas;
+ StP[P[i].StPIdx].Flag = 0; /*obsolete*/
+#endif
+
+
}
if (RestartFlag==2) /* start from snapshot */
{
P[i].StPIdx = i-N_gas;
StP[P[i].StPIdx].Flag = 0; /*obsolete*/
}
StP[P[i].StPIdx].PIdx = i;
#ifdef CHECK_ID_CORRESPONDENCE
StP[P[i].StPIdx].ID = P[i].ID;
#endif
}
//else
// P[i].StPIdx = -1; /* shoud be set, however, may be a problem in domain.c --> must be corrected */
#endif
#ifdef CHIMIE
if (P[i].Type==0)
{
if (RestartFlag==0 && header.flag_metals==0) /* only if starting from scratch and metal block not present */
{
for(j = 0; j < NELEMENTS; j++)
{
SphP[i].Metal[j] = (pow(10,All.InitGasMetallicity)-1e-10)*get_SolarAbundance(j);
//if (j==FE)
// SphP[i].Metal[j] = (pow(10,All.InitGasMetallicity)-1e-10)*All.CoolingParameters_FeHSolar;
//else
// SphP[i].Metal[j] = 0;
}
}
#ifdef CHIMIE_THERMAL_FEEDBACK
SphP[i].DeltaEgySpec = 0;
SphP[i].ThermalTime = All.TimeBegin-2*All.ChimieThermalTime;
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
SphP[i].WindTime = All.TimeBegin-2*All.ChimieWindTime;
SphP[i].WindFlag = 0;
#endif
}
#endif /* chimie */
}
/* here, we would like to reduce N_stars to TotN_stars */
/* MPI_Allreduce(&N_stars, &All.TotN_stars, 1, MPI_LONG_LONG, MPI_SUM, MPI_COMM_WORLD); does not works */
numlist = malloc(NTask * sizeof(int) * NTask);
MPI_Allgather(&N_stars, 1, MPI_INT, numlist, 1, MPI_INT, MPI_COMM_WORLD);
for(i = 0, All.TotN_stars = 0; i < NTask; i++)
All.TotN_stars += numlist[i];
free(numlist);
if(ThisTask == 0)
{
printf("Total number of star particles : %d%09d\n\n",(int) (All.TotN_stars / 1000000000), (int) (All.TotN_stars % 1000000000));
fflush(stdout);
}
#endif /*SFR*/
ngb_treeallocate(MAX_NGB);
force_treeallocate(All.TreeAllocFactor * All.MaxPart, All.MaxPart);
All.NumForcesSinceLastDomainDecomp = 1 + All.TotNumPart * All.TreeDomainUpdateFrequency;
Flag_FullStep = 1; /* to ensure that Peano-Hilber order is done */
domain_Decomposition(); /* do initial domain decomposition (gives equal numbers of particles) */
ngb_treebuild(); /* will build tree */
setup_smoothinglengths();
#ifdef CHIMIE
+#ifndef CHIMIE_INPUT_ALL
stars_setup_smoothinglengths();
+#endif
#endif
TreeReconstructFlag = 1;
/* at this point, the entropy variable normally contains the
* internal energy, read in from the initial conditions file, unless the file
* explicitly signals that the initial conditions contain the entropy directly.
* Once the density has been computed, we can convert thermal energy to entropy.
*/
#ifndef ISOTHERM_EQS
if(header.flag_entropy_instead_u == 0)
{
for(i = 0; i < N_gas; i++)
#ifdef MULTIPHASE
{
switch(SphP[i].Phase)
{
case GAS_SPH:
SphP[i].Entropy = GAMMA_MINUS1 * SphP[i].Entropy / pow(SphP[i].Density / a3, GAMMA_MINUS1);
break;
case GAS_STICKY:
break;
case GAS_DARK:
SphP[i].Entropy = -SphP[i].Entropy;
break;
}
}
#else
SphP[i].Entropy = GAMMA_MINUS1 * SphP[i].Entropy / pow(SphP[i].Density / a3, GAMMA_MINUS1);
#endif
}
#endif
#ifdef ENTROPYPRED
for(i = 0; i < N_gas; i++)
SphP[i].EntropyPred = SphP[i].Entropy;
#endif
}
/*! This routine computes the mass content of the box and compares it to the
* specified value of Omega-matter. If discrepant, the run is terminated.
*/
void check_omega(void)
{
double mass = 0, masstot, omega;
int i;
for(i = 0; i < NumPart; i++)
mass += P[i].Mass;
MPI_Allreduce(&mass, &masstot, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
omega =
masstot / (All.BoxSize * All.BoxSize * All.BoxSize) / (3 * All.Hubble * All.Hubble / (8 * M_PI * All.G));
if(fabs(omega - All.Omega0) > 1.0e-3)
{
if(ThisTask == 0)
{
printf("\n\nI've found something odd!\n");
printf
("The mass content accounts only for Omega=%g,\nbut you specified Omega=%g in the parameterfile.\n",
omega, All.Omega0);
printf("\nI better stop.\n");
fflush(stdout);
}
endrun(1);
}
}
/*! This function is used to find an initial smoothing length for each SPH
* particle. It guarantees that the number of neighbours will be between
* desired_ngb-MAXDEV and desired_ngb+MAXDEV. For simplicity, a first guess
* of the smoothing length is provided to the function density(), which will
* then iterate if needed to find the right smoothing length.
*/
void setup_smoothinglengths(void)
{
int i, no, p;
if(RestartFlag == 0)
{
for(i = 0; i < N_gas; i++)
{
no = Father[i];
while(10 * All.DesNumNgb * P[i].Mass > Nodes[no].u.d.mass)
{
p = Nodes[no].u.d.father;
if(p < 0)
break;
no = p;
}
#ifndef TWODIMS
SphP[i].Hsml =
pow(3.0 / (4 * M_PI) * All.DesNumNgb * P[i].Mass / Nodes[no].u.d.mass, 1.0 / 3) * Nodes[no].len;
#else
SphP[i].Hsml =
pow(1.0 / (M_PI) * All.DesNumNgb * P[i].Mass / Nodes[no].u.d.mass, 1.0 / 2) * Nodes[no].len;
#endif
}
}
density(0);
}
#ifdef CHIMIE
/*! This function is used to find an initial smoothing length for each SPH
* particle. It guarantees that the number of neighbours will be between
* desired_ngb-MAXDEV and desired_ngb+MAXDEV. For simplicity, a first guess
* of the smoothing length is provided to the function density(), which will
* then iterate if needed to find the right smoothing length.
*/
void stars_setup_smoothinglengths(void)
{
int i, no, p;
if(RestartFlag == 0)
{
for(i = 0; i < NumPart; i++)
{
if(P[i].Type == ST)
{
no = Father[i];
while(10 * All.DesNumNgb * P[i].Mass > Nodes[no].u.d.mass)
{
p = Nodes[no].u.d.father;
if(p < 0)
break;
no = p;
}
#ifndef TWODIMS
StP[P[i].StPIdx].Hsml =
pow(3.0 / (4 * M_PI) * All.DesNumNgb * P[i].Mass / Nodes[no].u.d.mass, 1.0 / 3) * Nodes[no].len;
#else
StP[P[i].StPIdx].Hsml =
pow(1.0 / (M_PI) * All.DesNumNgb * P[i].Mass / Nodes[no].u.d.mass, 1.0 / 2) * Nodes[no].len;
#endif
}
}
}
stars_density();
}
#endif
/*! If the code is run in glass-making mode, this function populates the
* simulation box with a Poisson sample of particles.
*/
#if (MAKEGLASS > 1)
void seed_glass(void)
{
int i, k, n_for_this_task;
double Range[3], LowerBound[3];
double drandom, partmass;
long long IDstart;
All.TotNumPart = MAKEGLASS;
partmass = All.Omega0 * (3 * All.Hubble * All.Hubble / (8 * M_PI * All.G))
* (All.BoxSize * All.BoxSize * All.BoxSize) / All.TotNumPart;
All.MaxPart = All.PartAllocFactor * (All.TotNumPart / NTask); /* sets the maximum number of particles that may */
allocate_memory();
header.npartTotal[1] = All.TotNumPart;
header.mass[1] = partmass;
if(ThisTask == 0)
{
printf("\nGlass initialising\nPartMass= %g\n", partmass);
printf("TotNumPart= %d%09d\n\n",
(int) (All.TotNumPart / 1000000000), (int) (All.TotNumPart % 1000000000));
}
/* set the number of particles assigned locally to this task */
n_for_this_task = All.TotNumPart / NTask;
if(ThisTask == NTask - 1)
n_for_this_task = All.TotNumPart - (NTask - 1) * n_for_this_task;
NumPart = 0;
IDstart = 1 + (All.TotNumPart / NTask) * ThisTask;
/* split the temporal domain into Ntask slabs in z-direction */
Range[0] = Range[1] = All.BoxSize;
Range[2] = All.BoxSize / NTask;
LowerBound[0] = LowerBound[1] = 0;
LowerBound[2] = ThisTask * Range[2];
srand48(ThisTask);
for(i = 0; i < n_for_this_task; i++)
{
for(k = 0; k < 3; k++)
{
drandom = drand48();
P[i].Pos[k] = LowerBound[k] + Range[k] * drandom;
P[i].Vel[k] = 0;
}
P[i].Mass = partmass;
P[i].Type = 1;
P[i].ID = IDstart + i;
NumPart++;
}
}
#endif
diff --git a/io.c b/io.c
index 07aac15..b9948e0 100644
--- a/io.c
+++ b/io.c
@@ -1,1610 +1,1622 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <mpi.h>
#include <errno.h>
#ifdef HAVE_HDF5
#include <hdf5.h>
#endif
#include "allvars.h"
#include "proto.h"
/*! \file io.c
* \brief Routines for producing a snapshot file on disk.
*/
static int n_type[6];
static long long ntot_type_all[6];
/*! This function writes a snapshot of the particle distribution to one or
* several files using the selected file format. If NumFilesPerSnapshot>1,
* the snapshot is distributed onto several files, several of them can be
* written simultaneously (up to NumFilesWrittenInParallel). Each file
* contains data from a group of processors.
*/
void savepositions(int num)
{
double t0, t1;
char buf[500];
int i, j, *temp, n, filenr, gr, ngroups, masterTask, lastTask;
t0 = second();
if(ThisTask == 0)
printf("\nwriting snapshot file... \n");
#if defined(SFR) || defined(BLACK_HOLES)
rearrange_particle_sequence();
/* ensures that new tree will be constructed */
All.NumForcesSinceLastDomainDecomp = 1 + All.TreeDomainUpdateFrequency * All.TotNumPart;
#endif
if(NTask < All.NumFilesPerSnapshot)
{
if(ThisTask == 0)
printf("Fatal error.\nNumber of processors must be larger or equal than All.NumFilesPerSnapshot.\n");
endrun(0);
}
if(All.SnapFormat < 1 || All.SnapFormat > 3)
{
if(ThisTask == 0)
printf("Unsupported File-Format\n");
endrun(0);
}
#ifndef HAVE_HDF5
if(All.SnapFormat == 3)
{
if(ThisTask == 0)
printf("Code wasn't compiled with HDF5 support enabled!\n");
endrun(0);
}
#endif
/* determine global and local particle numbers */
for(n = 0; n < 6; n++)
n_type[n] = 0;
for(n = 0; n < NumPart; n++)
n_type[P[n].Type]++;
#ifdef CHECK_TYPE_DURING_IO
if (n_type[0]!=N_gas)
{
printf("(%d) n_type[0]=%d N_gas=%d !!!\n\n",ThisTask,n_type[0],N_gas);
endrun(111000);
}
#ifdef SFR
if (n_type[ST]!=N_stars)
{
printf("(%d) n_type[ST]=%d N_gas=%d !!!\n\n",ThisTask,n_type[ST],N_stars);
endrun(111001);
}
#endif
#endif
/* because ntot_type_all[] is of type `long long', we cannot do a simple
* MPI_Allreduce() to sum the total particle numbers
*/
temp = malloc(NTask * 6 * sizeof(int));
MPI_Allgather(n_type, 6, MPI_INT, temp, 6, MPI_INT, MPI_COMM_WORLD);
for(i = 0; i < 6; i++)
{
ntot_type_all[i] = 0;
for(j = 0; j < NTask; j++)
ntot_type_all[i] += temp[j * 6 + i];
}
free(temp);
/* assign processors to output files */
distribute_file(All.NumFilesPerSnapshot, 0, 0, NTask - 1, &filenr, &masterTask, &lastTask);
fill_Tab_IO_Labels();
if(All.NumFilesPerSnapshot > 1)
sprintf(buf, "%s%s_%04d.%d", All.OutputDir, All.SnapshotFileBase, num, filenr);
else
sprintf(buf, "%s%s_%04d", All.OutputDir, All.SnapshotFileBase, num);
ngroups = All.NumFilesPerSnapshot / All.NumFilesWrittenInParallel;
if((All.NumFilesPerSnapshot % All.NumFilesWrittenInParallel))
ngroups++;
for(gr = 0; gr < ngroups; gr++)
{
if((filenr / All.NumFilesWrittenInParallel) == gr) /* ok, it's this processor's turn */
write_file(buf, masterTask, lastTask);
MPI_Barrier(MPI_COMM_WORLD);
}
if(ThisTask == 0)
printf("done with snapshot.\n");
t1 = second();
All.CPU_Snapshot += timediff(t0, t1);
}
/*! This function fills the write buffer with particle data. New output blocks
* can in principle be added here.
*/
void fill_write_buffer(enum iofields blocknr, int *startindex, int pc, int type)
{
int n, k, pindex;
float *fp;
#ifdef LONGIDS
long long *ip;
#else
int *ip;
#endif
#ifdef PERIODIC
FLOAT boxSize;
#endif
#ifdef PMGRID
double dt_gravkick_pm = 0;
#endif
double dt_gravkick, dt_hydrokick, a3inv = 1, fac1, fac2;
if(All.ComovingIntegrationOn)
{
a3inv = 1 / (All.Time * All.Time * All.Time);
fac1 = 1 / (All.Time * All.Time);
fac2 = 1 / pow(All.Time, 3 * GAMMA - 2);
}
else
a3inv = fac1 = fac2 = 1;
#ifdef PMGRID
if(All.ComovingIntegrationOn)
dt_gravkick_pm =
get_gravkick_factor(All.PM_Ti_begstep,
All.Ti_Current) -
get_gravkick_factor(All.PM_Ti_begstep, (All.PM_Ti_begstep + All.PM_Ti_endstep) / 2);
else
dt_gravkick_pm = (All.Ti_Current - (All.PM_Ti_begstep + All.PM_Ti_endstep) / 2) * All.Timebase_interval;
#endif
fp = CommBuffer;
ip = CommBuffer;
pindex = *startindex;
switch (blocknr)
{
case IO_POS: /* positions */
for(n = 0; n < pc; pindex++)
if(P[pindex].Type == type)
{
for(k = 0; k < 3; k++)
{
fp[k] = P[pindex].Pos[k];
#ifdef PERIODIC
boxSize = All.BoxSize;
#ifdef LONG_X
if(k == 0)
boxSize = All.BoxSize * LONG_X;
#endif
#ifdef LONG_Y
if(k == 1)
boxSize = All.BoxSize * LONG_Y;
#endif
#ifdef LONG_Z
if(k == 2)
boxSize = All.BoxSize * LONG_Z;
#endif
while(fp[k] < 0)
fp[k] += boxSize;
while(fp[k] >= boxSize)
fp[k] -= boxSize;
#endif
}
n++;
fp += 3;
}
break;
case IO_VEL: /* velocities */
for(n = 0; n < pc; pindex++)
if(P[pindex].Type == type)
{
if(All.ComovingIntegrationOn)
{
dt_gravkick =
get_gravkick_factor(P[pindex].Ti_begstep,
All.Ti_Current) -
get_gravkick_factor(P[pindex].Ti_begstep,
(P[pindex].Ti_begstep + P[pindex].Ti_endstep) / 2);
dt_hydrokick =
get_hydrokick_factor(P[pindex].Ti_begstep,
All.Ti_Current) -
get_hydrokick_factor(P[pindex].Ti_begstep,
(P[pindex].Ti_begstep + P[pindex].Ti_endstep) / 2);
}
else
dt_gravkick = dt_hydrokick =
(All.Ti_Current - (P[pindex].Ti_begstep + P[pindex].Ti_endstep) / 2) * All.Timebase_interval;
for(k = 0; k < 3; k++)
{
fp[k] = P[pindex].Vel[k] + P[pindex].GravAccel[k] * dt_gravkick;
if(P[pindex].Type == 0)
{
fp[k] += SphP[pindex].HydroAccel[k] * dt_hydrokick;
}
}
#ifdef PMGRID
for(k = 0; k < 3; k++)
fp[k] += P[pindex].GravPM[k] * dt_gravkick_pm;
#endif
for(k = 0; k < 3; k++)
fp[k] *= sqrt(a3inv);
n++;
fp += 3;
}
break;
case IO_ID: /* particle ID */
for(n = 0; n < pc; pindex++)
if(P[pindex].Type == type)
{
*ip++ = P[pindex].ID;
n++;
}
break;
case IO_MASS: /* particle mass */
for(n = 0; n < pc; pindex++)
if(P[pindex].Type == type)
{
*fp++ = P[pindex].Mass;
n++;
}
break;
case IO_U: /* internal energy */
for(n = 0; n < pc; pindex++)
if(P[pindex].Type == type)
{
#ifdef ISOTHERM_EQS
*fp++ = SphP[pindex].Entropy;
#else
#ifdef MULTIPHASE
switch(SphP[pindex].Phase)
{
case GAS_SPH:
*fp++ = dmax(All.MinEgySpec,SphP[pindex].Entropy / GAMMA_MINUS1 * pow(SphP[pindex].Density * a3inv, GAMMA_MINUS1));
break;
case GAS_STICKY:
*fp++ = SphP[pindex].Entropy;
break;
case GAS_DARK:
*fp++ = -SphP[pindex].Entropy;
break;
}
#else
*fp++ =
dmax(All.MinEgySpec,
SphP[pindex].Entropy / GAMMA_MINUS1 * pow(SphP[pindex].Density * a3inv, GAMMA_MINUS1));
#endif
#endif
n++;
}
break;
case IO_RHO: /* density */
for(n = 0; n < pc; pindex++)
if(P[pindex].Type == type)
{
*fp++ = SphP[pindex].Density;
n++;
}
break;
case IO_HSML: /* SPH smoothing length */
for(n = 0; n < pc; pindex++)
if(P[pindex].Type == type)
{
*fp++ = SphP[pindex].Hsml;
n++;
}
break;
/*********************************************/
/* here it is the end of the minimal output */
/*********************************************/
case IO_STAR_FORMATIONTIME: /* stellar formation time */
#ifdef OUTPUTSTELLAR_PROP
for(n = 0; n < pc; pindex++)
if(P[pindex].Type == type)
{
*fp++ = StP[P[pindex].StPIdx].FormationTime;
n++;
}
#endif
break;
case IO_INITIAL_MASS: /* stellar formation time */
#ifdef OUTPUTSTELLAR_PROP
for(n = 0; n < pc; pindex++)
if(P[pindex].Type == type)
{
*fp++ = StP[P[pindex].StPIdx].InitialMass;
n++;
}
#endif
break;
case IO_STAR_IDPROJ: /* stellar projenitor */
#ifdef OUTPUTSTELLAR_PROP
for(n = 0; n < pc; pindex++)
if(P[pindex].Type == type)
{
*ip++ = StP[P[pindex].StPIdx].IDProj;
n++;
}
#endif
break;
case IO_STAR_RHO: /* gas density around a star */
#ifdef OUTPUTSTELLAR_PROP
for(n = 0; n < pc; pindex++)
if(P[pindex].Type == type)
{
*fp++ = StP[P[pindex].StPIdx].Density;
n++;
}
#endif
break;
case IO_STAR_HSML: /* SPH smoothing length of a star */
#ifdef OUTPUTSTELLAR_PROP
for(n = 0; n < pc; pindex++)
if(P[pindex].Type == type)
{
*fp++ = StP[P[pindex].StPIdx].Hsml;
n++;
}
#endif
break;
case IO_STAR_METALS: /* stars metal */
#ifdef OUTPUTSTELLAR_PROP
for(n = 0; n < pc; pindex++)
if(P[pindex].Type == type)
{
for(k = 0; k < NELEMENTS; k++)
{
fp[k] = StP[P[pindex].StPIdx].Metal[k];
}
n++;
fp += NELEMENTS;
}
#endif
break;
case IO_METALS: /* gas metal */
#ifdef OUTPUTSTELLAR_PROP
for(n = 0; n < pc; pindex++)
if(P[pindex].Type == type)
{
for(k = 0; k < NELEMENTS; k++)
{
fp[k] = SphP[pindex].Metal[k];
}
n++;
fp += NELEMENTS;
}
#endif
break;
case IO_POT: /* gravitational potential */
#ifdef OUTPUTPOTENTIAL
for(n = 0; n < pc; pindex++)
if(P[pindex].Type == type)
{
*fp++ = P[pindex].Potential;
n++;
}
#endif
break;
case IO_ACCEL: /* acceleration */
#ifdef OUTPUTACCELERATION
for(n = 0; n < pc; pindex++)
if(P[pindex].Type == type)
{
for(k = 0; k < 3; k++)
fp[k] = fac1 * P[pindex].GravAccel[k];
#ifdef PMGRID
for(k = 0; k < 3; k++)
fp[k] += fac1 * P[pindex].GravPM[k];
#endif
if(P[pindex].Type == 0)
for(k = 0; k < 3; k++)
{
fp[k] += fac2 * SphP[pindex].HydroAccel[k];
}
fp += 3;
n++;
}
#endif
break;
case IO_DTENTR: /* rate of change of entropy */
#ifdef OUTPUTCHANGEOFENTROPY
for(n = 0; n < pc; pindex++)
if(P[pindex].Type == type)
{
*fp++ = SphP[pindex].DtEntropy;
n++;
}
#endif
break;
case IO_TSTP: /* timestep */
#ifdef OUTPUTTIMESTEP
for(n = 0; n < pc; pindex++)
if(P[pindex].Type == type)
{
*fp++ = (P[pindex].Ti_endstep - P[pindex].Ti_begstep) * All.Timebase_interval;
n++;
}
#endif
break;
case IO_ERADSTICKY: /* sticky radiated energy */
#ifdef OUTPUTERADSTICKY
/* obsolete */
#endif
break;
case IO_ERADFEEDBACK: /* feedback injected energy */
#ifdef OUTPUTERADFEEDBACK
for(n = 0; n < pc; pindex++)
if(P[pindex].Type == type)
{
*fp++ = SphP[pindex].EgySpecFeedback;
n++;
}
#endif
break;
case IO_ENERGYFLUX: /* energyflux */
#ifdef OUTPUTENERGYFLUX
for(n = 0; n < pc; pindex++)
if(P[pindex].Type == type)
{
*fp++ = SphP[pindex].EnergyFlux;
n++;
}
#endif
break;
case IO_OPTVAR: /* optional variable */
#ifdef OUTPUTOPTVAR
for(n = 0; n < pc; pindex++)
if(P[pindex].Type == type)
{
*fp++ = SphP[pindex].OptVar;
n++;
}
#endif
break;
}
*startindex = pindex;
}
/*! This function tells the size of one data entry in each of the blocks
* defined for the output file. If one wants to add a new output-block, this
* function should be augmented accordingly.
*/
int get_bytes_per_blockelement(enum iofields blocknr)
{
int bytes_per_blockelement = 0;
switch (blocknr)
{
case IO_POS:
case IO_VEL:
case IO_ACCEL:
bytes_per_blockelement = 3 * sizeof(float);
break;
case IO_ID:
#ifdef LONGIDS
bytes_per_blockelement = sizeof(long long);
#else
bytes_per_blockelement = sizeof(int);
#endif
break;
case IO_MASS:
case IO_U:
case IO_RHO:
case IO_HSML:
case IO_POT:
case IO_DTENTR:
case IO_TSTP:
case IO_ERADSPH:
case IO_ERADSTICKY:
case IO_ERADFEEDBACK:
case IO_ENERGYFLUX:
case IO_OPTVAR:
bytes_per_blockelement = sizeof(float);
break;
case IO_STAR_FORMATIONTIME:
case IO_INITIAL_MASS:
case IO_STAR_RHO:
case IO_STAR_HSML:
bytes_per_blockelement = sizeof(float);
break;
case IO_METALS:
#ifdef CHIMIE
case IO_STAR_METALS:
bytes_per_blockelement = NELEMENTS*sizeof(float);
#endif
break;
case IO_STAR_IDPROJ:
#ifdef LONGIDS
bytes_per_blockelement = sizeof(long long);
#else
bytes_per_blockelement = sizeof(int);
#endif
break;
}
return bytes_per_blockelement;
}
/*! This function returns the type of the data contained in a given block of
* the output file. If one wants to add a new output-block, this function
* should be augmented accordingly.
*/
int get_datatype_in_block(enum iofields blocknr)
{
int typekey;
switch (blocknr)
{
case IO_ID:
case IO_STAR_IDPROJ:
#ifdef LONGIDS
typekey = 2; /* native long long */
#else
typekey = 0; /* native int */
#endif
break;
default:
typekey = 1; /* native float */
break;
}
return typekey;
}
/*! This function informs about the number of elements stored per particle for
* the given block of the output file. If one wants to add a new
* output-block, this function should be augmented accordingly.
*/
int get_values_per_blockelement(enum iofields blocknr)
{
int values = 0;
switch (blocknr)
{
case IO_POS:
case IO_VEL:
case IO_ACCEL:
values = 3;
break;
case IO_ID:
case IO_MASS:
case IO_U:
case IO_RHO:
case IO_HSML:
case IO_POT:
case IO_DTENTR:
case IO_TSTP:
case IO_ERADSPH:
case IO_ERADSTICKY:
case IO_ERADFEEDBACK:
case IO_ENERGYFLUX:
case IO_OPTVAR:
case IO_STAR_FORMATIONTIME:
case IO_INITIAL_MASS:
case IO_STAR_IDPROJ:
case IO_STAR_RHO:
case IO_STAR_HSML:
values = 1;
break;
case IO_METALS:
#ifdef CHIMIE
case IO_STAR_METALS:
values = NELEMENTS;
#endif
break;
}
return values;
}
/*! This function determines how many particles there are in a given block,
* based on the information in the header-structure. It also flags particle
* types that are present in the block in the typelist array. If one wants to
* add a new output-block, this function should be augmented accordingly.
*/
int get_particles_in_block(enum iofields blocknr, int *typelist)
{
int i, nall, ntot_withmasses, ngas, nstars;
nall = 0;
ntot_withmasses = 0;
for(i = 0; i < 6; i++)
{
typelist[i] = 0;
if(header.npart[i] > 0)
{
nall += header.npart[i];
typelist[i] = 1;
}
if(All.MassTable[i] == 0)
ntot_withmasses += header.npart[i];
}
ngas = header.npart[0];
#if defined(SFR) || defined(STELLAR_PROP)
nstars = header.npart[ST];
#else
nstars = header.npart[4];
#endif
switch (blocknr)
{
case IO_POS:
case IO_VEL:
case IO_ACCEL:
case IO_TSTP:
case IO_ID:
case IO_POT:
return nall;
break;
case IO_MASS:
for(i = 0; i < 6; i++)
{
typelist[i] = 0;
if(All.MassTable[i] == 0 && header.npart[i] > 0)
typelist[i] = 1;
}
return ntot_withmasses;
break;
case IO_U:
case IO_RHO:
case IO_HSML:
case IO_DTENTR:
case IO_ERADSPH:
case IO_ERADSTICKY:
case IO_ERADFEEDBACK:
case IO_ENERGYFLUX:
case IO_OPTVAR:
case IO_METALS:
for(i = 1; i < 6; i++)
typelist[i] = 0;
return ngas;
break;
case IO_STAR_FORMATIONTIME:
case IO_INITIAL_MASS:
case IO_STAR_IDPROJ:
case IO_STAR_RHO:
case IO_STAR_HSML:
#if defined(STELLAR_PROP)
case IO_STAR_METALS:
for(i = 0; i < 6; i++)
{
typelist[i] = 0;
if(i == ST)
typelist[i] = 1;
}
return nstars;
#endif
break;
}
endrun(212);
return 0;
}
/*! This function tells whether or not a given block in the output file is
* present, depending on the type of simulation run and the compile-time
* options. If one wants to add a new output-block, this function should be
* augmented accordingly.
*/
int blockpresent(enum iofields blocknr)
{
#ifndef OUTPUTPOTENTIAL
if(blocknr == IO_POT)
return 0;
#endif
#ifndef OUTPUTACCELERATION
if(blocknr == IO_ACCEL)
return 0;
#endif
#ifndef OUTPUTCHANGEOFENTROPY
if(blocknr == IO_DTENTR)
return 0;
#endif
#ifndef OUTPUTTIMESTEP
if(blocknr == IO_TSTP)
return 0;
#endif
#ifndef OUTPUTERADSPH
if(blocknr == IO_ERADSPH)
return 0;
#endif
#ifndef OUTPUTERADSTICKY
if(blocknr == IO_ERADSTICKY)
return 0;
#endif
#ifndef OUTPUTERADFEEDBACK
if(blocknr == IO_ERADFEEDBACK)
return 0;
#endif
#ifndef OUTPUTENERGYFLUX
if(blocknr == IO_ENERGYFLUX)
return 0;
#endif
#ifndef OUTPUTOPTVAR
if(blocknr == IO_OPTVAR)
return 0;
#endif
#ifndef OUTPUTSTELLAR_PROP
if(blocknr == IO_STAR_FORMATIONTIME)
return 0;
#endif
#ifndef OUTPUTSTELLAR_PROP
if(blocknr == IO_INITIAL_MASS)
return 0;
#endif
#ifndef OUTPUTSTELLAR_PROP
if(blocknr == IO_STAR_IDPROJ)
return 0;
#endif
#ifndef OUTPUTSTELLAR_PROP
if(blocknr == IO_STAR_RHO)
return 0;
#endif
#ifndef OUTPUTSTELLAR_PROP
if(blocknr == IO_STAR_HSML)
return 0;
#endif
#ifndef OUTPUTSTELLAR_PROP
if(blocknr == IO_STAR_METALS)
return 0;
#endif
#ifndef OUTPUTSTELLAR_PROP
if(blocknr == IO_METALS)
return 0;
#endif
return 1; /* default: present */
}
#ifdef BLOCK_SKIPPING
/*! This function tells whether or not a given block in the input file is
* present, depending on the type of simulation run and the compile-time
* options. If one wants to add a new input-block, this function should be
* augmented accordingly.
*/
int blockabsent(enum iofields blocknr)
{
/* here we will for exampe read the gas initial metallicity if needed */
#ifdef CHIMIE
+
+#ifdef CHIMIE_INPUT_ALL
+ /* here, we restart from a file that contains all block*/
+ if(RestartFlag == 0 && header.flag_metals)
+ if(blocknr > IO_STAR_METALS) /* read all blocks */
+ return 1;
+ else
+ return 0;
+#else
+ /* here, we restart from a file that contains only the gas metals */
if(RestartFlag == 0 && header.flag_metals)
if(blocknr > IO_METALS) /* read in addition IO_RHO,IO_HSML and IO_METALS */
return 1;
else
return 0;
#endif
+#endif
+
if(RestartFlag == 0 && blocknr > IO_U)
return 1; /* ignore all other blocks in initial conditions */
return 0; /* default: absent */
}
#endif
/*! This function associates a short 4-character block name with each block
* number. This is stored in front of each block for snapshot
* FileFormat=2. If one wants to add a new output-block, this function should
* be augmented accordingly.
*/
void fill_Tab_IO_Labels(void)
{
enum iofields i;
for(i = 0; i < IO_NBLOCKS; i++)
switch (i)
{
case IO_POS:
strncpy(Tab_IO_Labels[IO_POS], "POS ", 4);
break;
case IO_VEL:
strncpy(Tab_IO_Labels[IO_VEL], "VEL ", 4);
break;
case IO_ID:
strncpy(Tab_IO_Labels[IO_ID], "ID ", 4);
break;
case IO_MASS:
strncpy(Tab_IO_Labels[IO_MASS], "MASS", 4);
break;
case IO_U:
strncpy(Tab_IO_Labels[IO_U], "U ", 4);
break;
case IO_RHO:
strncpy(Tab_IO_Labels[IO_RHO], "RHO ", 4);
break;
case IO_HSML:
strncpy(Tab_IO_Labels[IO_HSML], "HSML", 4);
break;
case IO_POT:
strncpy(Tab_IO_Labels[IO_POT], "POT ", 4);
break;
case IO_ACCEL:
strncpy(Tab_IO_Labels[IO_ACCEL], "ACCE", 4);
break;
case IO_DTENTR:
strncpy(Tab_IO_Labels[IO_DTENTR], "ENDT", 4);
break;
case IO_TSTP:
strncpy(Tab_IO_Labels[IO_TSTP], "TSTP", 4);
break;
case IO_ERADSPH:
strncpy(Tab_IO_Labels[IO_ERADSPH], "ERADSPH", 4);
break;
case IO_ERADSTICKY:
strncpy(Tab_IO_Labels[IO_ERADSTICKY], "ERADSTICKY", 4);
break;
case IO_ERADFEEDBACK:
strncpy(Tab_IO_Labels[IO_ERADFEEDBACK], "ERADFEEDBACK", 4);
break;
case IO_ENERGYFLUX:
strncpy(Tab_IO_Labels[IO_ENERGYFLUX], "ENERGYFLUX", 4);
break;
case IO_OPTVAR:
strncpy(Tab_IO_Labels[IO_OPTVAR], "OPTVAR", 4);
break;
case IO_STAR_FORMATIONTIME:
strncpy(Tab_IO_Labels[IO_STAR_FORMATIONTIME], "STAR_FORMATIONTIME", 4);
break;
case IO_INITIAL_MASS:
strncpy(Tab_IO_Labels[IO_INITIAL_MASS], "INITIAL_MASS", 4);
break;
case IO_STAR_IDPROJ:
strncpy(Tab_IO_Labels[IO_STAR_IDPROJ], "STAR_IDPROJ", 4);
break;
case IO_STAR_RHO:
strncpy(Tab_IO_Labels[IO_STAR_RHO], "STAR_RHO", 4);
break;
case IO_STAR_HSML:
strncpy(Tab_IO_Labels[IO_STAR_HSML], "STAR_HSML", 4);
break;
case IO_STAR_METALS:
strncpy(Tab_IO_Labels[IO_STAR_METALS], "STAR_METALS", 4);
break;
case IO_METALS:
strncpy(Tab_IO_Labels[IO_METALS], "METALS", 4);
break;
}
}
/*! This function returns a descriptive character string that describes the
* name of the block when the HDF5 file format is used. If one wants to add
* a new output-block, this function should be augmented accordingly.
*/
void get_dataset_name(enum iofields blocknr, char *buf)
{
strcpy(buf, "default");
switch (blocknr)
{
case IO_POS:
strcpy(buf, "Coordinates");
break;
case IO_VEL:
strcpy(buf, "Velocities");
break;
case IO_ID:
strcpy(buf, "ParticleIDs");
break;
case IO_MASS:
strcpy(buf, "Masses");
break;
case IO_U:
strcpy(buf, "InternalEnergy");
break;
case IO_RHO:
strcpy(buf, "Density");
break;
case IO_HSML:
strcpy(buf, "SmoothingLength");
break;
case IO_POT:
strcpy(buf, "Potential");
break;
case IO_ACCEL:
strcpy(buf, "Acceleration");
break;
case IO_DTENTR:
strcpy(buf, "RateOfChangeOfEntropy");
break;
case IO_TSTP:
strcpy(buf, "TimeStep");
break;
case IO_ERADSPH:
strcpy(buf, "EnergyRadiatedSph");
break;
case IO_ERADSTICKY:
strcpy(buf, "EnergyRadiatedSticky");
break;
case IO_ERADFEEDBACK:
strcpy(buf, "EnergyRadiatedFeedback");
break;
case IO_ENERGYFLUX:
strcpy(buf, "EnergyFlux");
break;
case IO_OPTVAR:
strcpy(buf, "OptVar");
break;
case IO_STAR_FORMATIONTIME:
strcpy(buf, "StarFormationTime");
break;
case IO_INITIAL_MASS:
strcpy(buf, "InitialMass");
break;
case IO_STAR_IDPROJ:
strcpy(buf, "StarIDProj");
break;
case IO_STAR_RHO:
strcpy(buf, "StarRho");
break;
case IO_STAR_HSML:
strcpy(buf, "StarHsml");
break;
case IO_STAR_METALS:
strcpy(buf, "StarMetals");
break;
case IO_METALS:
strcpy(buf, "Metals");
break;
}
}
/*! This function writes an actual snapshot file containing the data from
* processors 'writeTask' to 'lastTask'. 'writeTask' is the one that actually
* writes. Each snapshot file contains a header first, then particle
* positions, velocities and ID's. Particle masses are written only for
* those particle types with zero entry in MassTable. After that, first the
* internal energies u, and then the density is written for the SPH
* particles. If cooling is enabled, mean molecular weight and neutral
* hydrogen abundance are written for the gas particles. This is followed by
* the SPH smoothing length and further blocks of information, depending on
* included physics and compile-time flags. If HDF5 is used, the header is
* stored in a group called "/Header", and the particle data is stored
* separately for each particle type in groups calles "/PartType0",
* "/PartType1", etc. The sequence of the blocks is unimportant in this case.
*/
void write_file(char *fname, int writeTask, int lastTask)
{
int type, bytes_per_blockelement, npart, nextblock, typelist[6];
int n_for_this_task, ntask, n, p, pc, offset = 0, task;
int blockmaxlen, ntot_type[6], nn[6];
enum iofields blocknr;
int blksize;
int i;
MPI_Status status;
FILE *fd = 0;
#ifdef HAVE_HDF5
hid_t hdf5_file = 0, hdf5_grp[6], hdf5_headergrp = 0, hdf5_dataspace_memory;
hid_t hdf5_datatype = 0, hdf5_dataspace_in_file = 0, hdf5_dataset = 0;
herr_t hdf5_status;
hsize_t dims[2], count[2], start[2];
int rank, pcsum = 0;
char buf[500];
#endif
#define SKIP {my_fwrite(&blksize,sizeof(int),1,fd);}
/* determine particle numbers of each type in file */
if(ThisTask == writeTask)
{
for(n = 0; n < 6; n++)
ntot_type[n] = n_type[n];
for(task = writeTask + 1; task <= lastTask; task++)
{
MPI_Recv(&nn[0], 6, MPI_INT, task, TAG_LOCALN, MPI_COMM_WORLD, &status);
for(n = 0; n < 6; n++)
ntot_type[n] += nn[n];
}
for(task = writeTask + 1; task <= lastTask; task++)
MPI_Send(&ntot_type[0], 6, MPI_INT, task, TAG_N, MPI_COMM_WORLD);
}
else
{
MPI_Send(&n_type[0], 6, MPI_INT, writeTask, TAG_LOCALN, MPI_COMM_WORLD);
MPI_Recv(&ntot_type[0], 6, MPI_INT, writeTask, TAG_N, MPI_COMM_WORLD, &status);
}
/* fill file header */
for(n = 0; n < 6; n++)
{
header.npart[n] = ntot_type[n];
header.npartTotal[n] = (unsigned int) ntot_type_all[n];
header.npartTotalHighWord[n] = (unsigned int) (ntot_type_all[n] >> 32);
}
for(n = 0; n < 6; n++)
header.mass[n] = All.MassTable[n];
header.time = All.Time;
if(All.ComovingIntegrationOn)
header.redshift = 1.0 / All.Time - 1;
else
header.redshift = 0;
header.flag_sfr = 0;
header.flag_feedback = 0;
header.flag_cooling = 0;
header.flag_stellarage = 0;
header.flag_metals = 0;
#ifdef MULTIPHASE
header.critical_energy_spec = All.CriticalEgySpec;
#endif
#ifdef COOLING
header.flag_cooling = 1;
#endif
#ifdef SFR
header.flag_sfr = 1;
#ifdef OUTPUTSTELLAR_PROP
header.flag_stellarage = 1;
header.flag_metals = NELEMENTS;
#endif
#ifdef FEEDBACK
header.flag_feedback = 1;
#endif
#endif
header.num_files = All.NumFilesPerSnapshot;
header.BoxSize = All.BoxSize;
header.Omega0 = All.Omega0;
header.OmegaLambda = All.OmegaLambda;
header.HubbleParam = All.HubbleParam;
/* set fill to " " : yr Thu Aug 13 17:34:07 CEST 2009*/
memset(header.fill,' ',sizeof(header.fill));
/* fill file chimie-header */
header.flag_chimie_extraheader = 0;
#ifdef CHIMIE_EXTRAHEADER
header.flag_chimie_extraheader = 1;
chimie_extraheader.nelts = get_nelts();
for (i=0;i<get_nelts();i++)
{
chimie_extraheader.SolarAbundances[i]=get_SolarAbundance(i);
}
memset(chimie_extraheader.labels,' ',sizeof(chimie_extraheader.labels));
for (i=0,n=0;i<get_nelts();i++)
{
strcpy(&chimie_extraheader.labels[n],get_Element(i));
n+= strlen(get_Element(i));
strncpy(&chimie_extraheader.labels[n++],",",1);
}
#endif
/* open file and write header */
if(ThisTask == writeTask)
{
if(All.SnapFormat == 3)
{
#ifdef HAVE_HDF5
sprintf(buf, "%s.hdf5", fname);
hdf5_file = H5Fcreate(buf, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
hdf5_headergrp = H5Gcreate(hdf5_file, "/Header", 0);
for(type = 0; type < 6; type++)
{
if(header.npart[type] > 0)
{
sprintf(buf, "/PartType%d", type);
hdf5_grp[type] = H5Gcreate(hdf5_file, buf, 0);
}
}
write_header_attributes_in_hdf5(hdf5_headergrp);
#endif
}
else
{
if(!(fd = fopen(fname, "w")))
{
printf("can't open file `%s' for writing snapshot.\n", fname);
endrun(123);
}
if(All.SnapFormat == 2)
{
blksize = sizeof(int) + 4 * sizeof(char);
SKIP;
my_fwrite("HEAD", sizeof(char), 4, fd);
nextblock = sizeof(header) + 2 * sizeof(int);
my_fwrite(&nextblock, sizeof(int), 1, fd);
SKIP;
}
blksize = sizeof(header);
SKIP;
my_fwrite(&header, sizeof(header), 1, fd);
SKIP;
#ifdef CHIMIE_EXTRAHEADER
blksize = sizeof(chimie_extraheader);
SKIP;
my_fwrite(&chimie_extraheader, sizeof(chimie_extraheader), 1, fd);
SKIP;
#endif
}
}
ntask = lastTask - writeTask + 1;
for(blocknr = 0; blocknr < IO_NBLOCKS; blocknr++)
{
if(blockpresent(blocknr))
{
bytes_per_blockelement = get_bytes_per_blockelement(blocknr);
blockmaxlen = ((int) (All.BufferSize * 1024 * 1024)) / bytes_per_blockelement;
npart = get_particles_in_block(blocknr, &typelist[0]);
if(npart > 0)
{
if(ThisTask == writeTask)
{
if(All.SnapFormat == 1 || All.SnapFormat == 2)
{
if(All.SnapFormat == 2)
{
blksize = sizeof(int) + 4 * sizeof(char);
SKIP;
my_fwrite(Tab_IO_Labels[blocknr], sizeof(char), 4, fd);
nextblock = npart * bytes_per_blockelement + 2 * sizeof(int);
my_fwrite(&nextblock, sizeof(int), 1, fd);
SKIP;
}
blksize = npart * bytes_per_blockelement;
SKIP;
}
}
for(type = 0; type < 6; type++)
{
if(typelist[type])
{
#ifdef HAVE_HDF5
if(ThisTask == writeTask && All.SnapFormat == 3 && header.npart[type] > 0)
{
switch (get_datatype_in_block(blocknr))
{
case 0:
hdf5_datatype = H5Tcopy(H5T_NATIVE_UINT);
break;
case 1:
hdf5_datatype = H5Tcopy(H5T_NATIVE_FLOAT);
break;
case 2:
hdf5_datatype = H5Tcopy(H5T_NATIVE_UINT64);
break;
}
dims[0] = header.npart[type];
dims[1] = get_values_per_blockelement(blocknr);
if(dims[1] == 1)
rank = 1;
else
rank = 2;
get_dataset_name(blocknr, buf);
hdf5_dataspace_in_file = H5Screate_simple(rank, dims, NULL);
hdf5_dataset =
H5Dcreate(hdf5_grp[type], buf, hdf5_datatype, hdf5_dataspace_in_file,
H5P_DEFAULT);
pcsum = 0;
}
#endif
for(task = writeTask, offset = 0; task <= lastTask; task++)
{
if(task == ThisTask)
{
n_for_this_task = n_type[type];
for(p = writeTask; p <= lastTask; p++)
if(p != ThisTask)
MPI_Send(&n_for_this_task, 1, MPI_INT, p, TAG_NFORTHISTASK, MPI_COMM_WORLD);
}
else
MPI_Recv(&n_for_this_task, 1, MPI_INT, task, TAG_NFORTHISTASK, MPI_COMM_WORLD,
&status);
while(n_for_this_task > 0)
{
pc = n_for_this_task;
if(pc > blockmaxlen)
pc = blockmaxlen;
if(ThisTask == task)
fill_write_buffer(blocknr, &offset, pc, type);
if(ThisTask == writeTask && task != writeTask)
MPI_Recv(CommBuffer, bytes_per_blockelement * pc, MPI_BYTE, task,
TAG_PDATA, MPI_COMM_WORLD, &status);
if(ThisTask != writeTask && task == ThisTask)
MPI_Ssend(CommBuffer, bytes_per_blockelement * pc, MPI_BYTE, writeTask,
TAG_PDATA, MPI_COMM_WORLD);
if(ThisTask == writeTask)
{
if(All.SnapFormat == 3)
{
#ifdef HAVE_HDF5
start[0] = pcsum;
start[1] = 0;
count[0] = pc;
count[1] = get_values_per_blockelement(blocknr);
pcsum += pc;
H5Sselect_hyperslab(hdf5_dataspace_in_file, H5S_SELECT_SET,
start, NULL, count, NULL);
dims[0] = pc;
dims[1] = get_values_per_blockelement(blocknr);
hdf5_dataspace_memory = H5Screate_simple(rank, dims, NULL);
hdf5_status =
H5Dwrite(hdf5_dataset, hdf5_datatype, hdf5_dataspace_memory,
hdf5_dataspace_in_file, H5P_DEFAULT, CommBuffer);
H5Sclose(hdf5_dataspace_memory);
#endif
}
else
my_fwrite(CommBuffer, bytes_per_blockelement, pc, fd);
}
n_for_this_task -= pc;
}
}
#ifdef HAVE_HDF5
if(ThisTask == writeTask && All.SnapFormat == 3 && header.npart[type] > 0)
{
if(All.SnapFormat == 3)
{
H5Dclose(hdf5_dataset);
H5Sclose(hdf5_dataspace_in_file);
H5Tclose(hdf5_datatype);
}
}
#endif
}
}
if(ThisTask == writeTask)
{
if(All.SnapFormat == 1 || All.SnapFormat == 2)
SKIP;
}
}
}
}
if(ThisTask == writeTask)
{
if(All.SnapFormat == 3)
{
#ifdef HAVE_HDF5
for(type = 5; type >= 0; type--)
if(header.npart[type] > 0)
H5Gclose(hdf5_grp[type]);
H5Gclose(hdf5_headergrp);
H5Fclose(hdf5_file);
#endif
}
else
fclose(fd);
}
}
/*! This function writes the header information in case HDF5 is selected as
* file format.
*/
#ifdef HAVE_HDF5
void write_header_attributes_in_hdf5(hid_t handle)
{
hsize_t adim[1] = { 6 };
hid_t hdf5_dataspace, hdf5_attribute;
hdf5_dataspace = H5Screate(H5S_SIMPLE);
H5Sset_extent_simple(hdf5_dataspace, 1, adim, NULL);
hdf5_attribute = H5Acreate(handle, "NumPart_ThisFile", H5T_NATIVE_INT, hdf5_dataspace, H5P_DEFAULT);
H5Awrite(hdf5_attribute, H5T_NATIVE_UINT, header.npart);
H5Aclose(hdf5_attribute);
H5Sclose(hdf5_dataspace);
hdf5_dataspace = H5Screate(H5S_SIMPLE);
H5Sset_extent_simple(hdf5_dataspace, 1, adim, NULL);
hdf5_attribute = H5Acreate(handle, "NumPart_Total", H5T_NATIVE_UINT, hdf5_dataspace, H5P_DEFAULT);
H5Awrite(hdf5_attribute, H5T_NATIVE_UINT, header.npartTotal);
H5Aclose(hdf5_attribute);
H5Sclose(hdf5_dataspace);
hdf5_dataspace = H5Screate(H5S_SIMPLE);
H5Sset_extent_simple(hdf5_dataspace, 1, adim, NULL);
hdf5_attribute = H5Acreate(handle, "NumPart_Total_HW", H5T_NATIVE_UINT, hdf5_dataspace, H5P_DEFAULT);
H5Awrite(hdf5_attribute, H5T_NATIVE_UINT, header.npartTotalHighWord);
H5Aclose(hdf5_attribute);
H5Sclose(hdf5_dataspace);
hdf5_dataspace = H5Screate(H5S_SIMPLE);
H5Sset_extent_simple(hdf5_dataspace, 1, adim, NULL);
hdf5_attribute = H5Acreate(handle, "MassTable", H5T_NATIVE_DOUBLE, hdf5_dataspace, H5P_DEFAULT);
H5Awrite(hdf5_attribute, H5T_NATIVE_DOUBLE, header.mass);
H5Aclose(hdf5_attribute);
H5Sclose(hdf5_dataspace);
hdf5_dataspace = H5Screate(H5S_SCALAR);
hdf5_attribute = H5Acreate(handle, "Time", H5T_NATIVE_DOUBLE, hdf5_dataspace, H5P_DEFAULT);
H5Awrite(hdf5_attribute, H5T_NATIVE_DOUBLE, &header.time);
H5Aclose(hdf5_attribute);
H5Sclose(hdf5_dataspace);
hdf5_dataspace = H5Screate(H5S_SCALAR);
hdf5_attribute = H5Acreate(handle, "Redshift", H5T_NATIVE_DOUBLE, hdf5_dataspace, H5P_DEFAULT);
H5Awrite(hdf5_attribute, H5T_NATIVE_DOUBLE, &header.redshift);
H5Aclose(hdf5_attribute);
H5Sclose(hdf5_dataspace);
hdf5_dataspace = H5Screate(H5S_SCALAR);
hdf5_attribute = H5Acreate(handle, "BoxSize", H5T_NATIVE_DOUBLE, hdf5_dataspace, H5P_DEFAULT);
H5Awrite(hdf5_attribute, H5T_NATIVE_DOUBLE, &header.BoxSize);
H5Aclose(hdf5_attribute);
H5Sclose(hdf5_dataspace);
hdf5_dataspace = H5Screate(H5S_SCALAR);
hdf5_attribute = H5Acreate(handle, "NumFilesPerSnapshot", H5T_NATIVE_INT, hdf5_dataspace, H5P_DEFAULT);
H5Awrite(hdf5_attribute, H5T_NATIVE_INT, &header.num_files);
H5Aclose(hdf5_attribute);
H5Sclose(hdf5_dataspace);
hdf5_dataspace = H5Screate(H5S_SCALAR);
hdf5_attribute = H5Acreate(handle, "Omega0", H5T_NATIVE_DOUBLE, hdf5_dataspace, H5P_DEFAULT);
H5Awrite(hdf5_attribute, H5T_NATIVE_DOUBLE, &header.Omega0);
H5Aclose(hdf5_attribute);
H5Sclose(hdf5_dataspace);
hdf5_dataspace = H5Screate(H5S_SCALAR);
hdf5_attribute = H5Acreate(handle, "OmegaLambda", H5T_NATIVE_DOUBLE, hdf5_dataspace, H5P_DEFAULT);
H5Awrite(hdf5_attribute, H5T_NATIVE_DOUBLE, &header.OmegaLambda);
H5Aclose(hdf5_attribute);
H5Sclose(hdf5_dataspace);
hdf5_dataspace = H5Screate(H5S_SCALAR);
hdf5_attribute = H5Acreate(handle, "HubbleParam", H5T_NATIVE_DOUBLE, hdf5_dataspace, H5P_DEFAULT);
H5Awrite(hdf5_attribute, H5T_NATIVE_DOUBLE, &header.HubbleParam);
H5Aclose(hdf5_attribute);
H5Sclose(hdf5_dataspace);
hdf5_dataspace = H5Screate(H5S_SCALAR);
hdf5_attribute = H5Acreate(handle, "Flag_Sfr", H5T_NATIVE_INT, hdf5_dataspace, H5P_DEFAULT);
H5Awrite(hdf5_attribute, H5T_NATIVE_INT, &header.flag_sfr);
H5Aclose(hdf5_attribute);
H5Sclose(hdf5_dataspace);
hdf5_dataspace = H5Screate(H5S_SCALAR);
hdf5_attribute = H5Acreate(handle, "Flag_Cooling", H5T_NATIVE_INT, hdf5_dataspace, H5P_DEFAULT);
H5Awrite(hdf5_attribute, H5T_NATIVE_INT, &header.flag_cooling);
H5Aclose(hdf5_attribute);
H5Sclose(hdf5_dataspace);
hdf5_dataspace = H5Screate(H5S_SCALAR);
hdf5_attribute = H5Acreate(handle, "Flag_StellarAge", H5T_NATIVE_INT, hdf5_dataspace, H5P_DEFAULT);
H5Awrite(hdf5_attribute, H5T_NATIVE_INT, &header.flag_stellarage);
H5Aclose(hdf5_attribute);
H5Sclose(hdf5_dataspace);
hdf5_dataspace = H5Screate(H5S_SCALAR);
hdf5_attribute = H5Acreate(handle, "Flag_Metals", H5T_NATIVE_INT, hdf5_dataspace, H5P_DEFAULT);
H5Awrite(hdf5_attribute, H5T_NATIVE_INT, &header.flag_metals);
H5Aclose(hdf5_attribute);
H5Sclose(hdf5_dataspace);
hdf5_dataspace = H5Screate(H5S_SCALAR);
hdf5_attribute = H5Acreate(handle, "Flag_Feedback", H5T_NATIVE_INT, hdf5_dataspace, H5P_DEFAULT);
H5Awrite(hdf5_attribute, H5T_NATIVE_INT, &header.flag_feedback);
H5Aclose(hdf5_attribute);
H5Sclose(hdf5_dataspace);
header.flag_entropy_instead_u = 0;
hdf5_dataspace = H5Screate(H5S_SIMPLE);
H5Sset_extent_simple(hdf5_dataspace, 1, adim, NULL);
hdf5_attribute = H5Acreate(handle, "Flag_Entropy_ICs", H5T_NATIVE_UINT, hdf5_dataspace, H5P_DEFAULT);
H5Awrite(hdf5_attribute, H5T_NATIVE_UINT, header.flag_entropy_instead_u);
H5Aclose(hdf5_attribute);
H5Sclose(hdf5_dataspace);
}
#endif
/*! This catches I/O errors occuring for my_fwrite(). In this case we
* better stop.
*/
size_t my_fwrite(void *ptr, size_t size, size_t nmemb, FILE * stream)
{
size_t nwritten;
if((nwritten = fwrite(ptr, size, nmemb, stream)) != nmemb)
{
printf("I/O error (fwrite) on task=%d has occured: %s\n", ThisTask, strerror(errno));
fflush(stdout);
endrun(777);
}
return nwritten;
}
/*! This catches I/O errors occuring for fread(). In this case we
* better stop.
*/
size_t my_fread(void *ptr, size_t size, size_t nmemb, FILE * stream)
{
size_t nread;
if((nread = fread(ptr, size, nmemb, stream)) != nmemb)
{
printf("I/O error (fread) on task=%d has occured: %s\n", ThisTask, strerror(errno));
fflush(stdout);
endrun(778);
}
return nread;
}
diff --git a/read_ic.c b/read_ic.c
index 2d1d98b..080138c 100644
--- a/read_ic.c
+++ b/read_ic.c
@@ -1,932 +1,945 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <string.h>
#include <mpi.h>
#include "allvars.h"
#include "proto.h"
/*! \file read_ic.c
* \brief Read initial conditions in one of Gadget's file formats
*/
/*! This function reads initial conditions, in one of the three possible file
* formats currently supported by Gadget. Note: When a snapshot file is
* started from initial conditions (start-option 0), not all the information
* in the header is used, in particular, the STARTING TIME needs to be set in
* the parameterfile. Also, for gas particles, only the internal energy is
* read, the density and mean molecular weight will be recomputed by the
* code. When InitGasTemp>0 is given, the gas temperature will be initialzed
* to this value assuming a mean colecular weight either corresponding to
* complete neutrality, or full ionization.
*
* However, when the code is started with start-option 2, then all the this
* data in the snapshot files is preserved, i.e. this is also the way to
* resume a simulation from a snapshot file in case a regular restart file is
* not available.
*/
void read_ic(char *fname)
{
int i, num_files, rest_files, ngroups, gr, filenr, masterTask, lastTask, groupMaster;
double u_init;
char buf[500];
#ifndef ISOTHERM_EQS
double molecular_weight;
#endif
NumPart = 0;
N_gas = 0;
#ifdef SFR
N_stars = 0;
#endif
All.TotNumPart = 0;
num_files = find_files(fname);
rest_files = num_files;
fill_Tab_IO_Labels();
while(rest_files > NTask)
{
sprintf(buf, "%s.%d", fname, ThisTask + (rest_files - NTask));
if(All.ICFormat == 3)
sprintf(buf, "%s.%d.hdf5", fname, ThisTask + (rest_files - NTask));
ngroups = NTask / All.NumFilesWrittenInParallel;
if((NTask % All.NumFilesWrittenInParallel))
ngroups++;
groupMaster = (ThisTask / ngroups) * ngroups;
for(gr = 0; gr < ngroups; gr++)
{
if(ThisTask == (groupMaster + gr)) /* ok, it's this processor's turn */
read_file(buf, ThisTask, ThisTask);
MPI_Barrier(MPI_COMM_WORLD);
}
rest_files -= NTask;
}
if(rest_files > 0)
{
distribute_file(rest_files, 0, 0, NTask - 1, &filenr, &masterTask, &lastTask);
if(num_files > 1)
{
sprintf(buf, "%s.%d", fname, filenr);
if(All.ICFormat == 3)
sprintf(buf, "%s.%d.hdf5", fname, filenr);
}
else
{
sprintf(buf, "%s", fname);
if(All.ICFormat == 3)
sprintf(buf, "%s.hdf5", fname);
}
ngroups = rest_files / All.NumFilesWrittenInParallel;
if((rest_files % All.NumFilesWrittenInParallel))
ngroups++;
for(gr = 0; gr < ngroups; gr++)
{
if((filenr / All.NumFilesWrittenInParallel) == gr) /* ok, it's this processor's turn */
read_file(buf, masterTask, lastTask);
MPI_Barrier(MPI_COMM_WORLD);
}
}
/* this makes sure that masses are initialized in the case that the mass-block
is completely empty */
for(i = 0; i < NumPart; i++)
{
if(All.MassTable[P[i].Type] != 0)
P[i].Mass = All.MassTable[P[i].Type];
}
if(RestartFlag == 0)
{
if(All.InitGasTemp > 0)
{
u_init = (BOLTZMANN / PROTONMASS) * All.InitGasTemp;
u_init *= All.UnitMass_in_g / All.UnitEnergy_in_cgs; /* unit conversion */
#ifdef ISOTHERM_EQS
u_init *= (3.0/2);
#else
u_init *= (1.0 / GAMMA_MINUS1);
if(All.InitGasTemp > 1.0e4) /* assuming FULL ionization */
molecular_weight = 4 / (8 - 5 * (1 - HYDROGEN_MASSFRAC));
else /* assuming NEUTRAL GAS */
molecular_weight = 4 / (1 + 3 * HYDROGEN_MASSFRAC);
u_init /= molecular_weight;
#endif
for(i = 0; i < N_gas; i++)
{
if(SphP[i].Entropy == 0)
SphP[i].Entropy = u_init;
/* Note: the conversion to entropy will be done in the function init(),
after the densities have been computed */
}
}
}
#ifdef WRITE_ALL_MASSES
for(i = 0; i < 6; i++)
All.MassTable[i] = 0;
#endif
#ifdef MULTIPHASE
for(i = 0; i < N_gas; i++)
{
if(SphP[i].Entropy>0)
SphP[i].Entropy = dmax(All.MinEgySpec, SphP[i].Entropy);
else
SphP[i].Entropy = -dmax(All.MinEgySpec, -SphP[i].Entropy);
}
#else
for(i = 0; i < N_gas; i++)
SphP[i].Entropy = dmax(All.MinEgySpec, SphP[i].Entropy);
#endif
MPI_Barrier(MPI_COMM_WORLD);
if(ThisTask == 0)
{
printf("reading done.\n");
fflush(stdout);
}
if(ThisTask == 0)
{
printf("Total number of particles : %d%09d\n\n",
(int) (All.TotNumPart / 1000000000), (int) (All.TotNumPart % 1000000000));
fflush(stdout);
}
}
/*! This function reads out the buffer that was filled with particle data, and
* stores it at the appropriate place in the particle structures.
*/
void empty_read_buffer(enum iofields blocknr, int offset, int pc, int type)
{
int n, k;
float *fp;
#ifdef LONGIDS
long long *ip;
#else
int *ip;
#endif
fp = CommBuffer;
ip = CommBuffer;
switch (blocknr)
{
case IO_POS: /* positions */
for(n = 0; n < pc; n++)
for(k = 0; k < 3; k++)
P[offset + n].Pos[k] = *fp++;
for(n = 0; n < pc; n++)
P[offset + n].Type = type; /* initialize type here as well */
break;
case IO_VEL: /* velocities */
for(n = 0; n < pc; n++)
for(k = 0; k < 3; k++)
P[offset + n].Vel[k] = *fp++;
break;
case IO_ID: /* particle ID */
for(n = 0; n < pc; n++)
P[offset + n].ID = *ip++;
break;
case IO_MASS: /* particle mass */
for(n = 0; n < pc; n++)
P[offset + n].Mass = *fp++;
break;
case IO_U: /* temperature */
for(n = 0; n < pc; n++)
SphP[offset + n].Entropy = *fp++;
break;
case IO_RHO: /* density */
for(n = 0; n < pc; n++)
SphP[offset + n].Density = *fp++;
break;
case IO_HSML: /* SPH smoothing length */
for(n = 0; n < pc; n++)
SphP[offset + n].Hsml = *fp++;
break;
/* the other input fields (if present) are not needed to define the
initial conditions of the code */
case IO_POT:
case IO_ACCEL:
case IO_DTENTR:
case IO_TSTP:
case IO_ERADSPH:
case IO_ERADSTICKY:
case IO_ERADFEEDBACK:
case IO_ENERGYFLUX:
case IO_OPTVAR:
break;
case IO_METALS: /* gas metallicity */
#ifdef CHIMIE
for(n = 0; n < pc; n++)
{
for(k = 0; k < NELEMENTS; k++)
{
SphP[offset + n].Metal[k] = *fp++;
}
}
#endif
break;
case IO_STAR_FORMATIONTIME:
#ifdef STELLAR_PROP
for(n = 0; n < pc; n++)
StP[n].FormationTime = *fp++;
#endif
break;
case IO_INITIAL_MASS:
#ifdef STELLAR_PROP
for(n = 0; n < pc; n++)
StP[n].InitialMass = *fp++;
#endif
break;
case IO_STAR_IDPROJ:
#ifdef STELLAR_PROP
for(n = 0; n < pc; n++)
StP[n].IDProj = *ip++;
#endif
break;
case IO_STAR_RHO:
#ifdef STELLAR_PROP
for(n = 0; n < pc; n++)
StP[n].Density = *fp++;
#endif
break;
case IO_STAR_HSML:
#ifdef STELLAR_PROP
for(n = 0; n < pc; n++)
StP[n].Hsml = *fp++;
#endif
break;
case IO_STAR_METALS:
#ifdef CHIMIE
for(n = 0; n < pc; n++)
{
for(k = 0; k < NELEMENTS; k++)
{
StP[n].Metal[k] = *fp++;
}
}
#endif
break;
}
}
/*! This function reads a snapshot file and distributes the data it contains
* to tasks 'readTask' to 'lastTask'.
*/
void read_file(char *fname, int readTask, int lastTask)
{
int blockmaxlen;
int i, n_in_file, n_for_this_task, ntask, pc, offset = 0, task;
int blksize1, blksize2;
MPI_Status status;
FILE *fd = 0;
int nall;
int type;
char label[4];
int nstart, bytes_per_blockelement, npart, nextblock, typelist[6];
enum iofields blocknr;
#ifdef HAVE_HDF5
char buf[500];
int rank, pcsum;
hid_t hdf5_file, hdf5_grp[6], hdf5_dataspace_in_file;
hid_t hdf5_datatype, hdf5_dataspace_in_memory, hdf5_dataset;
hsize_t dims[2], count[2], start[2];
#endif
#define SKIP {my_fread(&blksize1,sizeof(int),1,fd);}
#define SKIP2 {my_fread(&blksize2,sizeof(int),1,fd);}
if(ThisTask == readTask)
{
if(All.ICFormat == 1 || All.ICFormat == 2)
{
if(!(fd = fopen(fname, "r")))
{
printf("can't open file `%s' for reading initial conditions.\n", fname);
endrun(123);
}
if(All.ICFormat == 2)
{
SKIP;
my_fread(&label, sizeof(char), 4, fd);
my_fread(&nextblock, sizeof(int), 1, fd);
printf("Reading header => '%c%c%c%c' (%d byte)\n", label[0], label[1], label[2], label[3],
nextblock);
SKIP2;
}
SKIP;
my_fread(&header, sizeof(header), 1, fd);
SKIP2;
if(blksize1 != 256 || blksize2 != 256)
{
printf("incorrect header format\n");
fflush(stdout);
endrun(890);
}
+#ifdef CHIMIE
+ if((header.flag_metals!= 0) && (header.flag_metals!= NELEMENTS))
+ {
+ printf("\n(Tasks=%d) NELEMENTS (=%d) != header.flag_metals (=%d) !!!\n\n",ThisTask,NELEMENTS,header.flag_metals);
+ printf("This means that the number of chemical elements stored in your initial condition file is different \n");
+ printf("from the variable NELEMENTS equal to the one in the chimie parameter file.\n");
+ printf("You can either modify you initial condition file or change the NELEMENTS and the chimie parameter file.");
+ endrun(12323);
+ }
+#endif
+
+
+
#ifdef CHIMIE_EXTRAHEADER
if (header.flag_chimie_extraheader)
{
SKIP;
my_fread(&chimie_extraheader, sizeof(chimie_extraheader), 1, fd);
SKIP2;
if(blksize1 != 256 || blksize2 != 256)
{
printf("incorrect chimie_extraheader format\n");
fflush(stdout);
endrun(891);
}
}
#endif
}
#ifdef HAVE_HDF5
if(All.ICFormat == 3)
{
read_header_attributes_in_hdf5(fname);
hdf5_file = H5Fopen(fname, H5F_ACC_RDONLY, H5P_DEFAULT);
for(type = 0; type < 6; type++)
{
if(header.npart[type] > 0)
{
sprintf(buf, "/PartType%d", type);
hdf5_grp[type] = H5Gopen(hdf5_file, buf);
}
}
}
#endif
for(task = readTask + 1; task <= lastTask; task++)
{
MPI_Ssend(&header, sizeof(header), MPI_BYTE, task, TAG_HEADER, MPI_COMM_WORLD);
#ifdef CHIMIE_EXTRAHEADER
if (header.flag_chimie_extraheader)
MPI_Ssend(&header, sizeof(chimie_extraheader), MPI_BYTE, task, TAG_CHIMIE_EXTRAHEADER, MPI_COMM_WORLD);
#endif
}
}
else
{
MPI_Recv(&header, sizeof(header), MPI_BYTE, readTask, TAG_HEADER, MPI_COMM_WORLD, &status);
#ifdef CHIMIE_EXTRAHEADER
if (header.flag_chimie_extraheader)
MPI_Recv(&chimie_extraheader, sizeof(chimie_extraheader), MPI_BYTE, readTask, TAG_CHIMIE_EXTRAHEADER, MPI_COMM_WORLD, &status);
#endif
}
if(All.TotNumPart == 0)
{
if(header.num_files <= 1)
for(i = 0; i < 6; i++)
header.npartTotal[i] = header.npart[i];
All.TotN_gas = header.npartTotal[0] + (((long long) header.npartTotalHighWord[0]) << 32);
#if defined(SFR) || defined(STELLAR_PROP)
All.TotN_stars = header.npartTotal[ST] + (((long long) header.npartTotalHighWord[ST]) << 32);
#endif
for(i = 0, All.TotNumPart = 0; i < 6; i++)
{
All.TotNumPart += header.npartTotal[i];
All.TotNumPart += (((long long) header.npartTotalHighWord[i]) << 32);
}
for(i = 0; i < 6; i++)
All.MassTable[i] = header.mass[i];
All.MaxPart = All.PartAllocFactor * (All.TotNumPart / NTask); /* sets the maximum number of particles that may */
All.MaxPartSph = All.PartAllocFactor * (All.TotN_gas / NTask); /* sets the maximum number of particles that may
reside on a processor */
#ifdef STELLAR_PROP
All.MaxPartStars = All.PartAllocFactor * (All.TotN_stars / NTask); /* existing star particles */
#ifdef SFR
All.MaxPartStars = All.MaxPartStars + All.StarFormationNStarsFromGas*All.MaxPartSph*All.StarsAllocFactor; /* potental star particles */
#endif
#endif
allocate_memory();
if(RestartFlag == 2)
All.Time = All.TimeBegin = header.time;
}
if(ThisTask == readTask)
{
for(i = 0, n_in_file = 0; i < 6; i++)
n_in_file += header.npart[i];
printf("\nreading file `%s' on task=%d (contains %d particles.)\n"
"distributing this file to tasks %d-%d\n"
"Type 0 (gas): %8d (tot=%6d%09d) masstab=%g\n"
"Type 1 (halo): %8d (tot=%6d%09d) masstab=%g\n"
"Type 2 (disk): %8d (tot=%6d%09d) masstab=%g\n"
"Type 3 (bulge): %8d (tot=%6d%09d) masstab=%g\n"
"Type 4 (stars): %8d (tot=%6d%09d) masstab=%g\n"
"Type 5 (bndry): %8d (tot=%6d%09d) masstab=%g\n\n", fname, ThisTask, n_in_file, readTask,
lastTask, header.npart[0], (int) (header.npartTotal[0] / 1000000000),
(int) (header.npartTotal[0] % 1000000000), All.MassTable[0], header.npart[1],
(int) (header.npartTotal[1] / 1000000000), (int) (header.npartTotal[1] % 1000000000),
All.MassTable[1], header.npart[2], (int) (header.npartTotal[2] / 1000000000),
(int) (header.npartTotal[2] % 1000000000), All.MassTable[2], header.npart[3],
(int) (header.npartTotal[3] / 1000000000), (int) (header.npartTotal[3] % 1000000000),
All.MassTable[3], header.npart[4], (int) (header.npartTotal[4] / 1000000000),
(int) (header.npartTotal[4] % 1000000000), All.MassTable[4], header.npart[5],
(int) (header.npartTotal[5] / 1000000000), (int) (header.npartTotal[5] % 1000000000),
All.MassTable[5]);
fflush(stdout);
}
ntask = lastTask - readTask + 1;
/* to collect the gas particles all at the beginning (in case several
snapshot files are read on the current CPU) we move the collisionless
particles such that a gap of the right size is created */
for(type = 0, nall = 0; type < 6; type++)
{
n_in_file = header.npart[type];
n_for_this_task = n_in_file / ntask;
if((ThisTask - readTask) < (n_in_file % ntask))
n_for_this_task++;
nall += n_for_this_task;
}
memmove(&P[N_gas + nall], &P[N_gas], (NumPart - N_gas) * sizeof(struct particle_data));
nstart = N_gas;
for(blocknr = 0; blocknr < IO_NBLOCKS; blocknr++)
{
if(blockpresent(blocknr))
{
#ifndef BLOCK_SKIPPING
if(RestartFlag == 0 && blocknr > IO_U)
continue; /* ignore all other blocks in initial conditions */
#else
if(blockabsent(blocknr))
continue;
#endif
bytes_per_blockelement = get_bytes_per_blockelement(blocknr);
blockmaxlen = ((int) (All.BufferSize * 1024 * 1024)) / bytes_per_blockelement;
npart = get_particles_in_block(blocknr, &typelist[0]);
if(npart > 0)
{
if(ThisTask == readTask)
{
if(All.ICFormat == 2)
{
SKIP;
my_fread(&label, sizeof(char), 4, fd);
my_fread(&nextblock, sizeof(int), 1, fd);
printf("Reading header => '%c%c%c%c' (%d byte)\n", label[0], label[1], label[2],
label[3], nextblock);
SKIP2;
if(strncmp(label, Tab_IO_Labels[blocknr], 4) != 0)
{
printf("incorrect block-structure!\n");
printf("expected '%c%c%c%c' but found '%c%c%c%c'\n",
label[0], label[1], label[2], label[3],
Tab_IO_Labels[blocknr][0], Tab_IO_Labels[blocknr][1],
Tab_IO_Labels[blocknr][2], Tab_IO_Labels[blocknr][3]);
fflush(stdout);
endrun(1890);
}
}
if(All.ICFormat == 1 || All.ICFormat == 2)
SKIP;
}
for(type = 0, offset = 0; type < 6; type++)
{
n_in_file = header.npart[type];
#ifdef HAVE_HDF5
pcsum = 0;
#endif
if(typelist[type] == 0)
{
n_for_this_task = n_in_file / ntask;
if((ThisTask - readTask) < (n_in_file % ntask))
n_for_this_task++;
offset += n_for_this_task;
}
else
{
for(task = readTask; task <= lastTask; task++)
{
n_for_this_task = n_in_file / ntask;
if((task - readTask) < (n_in_file % ntask))
n_for_this_task++;
if(task == ThisTask)
if(NumPart + n_for_this_task > All.MaxPart)
{
printf("too many particles\n");
endrun(1313);
}
do
{
pc = n_for_this_task;
if(pc > blockmaxlen)
pc = blockmaxlen;
if(ThisTask == readTask)
{
if(All.ICFormat == 1 || All.ICFormat == 2)
my_fread(CommBuffer, bytes_per_blockelement, pc, fd);
#ifdef HAVE_HDF5
if(All.ICFormat == 3)
{
get_dataset_name(blocknr, buf);
hdf5_dataset = H5Dopen(hdf5_grp[type], buf);
dims[0] = header.npart[type];
dims[1] = get_values_per_blockelement(blocknr);
if(dims[1] == 1)
rank = 1;
else
rank = 2;
hdf5_dataspace_in_file = H5Screate_simple(rank, dims, NULL);
dims[0] = pc;
hdf5_dataspace_in_memory = H5Screate_simple(rank, dims, NULL);
start[0] = pcsum;
start[1] = 0;
count[0] = pc;
count[1] = get_values_per_blockelement(blocknr);
pcsum += pc;
H5Sselect_hyperslab(hdf5_dataspace_in_file, H5S_SELECT_SET,
start, NULL, count, NULL);
switch (get_datatype_in_block(blocknr))
{
case 0:
hdf5_datatype = H5Tcopy(H5T_NATIVE_UINT);
break;
case 1:
hdf5_datatype = H5Tcopy(H5T_NATIVE_FLOAT);
break;
case 2:
hdf5_datatype = H5Tcopy(H5T_NATIVE_UINT64);
break;
}
H5Dread(hdf5_dataset, hdf5_datatype, hdf5_dataspace_in_memory,
hdf5_dataspace_in_file, H5P_DEFAULT, CommBuffer);
H5Tclose(hdf5_datatype);
H5Sclose(hdf5_dataspace_in_memory);
H5Sclose(hdf5_dataspace_in_file);
H5Dclose(hdf5_dataset);
}
#endif
}
if(ThisTask == readTask && task != readTask)
MPI_Ssend(CommBuffer, bytes_per_blockelement * pc, MPI_BYTE, task, TAG_PDATA,
MPI_COMM_WORLD);
if(ThisTask != readTask && task == ThisTask)
MPI_Recv(CommBuffer, bytes_per_blockelement * pc, MPI_BYTE, readTask,
TAG_PDATA, MPI_COMM_WORLD, &status);
if(ThisTask == task)
{
empty_read_buffer(blocknr, nstart + offset, pc, type);
offset += pc;
}
n_for_this_task -= pc;
}
while(n_for_this_task > 0);
}
}
}
if(ThisTask == readTask)
{
if(All.ICFormat == 1 || All.ICFormat == 2)
{
SKIP2;
if(blksize1 != blksize2)
{
printf("incorrect block-sizes detected!\n");
printf("Task=%d blocknr=%d blksize1=%d blksize2=%d\n", ThisTask, blocknr,
blksize1, blksize2);
fflush(stdout);
endrun(1889);
}
}
}
}
}
}
for(type = 0; type < 6; type++)
{
n_in_file = header.npart[type];
n_for_this_task = n_in_file / ntask;
if((ThisTask - readTask) < (n_in_file % ntask))
n_for_this_task++;
NumPart += n_for_this_task;
if(type == 0)
N_gas += n_for_this_task;
#ifdef SFR
if(type == ST)
N_stars += n_for_this_task;
#endif
}
if(ThisTask == readTask)
{
if(All.ICFormat == 1 || All.ICFormat == 2)
fclose(fd);
#ifdef HAVE_HDF5
if(All.ICFormat == 3)
{
for(type = 5; type >= 0; type--)
if(header.npart[type] > 0)
H5Gclose(hdf5_grp[type]);
H5Fclose(hdf5_file);
}
#endif
}
}
/*! This function determines onto how many files a given snapshot is
* distributed.
*/
int find_files(char *fname)
{
FILE *fd;
char buf[200], buf1[200];
int dummy;
sprintf(buf, "%s.%d", fname, 0);
sprintf(buf1, "%s", fname);
if(All.SnapFormat == 3)
{
sprintf(buf, "%s.%d.hdf5", fname, 0);
sprintf(buf1, "%s.hdf5", fname);
}
#ifndef HAVE_HDF5
if(All.SnapFormat == 3)
{
if(ThisTask == 0)
printf("Code wasn't compiled with HDF5 support enabled!\n");
endrun(0);
}
#endif
header.num_files = 0;
if(ThisTask == 0)
{
if((fd = fopen(buf, "r")))
{
if(All.ICFormat == 1 || All.ICFormat == 2)
{
if(All.ICFormat == 2)
{
fread(&dummy, sizeof(dummy), 1, fd);
fread(&dummy, sizeof(dummy), 1, fd);
fread(&dummy, sizeof(dummy), 1, fd);
fread(&dummy, sizeof(dummy), 1, fd);
}
fread(&dummy, sizeof(dummy), 1, fd);
fread(&header, sizeof(header), 1, fd);
fread(&dummy, sizeof(dummy), 1, fd);
}
fclose(fd);
#ifdef HAVE_HDF5
if(All.ICFormat == 3)
read_header_attributes_in_hdf5(buf);
#endif
}
}
MPI_Bcast(&header, sizeof(header), MPI_BYTE, 0, MPI_COMM_WORLD);
if(header.num_files > 0)
return header.num_files;
if(ThisTask == 0)
{
if((fd = fopen(buf1, "r")))
{
if(All.ICFormat == 1 || All.ICFormat == 2)
{
if(All.ICFormat == 2)
{
fread(&dummy, sizeof(dummy), 1, fd);
fread(&dummy, sizeof(dummy), 1, fd);
fread(&dummy, sizeof(dummy), 1, fd);
fread(&dummy, sizeof(dummy), 1, fd);
}
fread(&dummy, sizeof(dummy), 1, fd);
fread(&header, sizeof(header), 1, fd);
fread(&dummy, sizeof(dummy), 1, fd);
}
fclose(fd);
#ifdef HAVE_HDF5
if(All.ICFormat == 3)
read_header_attributes_in_hdf5(buf1);
#endif
header.num_files = 1;
}
}
MPI_Bcast(&header, sizeof(header), MPI_BYTE, 0, MPI_COMM_WORLD);
if(header.num_files > 0)
return header.num_files;
if(ThisTask == 0)
{
printf("\nCan't find initial conditions file.");
printf("neither as '%s'\nnor as '%s'\n", buf, buf1);
fflush(stdout);
}
endrun(0);
return 0;
}
/*! This function assigns a certain number of files to processors, such that
* each processor is exactly assigned to one file, and the number of cpus per
* file is as homogenous as possible. The number of files may at most be
* equal to the number of processors.
*/
void distribute_file(int nfiles, int firstfile, int firsttask, int lasttask, int *filenr, int *master,
int *last)
{
int ntask, filesleft, filesright, tasksleft, tasksright;
if(nfiles > 1)
{
ntask = lasttask - firsttask + 1;
filesleft = (((double) (ntask / 2)) / ntask) * nfiles;
if(filesleft <= 0)
filesleft = 1;
if(filesleft >= nfiles)
filesleft = nfiles - 1;
filesright = nfiles - filesleft;
tasksleft = ntask / 2;
tasksright = ntask - tasksleft;
distribute_file(filesleft, firstfile, firsttask, firsttask + tasksleft - 1, filenr, master, last);
distribute_file(filesright, firstfile + filesleft, firsttask + tasksleft, lasttask, filenr, master,
last);
}
else
{
if(ThisTask >= firsttask && ThisTask <= lasttask)
{
*filenr = firstfile;
*master = firsttask;
*last = lasttask;
}
}
}
/*! This function reads the header information in case the HDF5 file format is
* used.
*/
#ifdef HAVE_HDF5
void read_header_attributes_in_hdf5(char *fname)
{
hid_t hdf5_file, hdf5_headergrp, hdf5_attribute;
hdf5_file = H5Fopen(fname, H5F_ACC_RDONLY, H5P_DEFAULT);
hdf5_headergrp = H5Gopen(hdf5_file, "/Header");
hdf5_attribute = H5Aopen_name(hdf5_headergrp, "NumPart_ThisFile");
H5Aread(hdf5_attribute, H5T_NATIVE_INT, header.npart);
H5Aclose(hdf5_attribute);
hdf5_attribute = H5Aopen_name(hdf5_headergrp, "NumPart_Total");
H5Aread(hdf5_attribute, H5T_NATIVE_UINT, header.npartTotal);
H5Aclose(hdf5_attribute);
hdf5_attribute = H5Aopen_name(hdf5_headergrp, "NumPart_Total_HighWord");
H5Aread(hdf5_attribute, H5T_NATIVE_UINT, header.npartTotalHighWord);
H5Aclose(hdf5_attribute);
hdf5_attribute = H5Aopen_name(hdf5_headergrp, "MassTable");
H5Aread(hdf5_attribute, H5T_NATIVE_DOUBLE, header.mass);
H5Aclose(hdf5_attribute);
hdf5_attribute = H5Aopen_name(hdf5_headergrp, "Time");
H5Aread(hdf5_attribute, H5T_NATIVE_DOUBLE, &header.time);
H5Aclose(hdf5_attribute);
hdf5_attribute = H5Aopen_name(hdf5_headergrp, "NumFilesPerSnapshot");
H5Aread(hdf5_attribute, H5T_NATIVE_INT, &header.num_files);
H5Aclose(hdf5_attribute);
hdf5_attribute = H5Aopen_name(hdf5_headergrp, "Flag_Entropy_ICs");
H5Aread(hdf5_attribute, H5T_NATIVE_INT, &header.flag_entropy_instead_u);
H5Aclose(hdf5_attribute);
H5Gclose(hdf5_headergrp);
H5Fclose(hdf5_file);
}
#endif

Event Timeline