Page MenuHomec4science

No OneTemporary

File Metadata

Created
Fri, Sep 27, 21:26
This file is larger than 256 KB, so syntax highlighting was skipped.
This document is not UTF8. It was detected as ISO-8859-1 (Latin 1) and converted to UTF8 for display.
diff --git a/Makefile b/Makefile
index e8418f5..4f4283b 100644
--- a/Makefile
+++ b/Makefile
@@ -1,850 +1,850 @@
#----------------------------------------------------------------------
# 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
#--------------------------------------- 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 += -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 += -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"
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
INCL = allvars.h proto.h tags.h Makefile
CFLAGS = $(OPTIONS) $(GSL_INCL) $(FFTW_INCL) $(HDF5INCL)
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)
$(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/TODO b/TODO
index 87c8279..c66ef75 100644
--- a/TODO
+++ b/TODO
@@ -1,989 +1,1119 @@
multiple IMF :
----------
- add parameters
- add code
- add maxlivetime
---> !!! si toutes les étoiles explosent,
la masse de certaines étoiles devient très petite,
voir négative.
--> il faut voir les tables, regarder la perte de masse pour une masse donnée.
new cooling :
----------
--- tester le cooling avec M=4, on devrait avoir Tcool << Tdyn à faire
- ajouter implicit cooling integration ok
+ tester ok, semble bien
- verifier ComovingIntegrationOn à tester
- tester sur cluster à faire
- tester sur boite cosmo à faire
on peut enlever :
DtEgySpecRadSph
DtEntropyRadSph
new sfr :
----------
- crée des étoiles de plus petite masse, et donc, garder la part. de gaz. ok
- utiliser tous les critères, jeans aussi... à faire
- tester un model statique --> loi exp décroissante ok
- transformer toute la particule lorsque elle est trops petite ok
- ecrire les output de StP ok
- prendre en compte l'énergie des étoiles... ok
- conservation de l'énergie ok
1 proc, StarFormationNStarsFromGas = 1 snap00
4 proc, StarFormationNStarsFromGas = 1 snap01 mini diff.
1 proc, StarFormationNStarsFromGas = 4 snap02 sfr correcte, mais
!!! il y a des oscillations...
1 proc, StarFormationNStarsFromGas = 4 snap03 ok, on corrige avec TreeDomainUpdateFrequency = 0
4 proc, StarFormationNStarsFromGas = 4
- permettre : TreeDomainUpdateFrequency > 0 à faire
domain :
----------
- forcer les particules stellaire a etre arrangées dans le block 1 ok
domain.c à faire (difficile)
maxloadsph -> maxloadstars
pour PEANOHILBERT : trier les particules star à faire
peano.c à faire
domain_sumCost -> add local_DomainCountSt à faire (difficile ?)
- modifier StP ok
All.TotN_stars ok
All.MaxPartStars = All.StarFormationNStarsFromGas*All.MaxPartSph ok
+ All.PartAllocFactor * (All.TotN_stars / NTask)
allocate.c ok
All.MaxPartStars
restart.c ok
init.c ok
domain.c ok
starformation.c ok
rearrange_particle_sequence ok
io.c
read_ic.c ok
ok
- vérifier les output ok
int flag_sfr
int flag_feedback
int flag_cooling
int flag_stellarage
int flag_metals
typelist[6] ok
--> 0 si aucune particule de ce type est présente dans le block
get_particles_in_block ok
- vérifier les input ok
- partir avec un fichier qui contiend déjà des étoiles
--> conditions initiales (lit qu'une partie...) ok
--> redémarrage
- partir avec un fichier qui contiend déjà la métalicité du gaz
--> conditions initiales
--> redémarrage
- tester All.TotN_stars ok
- N_stars ok
chimie :
----------
- pour une part. d'étoile, trouver les plus proches particules de gaz ok
- il faut calculer hsml/density (gaz) pour les étoiles... ok
- dans do_chimie, commencer la boucle par la première étoile ok
et non particule
- verifier le bon nombre de voisins pour les étoiles ok
stars_density.c ok
chimie.c ok
tests :
- vérifier la densité (écrire) ok
- vérifier hsml (écrire) ok
-> on écrit dans le fichier de sortie Density,Hsml ok
- vérifier les plus proches voisins ok
--> dans chimie,
-> vérifier : Sum m/rho wij = 1, par example... ok
- initialisation
utiliser get_nelts pour avoir NELEMENTS, ou alors, check.... à faire
- pour une particule stellaire, calculer à faire
- la masse totale ejectée ok
- les métaux éjectés ok
- l'énergie éjectée ok
- injecter la masse au plus proches voisins ok
- enlever mass et elt ejecté par une étoile ok
!!! conservation de l'énergie kin,pot, int
!!! conservation de l'impulsion...
!!! conservation de la masse ok
ok, a 1%pres... a vérifier par la suite...
dans des conditions moins difficiles...
<-------- Wed Jul 22 15:09:25 CEST 2009
- mieux conserver l'énergie lors de feedback thermqie (rendre part. active ?) à faire !!! (ou feedback cinétique...)
- faire un fichier statistique qui comptes ce qui est crée... à faire
- injecter l'énergie thermique ok
- injecter l'énergie cinetique à faire
- utiliser la metallicité pour le cooling ok
- utiliser TreeDomainUpdateFrequency != 0.0 à faire
- vérifier dans chimie.c -> utilisation de vel ou velpred...
- unifier à faire
SolarAbun_Fe = 0.001771 pNbody
SolarAbun_Mg = 0.00091245 pNbody
#define FEH_SOLAR 0.001771 Gadget /* 0.00181 */
#define MGH_SOLAR 0.00091245 Gadget
FeHSolar = 0.00181 Gadget cooling !!!
- vérifier restart -> particulièrement les parametres à faire
??? All.ChimieSupernovaEnergy = all.ChimieSupernovaEnergy
- revoir sticky (faire attention au leap frog, par ex.) à faire
- cooling : on peut completement sortie docooling de timestep, non ?
!! initialisation correcte de : StarEnergyInt,StarEnergyRadSph, à faire
StarEnergyRadSticky...
--> aussi lors d'un restart !!!
--> should be in All.
--------------------------------------------------------------------------------
CPU
--------------------------------------------------------------------------------
timediff(t0, t1) = t1-t0
All.CPU_Total,
run.c : on somme les diff de la boucle principale
All.CPU_Gravity,
accel.c :
gravity_tree()
All.CPU_Hydro,
accel.c :
density()
hydro_force();
All.CPU_Domain,
domain.c :
domain_Decomposition() sans peano_hilbert_order
All.CPU_Potential, potential.c :
compute_potential()
All.CPU_Predict, accel.c :
force_update_hmax(); ???
predic.c :
move_particles()
run.c :
find_next_sync_point_and_drift()
All.CPU_TimeLine, timestep.c :
advance_and_find_timesteps()
All.CPU_Snapshot, io.c
savepositions()
All.CPU_TreeConstruction potential.c
force_treebuild()
gravtree.c
force_treebuild()
All.CPU_TreeWalk, gravtree.c !!!
All.CPU_CommSum, gravtree.c
All.CPU_Imbalance, gravtree.c
All.CPU_TreeWalk += sumt / NTask;
All.CPU_Imbalance += sumimbalance / NTask;
All.CPU_CommSum += sumcomm / NTask;
All.CPU_HydCompWalk, chimie.c density.c hydra.c stars_density.c !!!
All.CPU_HydCommSumm, chimie.c density.c hydra.c stars_density.c
All.CPU_HydImbalance, chimie.c density.c hydra.c stars_density.c
All.CPU_HydImbalance += sumimbalance / NTask;
All.CPU_HydCommSumm += sumcomm / NTask;
All.CPU_HydCompWalk += sumt / NTask;
All.CPU_EnsureNgb, density.c !!!
All.CPU_EnsureNgb += sumtimengb / NTask;
stars_density.c
All.CPU_EnsureNgb += sumtimengb / NTask;
All.CPU_PM, accel.c
long_range_force()
All.CPU_Peano
domain.c : peano_hilbert_order()
on pourait rajouter :
-------------------
All.CPU_Accel
if faut rajouter :
All.CPU_Chimie
All.CPU_StarFormation
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
- sticky bournaud
- faire des tests
- choix du sticky --> pour cluster, mieux dans rayon sph...
- éviter que la densité soit calculée ??? vraiment utiles ?
- conservation de l'énergie pour sticky
----------------------------------------
- improve multiphase computation : only with MULTIPHASE switched on
- test sticky only
* for each particle, find one particle to collide with
* try to do that in the same function than the main hydra (???)
- test sph only
- test dark gas
- test combination of all
check
* indep. of number of proc
##########################################3
MULTIPHASE
##########################################
- part of particles behave differently (sticky)
GAS_SPH -> normal sph
GAS_STICKY -> sticky
GAS_DARK -> no (weak) interaction
functions
multi_hydro_evaluate
sticky_evaluate
ngb_treefind_phase_pairs
io.c ok
init.c ok
read_ic.c ok
run.c ok
density.c ok (rien de particulier)
ngb.c
ngb_treefind_pairs hydra.c
every body sees every body
ngb_treefind_variable density.c
find density and hsml !!!! hsml is then needed to find colliding particules
!!!! but may be problematic if only sph part. are present in hsml !!!
ngb_treefind_phase_pairs bondi_accretion.c
hydra.c !!!!!!!!!!!!
multi_hydro_evaluate(i, 0);
hydro_evaluate(i, 0);
sticky_evaluate(i, 0);
timestep.c
global.c
cooling.c
starformation.c
bubbles.c
##########################################
PHASE_MIXING
##########################################
proto.h
phase_mixing
run.c
phase.c
##########################################
COLDGAS_CYCLE (need MULTIPHASE)
##########################################
- compute cycling or not
---------------------------------------
COLDGAS_CYCLE :parameters
-------------------------
ColdGasCycleTransitionTime;
ColdGasCycleTransitionParameter;
allvars.h ok
begrun.c ok
phase.c ok
##########################################
EXTERNAL_FLUX : really only external flux
##########################################
begrun.c
cooling.c
phase.c
allvars.h
HeatingPeSolarEnergyDensity
HeatingExternalFLuxEnergyDensity
##########################################
STELLAR_FLUX : only stellar flux
##########################################
allvars.h
init.c
gravtree.c
forcetree.c
begrun.c
HeatingPeSolarEnergyDensity;
HeatingPeLMRatioGas;
HeatingPeLMRatioHalo;
HeatingPeLMRatioDisk;
HeatingPeLMRatioBulge;
HeatingPeLMRatioStars;
HeatingPeLMRatioBndry;
HeatingPeLMRatio[6];
####################################################
# sticky_evaluate(i, 0)
####################################################
1) check who can inteact with who ?
- loop over active particles
- ngb_treefind_pairs ! find all particles in h_i ... check !!!
here we could use different fct, depending on the type
- if(P[j].Ti_endstep == All.Ti_Current) only active particles ! ensure symetry,
really necessary ???
- if(SphP[j].Phase == GAS_STICKY) ok, but may be done with "ngb_treefind_pairs"
- if(SphP[j].StickyFlag) SphP[i].StickyFlag = 1; in init.c
SphP[i].StickyFlag is determined in phase.c
2) what is modified by sticky_evaluate
P[target].Vel[k] <------ here, we change the velocity !!!!!!!
P[j].Vel[k]
SphP[target].EgySpecRadSticky <------ here, we count the energy !!!!!!!
SphP[j].EgySpecRadSticky
SphP[target].StickyCollisionNumber++;
SphP[j].StickyCollisionNumber++;
SphP[target].HydroAccel[k] = 0;
SphP[target].StickyFlag = 0;
SphP[target].DtEntropy = 0; /* force dt entropy to zero */
SphP[j].DtEgySpecFeedback = 0; /* should not be there */
!!!! we change the velocity and count energy further
tests:
- only sticky : be sure that particles interact symetrically...
####################################################
# problemes
####################################################
(!!) si Entropy < 0, le gaz est considéré GAS_DARK (output)
-> bien vérifier...
(!!) si une particule oscille frequemment entre dark et visible, elle risque
de colisonner trops souvent... StickyFlag=1 automatique lors du retour au sticky
####################################################
#
# comoving integration
#
####################################################
velocity
-------
gadget-1 : w=sqrt(a)*xp
gadget-2 : u=a*a*xp
################################################
# conversion (comobile -> physical')
################################################
r_p = x_c*a = Pos*a
v_p = x_c*H(a)*a + v_c * a = Pos*H(a)*a + Vel/a (in the code)
v_p = x_c*H(a)*a + v_c * a = Pos*H(a)*a + Vel*sqrt(a) (in the snapshot)
m_p = m_c = Mass
u_p = u_c (need to compute from entropy)
rho_p = rho_c / a^3 = Density/a^3
A = Ap
Pp = Pc * a^(-3 * gamma)
c_c = c_p a^(3(gamma-1))/2
################################################
# conversion (physical' -> physical)
################################################
pos_p = pos_p'/h
mass_p= mass_p'/h
t_p = t_p'/h
vel_p = vel_p'
u_p = u_p'
rho_p = rho_p'*h^2
* where :
starformation.c
---------------
1) .Density
if (SphP[i].Density*a3inv > All.ThresholdDensity)
-> All.ThresholdDensity en terme physical
2) .Vel
!!! FEEDBACK_WIND use Vel ---> bad !
chimie.c
---------------
1) .Density
LocalSysState.EnergyInt1 += P[i].Mass * SphP[i].EntropyPred / (GAMMA_MINUS1) * pow(SphP[i].Density*a3inv, GAMMA_MINUS1);
LocalSysState.EnergyInt2 += P[i].Mass * SphP[i].EntropyPred / (GAMMA_MINUS1) * pow(SphP[i].Density*a3inv, GAMMA_MINUS1);
EgySpec = SphP[i].EntropyPred / GAMMA_MINUS1 * pow(SphP[i].Density*a3inv, GAMMA_MINUS1);
DeltaEntropy = GAMMA_MINUS1*NewEgySpec/pow(SphP[i].Density*a3inv, GAMMA_MINUS1) - SphP[i].EntropyPred;
EgySpec = SphP[j].EntropyPred / GAMMA_MINUS1 * pow(SphP[j].Density*a3inv, GAMMA_MINUS1);
DeltaEntropy = GAMMA_MINUS1*NewEgySpec/pow(SphP[j].Density*a3inv, GAMMA_MINUS1) - SphP[j].EntropyPred;
2) .Vel
!!! chimie_compute_energy_kin
!!! chimie_apply_wind
!!! vj2 += SphP[j].VelPred[k]*SphP[j].VelPred[k];
!!! vi2 += vel[k]*vel[k];
timestep.c
---------------
a bien refaire
cooling.c
---------------
1) Density
CoolingForOne
DoCooling
lambda
2) Vel
no
#################################################
# steps for the entropy
predict.c
dt_drift = get_drift_factor(time0, time1);
dt_gravkick = get_gravkick_factor(time0, time1); -> pour v = a_grav * dt
dt_hydrokick = get_hydrokick_factor(time0, time1); -> pour v = a_hydro * dt
dt_entr = (time1 - (P[i].Ti_begstep + P[i].Ti_endstep) / 2) * All.Timebase_interval;
SphP[i].EntropyPred = (SphP[i].Entropy + SphP[i].DtEntropy * dt_entr);
timestep.c
dt_gravkick = get_gravkick_factor(tstart, tend);
dt_hydrokick = get_hydrokick_factor(tstart, tend);
dt_entr = (tend - tstart) * All.Timebase_interval;
SphP[i].Entropy += SphP[i].DtEntropy * dt_entr;
- que vaut DtEntropy
hydra.c
dtEntropy += 0.5 * hfc_visc * vdotr2;
SphP[i].DtEntropy *= GAMMA_MINUS1 / (hubble_a2 * pow(SphP[i].Density, GAMMA_MINUS1));
et c'est tout !
-------------------------------------------------------
Tue Dec 21 22:37:07 CET 2010
-------------------------------------------------------
dA/dt = SphP[i].DtEntropy * hubble_a
==>
dA/dt * ds/hubble_a
dans le code est ecrit par
SphP[i].DtEntropy * (tend - tstart) * All.Timebase_interval
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
j'ai suivit l'evolution de
SphP[i].DtEntropy * hubble_a
dans le cas d'un système isolé
ou du meme système en comobile,
le resultat est identique !!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/* Conversion into program time unit */
Cp->coeff_z[2][2] = Cp->coeff_z[2][2] + u_lt;
double u_lt;
double UnitLength_in_kpc; ok
double UnitMass_in_Msol; ok
u_lt = -log10( 4.7287e11*sqrt(pow(UnitLength_in_kpc,3)/UnitMass_in_Msol));
treeasph
unit_mass 1.e10 Msol
unit_length 1. kpc
u_lt = -log10( 4.7287d11*SQRT(unit_length**3/unit_mass))
u_lt : unit_local_time ? calculé a partir de G=1 ???
u_lt = 4728700.0 unit time in yr
d'ou vient :
4.7287d11 =
time unit = 4.72e6 ans
All.G = GRAVITY / pow(All.UnitLength_in_cm, 3) * All.UnitMass_in_g * pow(All.UnitTime_in_s, 2);
GRAVITY 6.672e-8
UnitTime_in_s = sqrt ( pow(UnitLength_in_cm, 3)/GRAVITY /UnitMass_in_g )
SEC_PER_MEGAYEAR=3.155e13
UnitLength_in_cm =3.085678e+21
UnitVelocity_in_cm_per_s =100000.0
UnitTime_in_s = UnitLength_in_cm / UnitVelocity_in_cm_per_s;
UnitTime_in_Megayears = UnitTime_in_s / SEC_PER_MEGAYEAR;
u_lt = -log10(UnitTime_in_Megayears/1e6)
5.3262507580106977
c Conversion into program time unit
coeff_z(3,3) = coeff_z(3,3) + u_lt
minlivetime maxlivetime
unite treeasph : 0.828579 5.64403e+08
4.72
==> Myr : 3.9108 2.6639e+09
première étoile : 16.8457 = 79.511 Myr
première sn : 17.6926 = 83.50 Myr
_________________________________________________________________
minlivetime maxlivetime
unite gadget : 0.00400612 2.72885e+06
978.027
==> Myr 3.918 2.668e+08
6.96579
première étoile : 7.04278 = 75.28
première sn : 7.06
isolated
--------
StP[m].FormationTime : myr formation de la ssp
minlivetime : myr temps de vie minimum
maxlivetime : myr temps de vie maximum
tmin : myr temps minimum d'exection
tmax : myr temps maximum d'exection
t1 : myr debut du pas de temps
t2 : myr find du pas de temps
il y a chimie, lorsque
1) tmin < t1 && tmax >=t1 debut du pas de temps dans l'interval [tmin,tmax]
tmin <=t2 && tmax > t2 find du pas de temps dans l'interval [tmin,tmax]
tmin >=t1 && tmax <=t2 t1,t2 hord de [tmin,tmax]
starf of sfr
0.708
+################################################################################
+# passage unite en h -> unités physiques
+################################################################################
+pos_p = pos_p'/h
+mass_p= mass_p'/h
+t_p = t_p'/h
+rho_p = rho_p'*h^2
+e_p = e_p'/h
+
+vel_p = vel_p'
+u_p = u_p'
+
+
+# parties a modifier :
+
+
+* starformation.c
+#################
+
+All.ThresholdDensity -> unite de h
+All.StarFormationDensity -> unite de h
+
+ --> rien a faire
+
+
+* cooling.c
+#################
+
+ --> lambda
+
+ nHcgs -> nHcgs*h^2 ok
+
+ All.mumh/All.Boltzmann ok indep de h
+
+ T= All.mumh/All.Boltzmann * GAMMA_MINUS1 * Entropy ok indep de h
+
+ l = cooling_function_with_metals ok ne dép que de T et Fe
+
+ !! l doit etre converti en unité h
+
+ l = l * h**3
+ l = l * nH2 si nH2 est en unité h oui
+
+ l = l * h**3
+ l = l * nH2h**2 si nH2 a été exprimé en unité normales ok ICI
+
+
+
+* chimie.c
+#################
+* !!! toutes les grandeurs liées au temps
+
+ minlivetime = star_lifetime(StP[m].Metal[NELEMENTS-1],Cp->Mmax*SOLAR_MASS/All.UnitMass_in_g);
+ maxlivetime = star_lifetime(StP[m].Metal[NELEMENTS-1],Cp->Mmin*SOLAR_MASS/All.UnitMass_in_g);
+
+ -> doit etre converti en h
+
+ minlivetime = minlivetime*h
+ maxlivetime = maxlivetime*h
+
+ suite :
+
+ comparaison t01 t02 -> ok
+
+ # star_mass_from_age prend des valeur non h
+ m2 = star_mass_from_age(StP[m].Metal[NELEMENTS-1],t01/h); !!!
+ m1 = star_mass_from_age(StP[m].Metal[NELEMENTS-1],t02/h); !!!
+
+ m1, n2 seront en non h
+
+ Total_mass_ejection -> M0/h
+ EjectedMass = EjectedMass*h
+
+
+ le reste devrait etre bon...
+
+
+
+ __________> a vérifier... et à réfléchir...
+
+
+
+# tests
+- prendre une simulation avec unités sans h,
+
+ -> transformer en unité avec h
+ pos = pos*h
+ vel = vel
+ mass = mass*h
+ u = u
+ rho = rho/h**2
+
+ -> transformer les parametes (qui doivent etre en unité de h dans le code)
+ pos = pos*h
+ rho = rho/h**2
+ t = t/h
+ e = e*h
+
+
+ HubbleParam ok
+ BoxSize ok
+ TimeBetSnapshot ok
+ TimeOfFirstSnapshot ok
+ TimeBetStatistics ok
+ MaxSizeTimestep ok
+ MinSizeTimestep ok
+ All.HubbleParam
+
+ StickyDensity non -> convertir dans le code ok
+ StarFormationTime non -> convertir dans le code ok
+ StarFormationDensity non -> convertir dans le code ok
+ ChimieMaxSizeTimestep non -> convertir dans le code ok
+ ChimieWindTime non -> convertir dans le code ok
+ ChimieThermalTime non -> convertir dans le code ok
+ ChimieSupernovaEnergy non -> convertir dans le code ok
+
+
+ SofteningGas ok
+ SofteningHalo
+ SofteningDisk
+ SofteningBulge
+ SofteningStars
+ SofteningBndry
+
+ SofteningGasMaxPhys ok
+ SofteningHaloMaxPhys
+ SofteningDiskMaxPhys
+ SofteningBulgeMaxPhys
+ SofteningStarsMaxPhys
+ SofteningBndryMaxPhys
diff --git a/allvars.h b/allvars.h
index 20ad4d8..658e547 100644
--- a/allvars.h
+++ b/allvars.h
@@ -1,1630 +1,1630 @@
/*! \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 MAXNELEMENTS 64
#define FIRST_ELEMENT "Fe"
#define FE 0
#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_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. */
/* 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[9][171];
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/begrun.c b/begrun.c
index 05d2577..907a8ff 100644
--- a/begrun.c
+++ b/begrun.c
@@ -1,2053 +1,2031 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <mpi.h>
#include <sys/types.h>
#include <unistd.h>
#include <gsl/gsl_rng.h>
#include "allvars.h"
#include "proto.h"
/*! \file begrun.c
* \brief initial set-up of a simulation run
*
* This file contains various functions to initialize a simulation run. In
* particular, the parameterfile is read in and parsed, the initial
* conditions or restart files are read, and global variables are
* initialized to their proper values.
*/
/*! This function performs the initial set-up of the simulation. First, the
* parameterfile is set, then routines for setting units, reading
* ICs/restart-files are called, auxialiary memory is allocated, etc.
*/
void begrun(void)
{
struct global_data_all_processes all;
#ifdef DETAILED_CPU
double tstart,tend;
tstart = second();
#endif
if(ThisTask == 0)
{
printf("\nThis is Gadget, version `%s'.\n", GADGETVERSION);
printf("\nRunning on %d processors.\n", NTask);
}
read_parameter_file(ParameterFile); /* ... read in parameters for this run */
allocate_commbuffers(); /* ... allocate buffer-memory for particle
exchange during force computation */
set_units();
#if defined(PERIODIC) && (!defined(PMGRID) || defined(FORCETEST))
ewald_init();
#endif
open_outputfiles();
random_generator = gsl_rng_alloc(gsl_rng_ranlxd1);
#ifdef RANDOMSEED_AS_PARAMETER
if(ThisTask == 0)
printf("Using %d as initial random seed\n",All.RandomSeed);
gsl_rng_set(random_generator, All.RandomSeed); /* start-up seed */
#else
printf("Using %d as initial random seed\n",42);
gsl_rng_set(random_generator, 42); /* start-up seed */
#endif
#ifdef PMGRID
long_range_init();
#endif
All.TimeLastRestartFile = CPUThisRun;
#ifdef MULTIPHASE
All.StickyLastCollisionTime = -1;
#endif
/* other physics initialization */
#ifdef COOLING
if (All.CoolingType==0) /* sutherland */
{
if(ThisTask == 0) printf("Initialize cooling function...\n");
init_cooling(0);
if(ThisTask == 0) printf("Initialize cooling function done.\n");
}
if (All.CoolingType==2) /* cooling with metals */
{
if(ThisTask == 0) printf("Initialize cooling function...\n");
init_cooling_with_metals();
if(ThisTask == 0) printf("Initialize cooling function done.\n");
}
+
#endif
#ifdef CHIMIE
int i;
if(ThisTask == 0) printf("Initialize chimie...\n");
init_chimie();
check_chimie();
if(ThisTask == 0)
{
for (i=0;i<get_nelts();i++)
printf("solar abundance %s\t= %g\n",get_Element(i),get_SolarAbundance(i));
}
if(ThisTask == 0) printf("Initialize chimie done...\n");
-#ifdef COOLING
- All.CoolingParameters_FeHSolar = get_SolarAbundance(FE); /* for consitency, use the value defined in chimie file */
-#endif
#endif
-
+#ifdef COOLING
+#ifdef CHIMIE
+ All.CoolingParameters_FeHSolar = get_SolarAbundance(FE); /* for consitency, use the value defined in chimie file */
+#else
+ All.CoolingParameters_FeHSolar = FEH_SOLAR; /* use a default value */
+#endif
+#endif
+
+
if(RestartFlag == 0 || RestartFlag == 2)
{
set_random_numbers();
init(); /* ... read in initial model */
init_local_sys_state();
}
else
{
all = All; /* save global variables. (will be read from restart file) */
restart(RestartFlag); /* ... read restart file. Note: This also resets
all variables in the struct `All'.
However, during the run, some variables in the parameter
file are allowed to be changed, if desired. These need to
copied in the way below.
Note: All.PartAllocFactor is treated in restart() separately.
*/
/* yr
if we want a parameter to be taken as the one written in the parameter file,
we have to save it below,
instead, the value of the restart file will be taken.
This is usefull, for example, if stop a run and want it to be restarted with
different parameters.
*/
All.MinSizeTimestep = all.MinSizeTimestep;
All.MaxSizeTimestep = all.MaxSizeTimestep;
All.BufferSize = all.BufferSize;
All.BunchSizeForce = all.BunchSizeForce;
All.BunchSizeDensity = all.BunchSizeDensity;
All.BunchSizeHydro = all.BunchSizeHydro;
All.BunchSizeDomain = all.BunchSizeDomain;
#ifdef MULTIPHASE
All.BunchSizeSticky = all.BunchSizeSticky;
#endif
#ifdef CHIMIE
All.BunchSizeChimie = all.BunchSizeChimie;
#endif
All.TimeLimitCPU = all.TimeLimitCPU;
All.ResubmitOn = all.ResubmitOn;
All.TimeBetSnapshot = all.TimeBetSnapshot;
All.TimeBetStatistics = all.TimeBetStatistics;
All.CpuTimeBetRestartFile = all.CpuTimeBetRestartFile;
All.ErrTolIntAccuracy = all.ErrTolIntAccuracy;
All.MaxRMSDisplacementFac = all.MaxRMSDisplacementFac;
All.ErrTolForceAcc = all.ErrTolForceAcc;
All.TypeOfTimestepCriterion = all.TypeOfTimestepCriterion;
All.TypeOfOpeningCriterion = all.TypeOfOpeningCriterion;
All.NumFilesWrittenInParallel = all.NumFilesWrittenInParallel;
All.TreeDomainUpdateFrequency = all.TreeDomainUpdateFrequency;
All.SnapFormat = all.SnapFormat;
All.NumFilesPerSnapshot = all.NumFilesPerSnapshot;
All.MaxNumNgbDeviation = all.MaxNumNgbDeviation;
All.ArtBulkViscConst = all.ArtBulkViscConst;
All.OutputListOn = all.OutputListOn;
All.CourantFac = all.CourantFac;
All.OutputListLength = all.OutputListLength;
memcpy(All.OutputListTimes, all.OutputListTimes, sizeof(double) * All.OutputListLength);
#ifdef RANDOMSEED_AS_PARAMETER
All.RandomSeed = all.RandomSeed;
#endif
#ifdef MULTIPHASE
All.CriticalTemperature = all.CriticalTemperature;
All.CriticalNonCollisionalTemperature = all.CriticalNonCollisionalTemperature;
All.StickyUseGridForCollisions = all.StickyUseGridForCollisions;
All.StickyTime = all.StickyTime;
All.StickyCollisionTime = all.StickyCollisionTime;
All.StickyIdleTime = all.StickyIdleTime;
All.StickyMinVelocity = all.StickyMinVelocity;
All.StickyMaxVelocity = all.StickyMaxVelocity;
All.StickyLambda = all.StickyLambda;
All.StickyDensity = all.StickyDensity;
All.StickyDensityPower = all.StickyDensityPower;
All.StickyRsphFact = all.StickyRsphFact;
All.StickyBetaR = all.StickyBetaR;
All.StickyBetaT = all.StickyBetaT;
All.StickyGridNx = all.StickyGridNx;
All.StickyGridNy = all.StickyGridNy;
All.StickyGridNz = all.StickyGridNz;
All.StickyGridXmin = all.StickyGridXmin;
All.StickyGridXmax = all.StickyGridXmax;
All.StickyGridYmin = all.StickyGridYmin;
All.StickyGridYmax = all.StickyGridYmax;
All.StickyGridZmin = all.StickyGridZmin;
All.StickyGridZmax = all.StickyGridZmax;
#ifdef COLDGAS_CYCLE
All.ColdGasCycleTransitionTime = all.ColdGasCycleTransitionTime;
All.ColdGasCycleTransitionParameter = all.ColdGasCycleTransitionParameter;
#endif
#endif
#ifdef OUTERPOTENTIAL
#ifdef NFW
All.HaloConcentration = all.HaloConcentration;
All.HaloMass = all.HaloMass;
All.GasMassFraction = all.GasMassFraction;
#endif
#ifdef PLUMMER
All.PlummerMass = all.PlummerMass;
All.PlummerSoftenning = all.PlummerSoftenning;
#endif
#ifdef MIYAMOTONAGAI
All.MiyamotoNagaiMass = all.MiyamotoNagaiMass;
All.MiyamotoNagaiHr = all.MiyamotoNagaiHr;
All.MiyamotoNagaiHz = all.MiyamotoNagaiHz;
#endif
#ifdef PISOTHERM
All.Rho0 = all.Rho0;
All.Rc = all.Rc;
All.GasMassFraction = all.GasMassFraction;
#endif
#ifdef CORIOLIS
All.CoriolisOmegaX0 = all.CoriolisOmegaX0;
All.CoriolisOmegaY0 = all.CoriolisOmegaY0;
All.CoriolisOmegaZ0 = all.CoriolisOmegaZ0;
#endif
#endif
#ifdef SFR
//All.StarFormationNStarsFromGas = all.StarFormationNStarsFromGas; /* do not change the param. if restarting, else, StarFormationStarMass will be wrong */
//All.StarFormationStarMass = all.StarFormationStarMass;
All.StarFormationMgMsFraction = all.StarFormationMgMsFraction;
All.StarFormationType = all.StarFormationType;
All.StarFormationCstar = all.StarFormationCstar;
All.StarFormationTime = all.StarFormationTime;
All.StarFormationDensity = all.StarFormationDensity;
All.StarFormationTemperature = all.StarFormationTemperature;
All.ThresholdDensity = all.ThresholdDensity;
#endif
#ifdef COOLING
All.CoolingType = all.CoolingType;
All.CutofCoolingTemperature = all.CutofCoolingTemperature;
All.InitGasMetallicity = all.InitGasMetallicity;
#endif
#ifdef CHIMIE
All.ChimieSupernovaEnergy = all.ChimieSupernovaEnergy; /* do not use this value, use the restartfile one */
All.ChimieKineticFeedbackFraction = all.ChimieKineticFeedbackFraction;
All.ChimieWindSpeed = all.ChimieWindSpeed;
All.ChimieWindTime = all.ChimieWindTime;
All.ChimieThermalTime = all.ChimieThermalTime;
All.ChimieMaxSizeTimestep = all.ChimieMaxSizeTimestep;
#endif
#if defined (HEATING_PE)
All.HeatingPeElectronFraction = all.HeatingPeElectronFraction;
#endif
#if defined (HEATING_PE) || defined (STELLAR_FLUX) || defined (EXTERNAL_FLUX)
All.HeatingPeSolarEnergyDensity = all.HeatingPeSolarEnergyDensity;
#endif
#if defined (HEATING_PE) || defined (STELLAR_FLUX)
All.HeatingPeLMRatioGas = all.HeatingPeLMRatioGas;
All.HeatingPeLMRatioHalo = all.HeatingPeLMRatioHalo;
All.HeatingPeLMRatioDisk = all.HeatingPeLMRatioDisk;
All.HeatingPeLMRatioBulge = all.HeatingPeLMRatioBulge;
All.HeatingPeLMRatioStars = all.HeatingPeLMRatioStars;
All.HeatingPeLMRatioBndry = all.HeatingPeLMRatioBndry;
All.HeatingPeLMRatio[0] = all.HeatingPeLMRatio[0];
All.HeatingPeLMRatio[1] = all.HeatingPeLMRatio[1];
All.HeatingPeLMRatio[2] = all.HeatingPeLMRatio[2];
All.HeatingPeLMRatio[3] = all.HeatingPeLMRatio[3];
All.HeatingPeLMRatio[4] = all.HeatingPeLMRatio[4];
All.HeatingPeLMRatio[5] = all.HeatingPeLMRatio[5];
#endif
#ifdef EXTERNAL_FLUX
All.HeatingExternalFLuxEnergyDensity = all.HeatingExternalFLuxEnergyDensity;
#endif
#ifdef FEEDBACK
All.SupernovaEgySpecPerMassUnit = all.SupernovaEgySpecPerMassUnit;
All.SupernovaFractionInEgyKin = all.SupernovaFractionInEgyKin;
All.SupernovaTime = all.SupernovaTime;
#endif
#ifdef FEEDBACK_WIND
All.SupernovaWindEgySpecPerMassUnit = all.SupernovaWindEgySpecPerMassUnit;
All.SupernovaWindFractionInEgyKin = all.SupernovaWindFractionInEgyKin;
All.SupernovaWindParameter = all.SupernovaWindParameter;
All.SupernovaWindIntAccuracy = all.SupernovaWindIntAccuracy;
#endif
#ifdef BUBBLES
All.BubblesDelta = all.BubblesDelta;
All.BubblesAlpha = all.BubblesAlpha;
All.BubblesRadiusFactor = all.BubblesRadiusFactor;
All.BubblesR = all.BubblesR;
#endif
#ifdef AGN_HEATING
All.AGNHeatingPower = all.AGNHeatingPower;
All.AGNHeatingRmax = all.AGNHeatingRmax;
#endif
#ifdef AGN_ACCRETION
All.TimeBetAccretion = all.TimeBetAccretion;
All.AccretionRadius = all.AccretionRadius;
All.AGNFactor = all.AGNFactor;
All.MinMTotInRa = all.MinMTotInRa;
#endif
#ifdef BONDI_ACCRETION
All.BondiEfficiency = all.BondiEfficiency;
All.BondiBlackHoleMass = all.BondiBlackHoleMass;
All.BondiHsmlFactor = all.BondiHsmlFactor;
All.BondiPower = all.BondiPower;
All.BondiTimeBet = all.BondiTimeBet;
#endif
strcpy(All.ResubmitCommand, all.ResubmitCommand);
strcpy(All.OutputListFilename, all.OutputListFilename);
strcpy(All.OutputDir, all.OutputDir);
strcpy(All.RestartFile, all.RestartFile);
strcpy(All.EnergyFile, all.EnergyFile);
#ifdef SYSTEMSTATISTICS
strcpy(All.SystemFile, all.SystemFile);
#endif
strcpy(All.InfoFile, all.InfoFile);
strcpy(All.CpuFile, all.CpuFile);
strcpy(All.LogFile, all.LogFile);
#ifdef SFR
strcpy(All.SfrFile, all.SfrFile);
#endif
#ifdef CHIMIE
strcpy(All.ChimieFile, all.ChimieFile);
#endif
#ifdef MULTIPHASE
strcpy(All.PhaseFile, all.PhaseFile);
strcpy(All.StickyFile, all.StickyFile);
#endif
#ifdef AGN_ACCRETION
strcpy(All.AccretionFile, all.AccretionFile);
#endif
#ifdef BONDI_ACCRETION
strcpy(All.BondiFile, all.BondiFile);
#endif
#ifdef BUBBLES
strcpy(All.BubbleFile, all.BubbleFile);
#endif
strcpy(All.TimingsFile, all.TimingsFile);
strcpy(All.SnapshotFileBase, all.SnapshotFileBase);
if(All.TimeMax != all.TimeMax)
readjust_timebase(All.TimeMax, all.TimeMax);
}
#ifdef PMGRID
long_range_init_regionsize();
#endif
if(All.ComovingIntegrationOn)
init_drift_table();
#ifdef COSMICTIME
if(All.ComovingIntegrationOn)
{
if (ThisTask==0)
printf("Initialize cosmic table\n");
init_cosmictime_table();
if (ThisTask==0)
printf("Initialize cosmic table done.\n");
}
#endif
if(RestartFlag == 2)
All.Ti_nextoutput = find_next_outputtime(All.Ti_Current + 1);
else
All.Ti_nextoutput = find_next_outputtime(All.Ti_Current);
All.TimeLastRestartFile = CPUThisRun;
/* other initialization for special behavior */
#ifdef SFR
if (ThisTask == 0)
printf("StarFormationStarMass = %g\n\n",All.StarFormationStarMass);
#endif
#ifdef OUTERPOTENTIAL
if(ThisTask == 0) printf("Initialize outer potential...\n");
init_outer_potential();
if(ThisTask == 0) printf("Initialize outer potential done.\n");
#endif
#ifdef BUBBLES
if(ThisTask == 0) printf("Initialize bubble function...\n");
init_bubble();
if(ThisTask == 0) printf("Initialize bubble function done.\n");
#endif
#ifdef MULTIPHASE
if(ThisTask == 0) printf("Initialize sticky...\n");
header.critical_energy_spec = All.CriticalEgySpec;
init_sticky();
if(ThisTask == 0) printf("Initialize sticky done.\n");
#endif
#ifdef DETAILED_CPU
tend = second();
All.CPU_Begrun += timediff(tstart, tend);
All.CPU_Begrun -= All.CPU_Leapfrog;
All.CPU_Begrun -= All.CPU_Domain;
All.CPU_Begrun -= All.CPU_Snapshot;
#endif
}
/*! Computes conversion factors between internal code units and the
* cgs-system.
*/
void set_units(void)
{
double meanweight;
All.UnitTime_in_s = All.UnitLength_in_cm / All.UnitVelocity_in_cm_per_s;
All.UnitTime_in_Megayears = All.UnitTime_in_s / SEC_PER_MEGAYEAR;
if(All.GravityConstantInternal == 0)
All.G = GRAVITY / pow(All.UnitLength_in_cm, 3) * All.UnitMass_in_g * pow(All.UnitTime_in_s, 2);
else
All.G = All.GravityConstantInternal;
All.UnitDensity_in_cgs = All.UnitMass_in_g / pow(All.UnitLength_in_cm, 3);
All.UnitPressure_in_cgs = All.UnitMass_in_g / All.UnitLength_in_cm / pow(All.UnitTime_in_s, 2);
All.UnitCoolingRate_in_cgs = All.UnitPressure_in_cgs / All.UnitTime_in_s;
All.UnitEnergy_in_cgs = All.UnitMass_in_g * pow(All.UnitLength_in_cm, 2) / pow(All.UnitTime_in_s, 2);
/* convert some physical input parameters to internal units */
All.Hubble = HUBBLE * All.UnitTime_in_s;
meanweight = 4.0 / (1 + 3 * HYDROGEN_MASSFRAC); /* note: we assume neutral gas here */
/*meanweight = 4 / (8 - 5 * (1 - HYDROGEN_MASSFRAC));*/ /* note: we assume FULL ionized gas here */
All.Boltzmann = BOLTZMANN /All.UnitEnergy_in_cgs;
All.ProtonMass = PROTONMASS/All.UnitMass_in_g;
All.mumh = All.ProtonMass*meanweight;
#ifdef MULTIPHASE
- if (All.ComovingIntegrationOn)
- All.StickyTime *= 3.1536e+13*All.HubbleParam/All.UnitTime_in_s; /* Myr to code unit */
- else
- All.StickyTime *= 3.1536e+13/All.UnitTime_in_s; /* Myr to code unit */
-
- if (All.ComovingIntegrationOn)
- All.StickyCollisionTime *= 3.1536e+13*All.HubbleParam/All.UnitTime_in_s; /* Myr to code unit */
- else
- All.StickyCollisionTime *= 3.1536e+13/All.UnitTime_in_s; /* Myr to code unit */
-
- if (All.ComovingIntegrationOn)
- All.StickyIdleTime *= 3.1536e+13*All.HubbleParam/All.UnitTime_in_s; /* Myr to code unit */
- else
- All.StickyIdleTime *= 3.1536e+13/All.UnitTime_in_s; /* Myr to code unit */
-
-
- if (All.ComovingIntegrationOn)
- {
- All.StickyMinVelocity *= 100000/All.UnitTime_in_s; /* km/s to code unit */
- printf("here, you must check the unit conversion !");
- endrun(9876);
- }
- else
- All.StickyMinVelocity *= 100000/All.UnitVelocity_in_cm_per_s; /* km/s to code unit */
-
- if (All.ComovingIntegrationOn)
- {
- All.StickyMaxVelocity *= 100000/All.UnitTime_in_s; /* km/s to code unit */
- printf("here, you must check the unit conversion !");
- endrun(9876);
- }
- else
- All.StickyMaxVelocity *= 100000/All.UnitVelocity_in_cm_per_s; /* km/s to code unit */
+ All.StickyTime *= 3.1536e+13*All.HubbleParam/All.UnitTime_in_s; /* Myr to code unit */
+ All.StickyCollisionTime *= 3.1536e+13*All.HubbleParam/All.UnitTime_in_s; /* Myr to code unit */
+ All.StickyIdleTime *= 3.1536e+13*All.HubbleParam/All.UnitTime_in_s; /* Myr to code unit */
+ All.StickyMinVelocity *=1e5/All.UnitVelocity_in_cm_per_s; /* km/s to code unit */
+ All.StickyMaxVelocity *=1e5/All.UnitVelocity_in_cm_per_s; /* km/s to code unit */
if (All.StickyTime==0)
All.StickyLambda = 0;
else
All.StickyLambda = 1./All.StickyTime;
- All.CriticalEgySpec = 1./GAMMA_MINUS1 * All.Boltzmann/All.mumh * All.CriticalTemperature;
- All.CriticalNonCollisionalEgySpec = 1./GAMMA_MINUS1 * All.Boltzmann/All.mumh * All.CriticalNonCollisionalTemperature;
- All.StickyDensity = All.StickyDensity/All.UnitDensity_in_cgs;
+ All.CriticalEgySpec = 1./GAMMA_MINUS1 * All.Boltzmann/All.mumh * All.CriticalTemperature;
+ All.CriticalNonCollisionalEgySpec = 1./GAMMA_MINUS1 * All.Boltzmann/All.mumh * All.CriticalNonCollisionalTemperature;
+ All.StickyDensity = All.StickyDensity/All.UnitDensity_in_cgs/(All.HubbleParam*All.HubbleParam);
-// if((All.StickyLambda > 0.1/All.MaxSizeTimestep)&&(ThisTask==0))
-// {
-// printf("\nStickyLambda is to big and you may experiment numerical problems !\n");
-// printf("You should either decrease StickyLambda or decrease MaxSizeTimestep.\n");
-// printf("(StickyLambda=%g,maxStickyLambda=%g)\n",All.StickyLambda,0.01/All.MaxSizeTimestep);
-// printf("try \n");
-// printf("StickyLambda <= %g or MaxSizeTimestep <= %g \n",(0.01/All.MaxSizeTimestep),(0.01/All.StickyLambda));
-// fflush(stdout);
-// endrun(121212);
-// }
+
+//if((All.StickyLambda > 0.1/All.MaxSizeTimestep)&&(ThisTask==0))
+// {
+// printf("\nStickyLambda is to big and you may experiment numerical problems !\n");
+// printf("You should either decrease StickyLambda or decrease MaxSizeTimestep.\n");
+// printf("(StickyLambda=%g,maxStickyLambda=%g)\n",All.StickyLambda,0.01/All.MaxSizeTimestep);
+// printf("try \n");
+// printf("StickyLambda <= %g or MaxSizeTimestep <= %g \n",(0.01/All.MaxSizeTimestep),(0.01/All.StickyLambda));
+// fflush(stdout);
+// endrun(121212);
+// }
#ifdef COLDGAS_CYCLE
- if (All.ComovingIntegrationOn)
- All.ColdGasCycleTransitionTime *= 3.1536e+13*All.HubbleParam/All.UnitTime_in_s; /* Myr to code unit */
- else
- All.ColdGasCycleTransitionTime *= 3.1536e+13/All.UnitTime_in_s; /* Myr to code unit */
+ All.ColdGasCycleTransitionTime *= 3.1536e+13*All.HubbleParam/All.UnitTime_in_s; /* Myr to code unit */
#endif
#endif
+
#ifdef SFR
- All.StarFormationTime = All.StarFormationTime/All.UnitTime_in_s * 3.1536e16;
- All.StarFormationDensity = All.StarFormationDensity/All.UnitDensity_in_cgs;
+ All.StarFormationTime = All.StarFormationTime/All.UnitTime_in_s * 3.1536e16*All.HubbleParam;
+ All.StarFormationDensity = All.StarFormationDensity/All.UnitDensity_in_cgs/(All.HubbleParam*All.HubbleParam);
#endif
+
#if defined (HEATING_PE) || defined (STELLAR_FLUX)
- All.HeatingPeLMRatio[0] = All.HeatingPeLMRatioGas;
- All.HeatingPeLMRatio[1] = All.HeatingPeLMRatioHalo;
- All.HeatingPeLMRatio[2] = All.HeatingPeLMRatioDisk;
- All.HeatingPeLMRatio[3] = All.HeatingPeLMRatioBulge;
- All.HeatingPeLMRatio[4] = All.HeatingPeLMRatioStars;
- All.HeatingPeLMRatio[5] = All.HeatingPeLMRatioBndry;
-
- int k;
- for (k=0;k<6;k++)
- {
- All.HeatingPeLMRatio[k] *= 1./SOLAR_MASS; /* erg/s/Msol to erg/s/g */
- All.HeatingPeLMRatio[k] *= All.UnitMass_in_g*All.UnitTime_in_s / All.UnitEnergy_in_cgs; /* erg/s/g to code unit */
- }
+ All.HeatingPeLMRatio[0] = All.HeatingPeLMRatioGas;
+ All.HeatingPeLMRatio[1] = All.HeatingPeLMRatioHalo;
+ All.HeatingPeLMRatio[2] = All.HeatingPeLMRatioDisk;
+ All.HeatingPeLMRatio[3] = All.HeatingPeLMRatioBulge;
+ All.HeatingPeLMRatio[4] = All.HeatingPeLMRatioStars;
+ All.HeatingPeLMRatio[5] = All.HeatingPeLMRatioBndry;
+
+ int k;
+ for (k=0;k<6;k++)
+ {
+ All.HeatingPeLMRatio[k] *= 1./SOLAR_MASS; /* erg/s/Msol to erg/s/g */
+ All.HeatingPeLMRatio[k] *= All.UnitMass_in_g*All.UnitTime_in_s / All.UnitEnergy_in_cgs / All.HubbleParam; /* erg/s/g to code unit */
+ }
#endif
#ifdef FEEDBACK
All.SupernovaEgySpecPerMassUnit *= All.UnitMass_in_g / All.UnitEnergy_in_cgs;
- if (All.ComovingIntegrationOn)
- All.SupernovaTime *= 3.1536e+13*All.HubbleParam/All.UnitTime_in_s; /* Myr to code unit */
- else
- All.SupernovaTime *= 3.1536e+13/All.UnitTime_in_s; /* Myr to code unit */
+ All.SupernovaTime *= 3.1536e+13*All.HubbleParam/All.UnitTime_in_s; /* Myr to code unit */
#endif
#ifdef FEEDBACK_WIND
All.SupernovaWindEgySpecPerMassUnit *= All.UnitMass_in_g / All.UnitEnergy_in_cgs;
All.SupernovaWindSpeed = sqrt( 2*All.SupernovaWindFractionInEgyKin * All.SupernovaWindEgySpecPerMassUnit / All.SupernovaWindParameter );
#endif
#if defined (AGN_ACCRETION) || defined (BONDI_ACCRETION)
All.LightSpeed = C/All.UnitVelocity_in_cm_per_s;
#endif
#ifdef CHIMIE
- All.ChimieSupernovaEnergy = All.ChimieSupernovaEnergy/All.UnitMass_in_g/pow(All.UnitVelocity_in_cm_per_s,2);
+ All.ChimieSupernovaEnergy = All.ChimieSupernovaEnergy/All.UnitMass_in_g/pow(All.UnitVelocity_in_cm_per_s,2)*All.HubbleParam;
All.ChimieWindSpeed = All.ChimieWindSpeed*1e5/All.UnitVelocity_in_cm_per_s;
- All.ChimieWindTime = All.ChimieWindTime*3.1536e13/All.UnitTime_in_s;
- All.ChimieThermalTime = All.ChimieThermalTime*3.1536e13/All.UnitTime_in_s;
- All.ChimieMaxSizeTimestep = All.ChimieMaxSizeTimestep*3.1536e13/All.UnitTime_in_s;
+ All.ChimieWindTime = All.ChimieWindTime*3.1536e13/All.UnitTime_in_s*All.HubbleParam;
+ All.ChimieThermalTime = All.ChimieThermalTime*3.1536e13/All.UnitTime_in_s*All.HubbleParam;
+ All.ChimieMaxSizeTimestep = All.ChimieMaxSizeTimestep*3.1536e13/All.UnitTime_in_s*All.HubbleParam;
#endif
+
+
+
if(ThisTask == 0)
{
printf("\nHubble (internal units) = %g\n", All.Hubble);
printf("G (internal units) = %g\n", All.G);
printf("Boltzmann = %g \n", All.Boltzmann);
printf("ProtonMass = %g \n", All.ProtonMass);
printf("mumh = %g \n", All.mumh);
printf("UnitMass_in_g = %g \n", All.UnitMass_in_g);
printf("UnitTime_in_s = %g \n", All.UnitTime_in_s);
printf("UnitVelocity_in_cm_per_s = %g \n", All.UnitVelocity_in_cm_per_s);
printf("UnitDensity_in_cgs = %g \n", All.UnitDensity_in_cgs);
printf("UnitEnergy_in_cgs = %g \n", All.UnitEnergy_in_cgs);
printf("\n");
#ifdef SFR
printf("StarFormationDensity (internal units) = %g \n", All.StarFormationDensity);
printf("StarFormationTime (internal units) = %g \n", All.StarFormationTime);
#endif
#ifdef FEEDBACK
printf("SupernovaTime (internal units) = %g \n", All.SupernovaTime);
printf("SupernovaEgySpecPerMassUnit (internal units) = %g \n", All.SupernovaEgySpecPerMassUnit);
#endif
#ifdef FEEDBACK_WIND
printf("SupernovaWindEgySpecPerMassUnit (internal units) = %g \n", All.SupernovaWindEgySpecPerMassUnit);
printf("SupernovaWindSpeed (internal units) = %g \n", All.SupernovaWindSpeed);
#endif
#ifdef MULTIPHASE
printf("CriticalEgySpec (internal units) = %g \n", All.CriticalEgySpec);
printf("CriticalNonCollisionalEgySpec (internal units) = %g \n", All.CriticalNonCollisionalEgySpec);
printf("StickyCollisionTime (internal units) = %g \n", All.StickyCollisionTime);
printf("StickyIdleTime (internal units) = %g \n", All.StickyIdleTime);
printf("StickyDensity (internal units) = %g \n", All.StickyDensity);
printf("StickyTime (internal units) = %g \n", All.StickyTime);
printf("StickyMinVelocity (internal units) = %g \n", All.StickyMinVelocity);
printf("StickyMaxVelocity (internal units) = %g \n", All.StickyMaxVelocity);
#endif
#ifdef COLDGAS_CYCLE
printf("ColdGasCycleTransitionTime (internal units) = %g \n", All.ColdGasCycleTransitionTime);
#endif
#ifdef CHIMIE
printf("ChimieSupernovaEnergy (internal units) = %g \n", All.ChimieSupernovaEnergy);
printf("ChimieWindSpeed (internal units) = %g \n", All.ChimieWindSpeed);
printf("ChimieWindTime (internal units) = %g \n", All.ChimieWindTime);
printf("ChimieThermalTime (internal units) = %g \n", All.ChimieThermalTime);
printf("ChimieMaxSizeTimestep (internal units) = %g \n", All.ChimieMaxSizeTimestep);
#endif
printf("\n");
}
#ifdef ISOTHERM_EQS
All.MinEgySpec = 0;
#else
All.MinEgySpec = 1 / meanweight * (1.0 / GAMMA_MINUS1) * (BOLTZMANN / PROTONMASS) * All.MinGasTemp;
All.MinEgySpec *= All.UnitMass_in_g / All.UnitEnergy_in_cgs;
#endif
}
/*! Initialize local system state variables
*/
void init_local_sys_state(void)
{
#ifdef SFR
LocalSysState.StarEnergyInt = 0.;
#ifdef COOLING
LocalSysState.RadiatedEnergy = 0.;
#endif
#endif
#ifdef CHIMIE_THERMAL_FEEDBACK
LocalSysState.EnergyThermalFeedback = 0.;
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
LocalSysState.EnergyKineticFeedback = 0.;
#endif
#ifdef MULTIPHASE
LocalSysState.EnergyRadSticky = 0.;
#endif
#ifdef FEEDBACK_WIND
LocalSysState.EnergyFeedbackWind = 0.;
#endif
}
/*! This function opens various log-files that report on the status and
* performance of the simulstion. On restart from restart-files
* (start-option 1), the code will append to these files.
*/
void open_outputfiles(void)
{
char mode[2], buf[200];
#ifdef ADVANCEDSTATISTICS
int i=0;
#endif
if(ThisTask != 0) /* only the root processor writes to the log files */
return;
if(RestartFlag == 0)
strcpy(mode, "w");
else
strcpy(mode, "a");
sprintf(buf, "%s%s", All.OutputDir, All.CpuFile);
if(!(FdCPU = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
#ifdef ADVANCEDCPUSTATISTICS
else
{
if(RestartFlag == 0) /* write the header */
{
fprintf(FdCPU,"# Step ");
fprintf(FdCPU,"Time ");
fprintf(FdCPU,"nCPUs ");
fprintf(FdCPU,"CPU_Total ");
#ifdef DETAILED_CPU
fprintf(FdCPU,"CPU_Leapfrog ");
fprintf(FdCPU,"CPU_Physics ");
fprintf(FdCPU,"CPU_Residual ");
fprintf(FdCPU,"CPU_Accel ");
fprintf(FdCPU,"CPU_Begrun ");
#endif
fprintf(FdCPU,"CPU_Gravity ");
fprintf(FdCPU,"CPU_Hydro ");
#ifdef COOLING
fprintf(FdCPU,"CPU_Cooling ");
#endif
#ifdef SFR
fprintf(FdCPU,"CPU_StarFormation ");
#endif
#ifdef CHIMIE
fprintf(FdCPU,"CPU_Chimie ");
#endif
#ifdef MULTIPHASE
fprintf(FdCPU,"CPU_Sticky ");
#endif
fprintf(FdCPU,"CPU_Domain ");
fprintf(FdCPU,"CPU_Potential ");
fprintf(FdCPU,"CPU_Predict ");
fprintf(FdCPU,"CPU_TimeLine ");
fprintf(FdCPU,"CPU_Snapshot ");
fprintf(FdCPU,"CPU_TreeWalk ");
fprintf(FdCPU,"CPU_TreeConstruction ");
fprintf(FdCPU,"CPU_CommSum ");
fprintf(FdCPU,"CPU_Imbalance ");
fprintf(FdCPU,"CPU_HydCompWalk ");
fprintf(FdCPU,"CPU_HydCommSumm ");
fprintf(FdCPU,"CPU_HydImbalance ");
fprintf(FdCPU,"CPU_EnsureNgb ");
fprintf(FdCPU,"CPU_PM ");
fprintf(FdCPU,"CPU_Peano ");
#ifdef DETAILED_CPU_DOMAIN
fprintf(FdCPU,"CPU_Domain_findExtend ");
fprintf(FdCPU,"CPU_Domain_determineTopTree ");
fprintf(FdCPU,"CPU_Domain_sumCost ");
fprintf(FdCPU,"CPU_Domain_findSplit ");
fprintf(FdCPU,"CPU_Domain_shiftSplit ");
fprintf(FdCPU,"CPU_Domain_countToGo ");
fprintf(FdCPU,"CPU_Domain_exchange ");
#endif
#ifdef DETAILED_CPU_GRAVITY
fprintf(FdCPU,"CPU_Gravity_TreeWalk1 ");
fprintf(FdCPU,"CPU_Gravity_TreeWalk2 ");
fprintf(FdCPU,"CPU_Gravity_CommSum1 ");
fprintf(FdCPU,"CPU_Gravity_CommSum2 ");
fprintf(FdCPU,"CPU_Gravity_Imbalance1 ");
fprintf(FdCPU,"CPU_Gravity_Imbalance2 ");
#endif
/* return */
fprintf(FdCPU,"\n");
fflush(FdCPU);
}
}
#endif
sprintf(buf, "%s%s", All.OutputDir, All.InfoFile);
if(!(FdInfo = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
sprintf(buf, "%s%s", All.OutputDir, All.LogFile);
if(!(FdLog = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
sprintf(buf, "%s%s", All.OutputDir, All.EnergyFile);
if(!(FdEnergy = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
#ifdef ADVANCEDSTATISTICS
else
{
if(RestartFlag == 0) /* write the header */
{
fprintf(FdEnergy,"# Time EnergyInt EnergyPot EnergyKin ");
#ifdef COOLING
fprintf(FdEnergy,"EnergyRadSph ");
#endif
#ifdef AGN_HEATING
fprintf(FdEnergy,"EnergyAGNHeat ");
#endif
#ifdef MULTIPHASE
fprintf(FdEnergy,"EnergyRadSticky ");
#endif
#ifdef FEEDBACK_WIND
fprintf(FdEnergy,"EnergyFeedbackWind ");
#endif
#ifdef BUBBLES
fprintf(FdEnergy,"EnergyBubbles ");
#endif
#ifdef CHIMIE_THERMAL_FEEDBACK
fprintf(FdEnergy,"EnergyThermalFeedback ");
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
fprintf(FdEnergy,"EnergyKineticFeedback ");
#endif
for (i=0;i<6;i++)
{
fprintf(FdEnergy,"EnergyIntComp%d EnergyPotComp%d EnergyKinComp%d ",i+1,i+1,i+1);
#ifdef COOLING
fprintf(FdEnergy,"EnergyRadSphComp%d ",i+1);
#endif
#ifdef MULTIPHASE
fprintf(FdEnergy,"EnergyRadStickyComp%d ",i+1);
#endif
#ifdef FEEDBACK_WIND
fprintf(FdEnergy,"EnergyFeedbackWindComp%d ",i+1);
#endif
#ifdef BUBBLES
fprintf(FdEnergy,"EnergyBubblesComp%d ",i+1);
#endif
#ifdef CHIMIE_THERMAL_FEEDBACK
fprintf(FdEnergy,"EnergyThermalFeedbackComp%d ",i+1);
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
fprintf(FdEnergy,"EnergyKineticFeedbackComp%d ",i+1);
#endif
}
for (i=0;i<6;i++)
fprintf(FdEnergy,"MassComp%d ",i+1);
/* return */
fprintf(FdEnergy,"\n");
fflush(FdEnergy);
}
}
#endif
#ifdef SYSTEMSTATISTICS
sprintf(buf, "%s%s", All.OutputDir, All.SystemFile);
if(!(FdSystem = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
#endif
sprintf(buf, "%s%s", All.OutputDir, All.TimingsFile);
if(!(FdTimings = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
#ifdef FORCETEST
if(RestartFlag == 0)
{
sprintf(buf, "%s%s", All.OutputDir, "forcetest.txt");
if(!(FdForceTest = fopen(buf, "w")))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
fclose(FdForceTest);
}
#endif
#ifdef SFR
sprintf(buf, "%s%s", All.OutputDir, All.SfrFile);
if(!(FdSfr = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
#endif
#ifdef CHIMIE
sprintf(buf, "%s%s", All.OutputDir, All.ChimieFile);
if(!(FdChimie = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
#endif
#ifdef MULTIPHASE
sprintf(buf, "%s%s", All.OutputDir, All.PhaseFile);
if(!(FdPhase = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
sprintf(buf, "%s%s", All.OutputDir, All.StickyFile);
if(!(FdSticky = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
#endif
#ifdef AGN_ACCRETION
sprintf(buf, "%s%s", All.OutputDir, All.AccretionFile);
if(!(FdAccretion = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
#endif
#ifdef BONDI_ACCRETION
sprintf(buf, "%s%s", All.OutputDir, All.BondiFile);
if(!(FdBondi = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
#endif
#ifdef BUBBLES
sprintf(buf, "%s%s", All.OutputDir, All.BubbleFile);
if(!(FdBubble = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
#endif
}
/*! This function closes the global log-files.
*/
void close_outputfiles(void)
{
if(ThisTask != 0) /* only the root processor writes to the log files */
return;
fclose(FdCPU);
fclose(FdInfo);
fclose(FdLog);
fclose(FdEnergy);
#ifdef SYSTEMSTATISTICS
fclose(FdSystem);
#endif
fclose(FdTimings);
#ifdef FORCETEST
fclose(FdForceTest);
#endif
#ifdef SFR
fclose(FdSfr);
#endif
#ifdef MULTIPHASE
fclose(FdPhase);
fclose(FdSticky);
#endif
#ifdef AGN_ACCRETION
fclose(FdAccretion);
#endif
#ifdef BONDI_ACCRETION
fclose(FdBondi);
#endif
#ifdef BUBBLES
fclose(FdBubble);
#endif
}
/*! This function parses the parameterfile in a simple way. Each paramater
* is defined by a keyword (`tag'), and can be either of type double, int,
* or character string. The routine makes sure that each parameter
* appears exactly once in the parameterfile, otherwise error messages are
* produced that complain about the missing parameters.
*/
void read_parameter_file(char *fname)
{
#define DOUBLE 1
#define STRING 2
#define INT 3
#define MAXTAGS 300
FILE *fd, *fdout;
char buf[200], buf1[200], buf2[200], buf3[400];
int i, j, nt;
int id[MAXTAGS];
void *addr[MAXTAGS];
char tag[MAXTAGS][50];
int errorFlag = 0;
if(sizeof(long long) != 8)
{
if(ThisTask == 0)
printf("\nType `long long' is not 64 bit on this platform. Stopping.\n\n");
endrun(0);
}
if(sizeof(int) != 4)
{
if(ThisTask == 0)
printf("\nType `int' is not 32 bit on this platform. Stopping.\n\n");
endrun(0);
}
if(sizeof(float) != 4)
{
if(ThisTask == 0)
printf("\nType `float' is not 32 bit on this platform. Stopping.\n\n");
endrun(0);
}
if(sizeof(double) != 8)
{
if(ThisTask == 0)
printf("\nType `double' is not 64 bit on this platform. Stopping.\n\n");
endrun(0);
}
if(ThisTask == 0) /* read parameter file on process 0 */
{
nt = 0;
strcpy(tag[nt], "InitCondFile");
addr[nt] = All.InitCondFile;
id[nt++] = STRING;
strcpy(tag[nt], "OutputDir");
addr[nt] = All.OutputDir;
id[nt++] = STRING;
strcpy(tag[nt], "SnapshotFileBase");
addr[nt] = All.SnapshotFileBase;
id[nt++] = STRING;
strcpy(tag[nt], "EnergyFile");
addr[nt] = All.EnergyFile;
id[nt++] = STRING;
#ifdef SYSTEMSTATISTICS
strcpy(tag[nt], "SystemFile");
addr[nt] = All.SystemFile;
id[nt++] = STRING;
#endif
strcpy(tag[nt], "CpuFile");
addr[nt] = All.CpuFile;
id[nt++] = STRING;
#ifdef SFR
strcpy(tag[nt], "SfrFile");
addr[nt] = All.SfrFile;
id[nt++] = STRING;
#endif
#ifdef CHIMIE
strcpy(tag[nt], "ChimieFile");
addr[nt] = All.ChimieFile;
id[nt++] = STRING;
#endif
#ifdef MULTIPHASE
strcpy(tag[nt], "PhaseFile");
addr[nt] = All.PhaseFile;
id[nt++] = STRING;
strcpy(tag[nt], "StickyFile");
addr[nt] = All.StickyFile;
id[nt++] = STRING;
#endif
#ifdef AGN_ACCRETION
strcpy(tag[nt], "AccretionFile");
addr[nt] = All.AccretionFile;
id[nt++] = STRING;
#endif
#ifdef BONDI_ACCRETION
strcpy(tag[nt], "BondiFile");
addr[nt] = All.BondiFile;
id[nt++] = STRING;
#endif
#ifdef BUBBLES
strcpy(tag[nt], "BubbleFile");
addr[nt] = All.BubbleFile;
id[nt++] = STRING;
#endif
strcpy(tag[nt], "InfoFile");
addr[nt] = All.InfoFile;
id[nt++] = STRING;
strcpy(tag[nt], "LogFile");
addr[nt] = All.LogFile;
id[nt++] = STRING;
strcpy(tag[nt], "TimingsFile");
addr[nt] = All.TimingsFile;
id[nt++] = STRING;
strcpy(tag[nt], "RestartFile");
addr[nt] = All.RestartFile;
id[nt++] = STRING;
strcpy(tag[nt], "ResubmitCommand");
addr[nt] = All.ResubmitCommand;
id[nt++] = STRING;
strcpy(tag[nt], "OutputListFilename");
addr[nt] = All.OutputListFilename;
id[nt++] = STRING;
strcpy(tag[nt], "OutputListOn");
addr[nt] = &All.OutputListOn;
id[nt++] = INT;
strcpy(tag[nt], "Omega0");
addr[nt] = &All.Omega0;
id[nt++] = DOUBLE;
strcpy(tag[nt], "OmegaBaryon");
addr[nt] = &All.OmegaBaryon;
id[nt++] = DOUBLE;
strcpy(tag[nt], "OmegaLambda");
addr[nt] = &All.OmegaLambda;
id[nt++] = DOUBLE;
strcpy(tag[nt], "HubbleParam");
addr[nt] = &All.HubbleParam;
id[nt++] = DOUBLE;
strcpy(tag[nt], "BoxSize");
addr[nt] = &All.BoxSize;
id[nt++] = DOUBLE;
strcpy(tag[nt], "PeriodicBoundariesOn");
addr[nt] = &All.PeriodicBoundariesOn;
id[nt++] = INT;
strcpy(tag[nt], "TimeOfFirstSnapshot");
addr[nt] = &All.TimeOfFirstSnapshot;
id[nt++] = DOUBLE;
strcpy(tag[nt], "CpuTimeBetRestartFile");
addr[nt] = &All.CpuTimeBetRestartFile;
id[nt++] = DOUBLE;
strcpy(tag[nt], "TimeBetStatistics");
addr[nt] = &All.TimeBetStatistics;
id[nt++] = DOUBLE;
strcpy(tag[nt], "TimeBegin");
addr[nt] = &All.TimeBegin;
id[nt++] = DOUBLE;
strcpy(tag[nt], "TimeMax");
addr[nt] = &All.TimeMax;
id[nt++] = DOUBLE;
strcpy(tag[nt], "TimeBetSnapshot");
addr[nt] = &All.TimeBetSnapshot;
id[nt++] = DOUBLE;
strcpy(tag[nt], "UnitVelocity_in_cm_per_s");
addr[nt] = &All.UnitVelocity_in_cm_per_s;
id[nt++] = DOUBLE;
strcpy(tag[nt], "UnitLength_in_cm");
addr[nt] = &All.UnitLength_in_cm;
id[nt++] = DOUBLE;
strcpy(tag[nt], "UnitMass_in_g");
addr[nt] = &All.UnitMass_in_g;
id[nt++] = DOUBLE;
strcpy(tag[nt], "TreeDomainUpdateFrequency");
addr[nt] = &All.TreeDomainUpdateFrequency;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ErrTolIntAccuracy");
addr[nt] = &All.ErrTolIntAccuracy;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ErrTolTheta");
addr[nt] = &All.ErrTolTheta;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ErrTolForceAcc");
addr[nt] = &All.ErrTolForceAcc;
id[nt++] = DOUBLE;
strcpy(tag[nt], "MinGasHsmlFractional");
addr[nt] = &All.MinGasHsmlFractional;
id[nt++] = DOUBLE;
strcpy(tag[nt], "MaxSizeTimestep");
addr[nt] = &All.MaxSizeTimestep;
id[nt++] = DOUBLE;
strcpy(tag[nt], "MinSizeTimestep");
addr[nt] = &All.MinSizeTimestep;
id[nt++] = DOUBLE;
strcpy(tag[nt], "MaxRMSDisplacementFac");
addr[nt] = &All.MaxRMSDisplacementFac;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ArtBulkViscConst");
addr[nt] = &All.ArtBulkViscConst;
id[nt++] = DOUBLE;
strcpy(tag[nt], "CourantFac");
addr[nt] = &All.CourantFac;
id[nt++] = DOUBLE;
strcpy(tag[nt], "DesNumNgb");
addr[nt] = &All.DesNumNgb;
id[nt++] = DOUBLE;
strcpy(tag[nt], "MaxNumNgbDeviation");
addr[nt] = &All.MaxNumNgbDeviation;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ComovingIntegrationOn");
addr[nt] = &All.ComovingIntegrationOn;
id[nt++] = INT;
strcpy(tag[nt], "ICFormat");
addr[nt] = &All.ICFormat;
id[nt++] = INT;
strcpy(tag[nt], "SnapFormat");
addr[nt] = &All.SnapFormat;
id[nt++] = INT;
strcpy(tag[nt], "NumFilesPerSnapshot");
addr[nt] = &All.NumFilesPerSnapshot;
id[nt++] = INT;
strcpy(tag[nt], "NumFilesWrittenInParallel");
addr[nt] = &All.NumFilesWrittenInParallel;
id[nt++] = INT;
strcpy(tag[nt], "ResubmitOn");
addr[nt] = &All.ResubmitOn;
id[nt++] = INT;
strcpy(tag[nt], "TypeOfTimestepCriterion");
addr[nt] = &All.TypeOfTimestepCriterion;
id[nt++] = INT;
strcpy(tag[nt], "TypeOfOpeningCriterion");
addr[nt] = &All.TypeOfOpeningCriterion;
id[nt++] = INT;
strcpy(tag[nt], "TimeLimitCPU");
addr[nt] = &All.TimeLimitCPU;
id[nt++] = DOUBLE;
strcpy(tag[nt], "SofteningHalo");
addr[nt] = &All.SofteningHalo;
id[nt++] = DOUBLE;
strcpy(tag[nt], "SofteningDisk");
addr[nt] = &All.SofteningDisk;
id[nt++] = DOUBLE;
strcpy(tag[nt], "SofteningBulge");
addr[nt] = &All.SofteningBulge;
id[nt++] = DOUBLE;
strcpy(tag[nt], "SofteningGas");
addr[nt] = &All.SofteningGas;
id[nt++] = DOUBLE;
strcpy(tag[nt], "SofteningStars");
addr[nt] = &All.SofteningStars;
id[nt++] = DOUBLE;
strcpy(tag[nt], "SofteningBndry");
addr[nt] = &All.SofteningBndry;
id[nt++] = DOUBLE;
strcpy(tag[nt], "SofteningHaloMaxPhys");
addr[nt] = &All.SofteningHaloMaxPhys;
id[nt++] = DOUBLE;
strcpy(tag[nt], "SofteningDiskMaxPhys");
addr[nt] = &All.SofteningDiskMaxPhys;
id[nt++] = DOUBLE;
strcpy(tag[nt], "SofteningBulgeMaxPhys");
addr[nt] = &All.SofteningBulgeMaxPhys;
id[nt++] = DOUBLE;
strcpy(tag[nt], "SofteningGasMaxPhys");
addr[nt] = &All.SofteningGasMaxPhys;
id[nt++] = DOUBLE;
strcpy(tag[nt], "SofteningStarsMaxPhys");
addr[nt] = &All.SofteningStarsMaxPhys;
id[nt++] = DOUBLE;
strcpy(tag[nt], "SofteningBndryMaxPhys");
addr[nt] = &All.SofteningBndryMaxPhys;
id[nt++] = DOUBLE;
strcpy(tag[nt], "BufferSize");
addr[nt] = &All.BufferSize;
id[nt++] = INT;
strcpy(tag[nt], "PartAllocFactor");
addr[nt] = &All.PartAllocFactor;
id[nt++] = DOUBLE;
strcpy(tag[nt], "TreeAllocFactor");
addr[nt] = &All.TreeAllocFactor;
id[nt++] = DOUBLE;
strcpy(tag[nt], "GravityConstantInternal");
addr[nt] = &All.GravityConstantInternal;
id[nt++] = DOUBLE;
strcpy(tag[nt], "InitGasTemp");
addr[nt] = &All.InitGasTemp;
id[nt++] = DOUBLE;
strcpy(tag[nt], "MinGasTemp");
addr[nt] = &All.MinGasTemp;
id[nt++] = DOUBLE;
#ifdef RANDOMSEED_AS_PARAMETER
strcpy(tag[nt], "RandomSeed");
addr[nt] = &All.RandomSeed;
id[nt++] = INT;
#endif
#ifdef COOLING
strcpy(tag[nt], "CoolingFile");
addr[nt] = All.CoolingFile;
id[nt++] = STRING;
strcpy(tag[nt], "CutofCoolingTemperature");
addr[nt] = &All.CutofCoolingTemperature;
id[nt++] = DOUBLE;
strcpy(tag[nt], "InitGasMetallicity");
addr[nt] = &All.InitGasMetallicity;
id[nt++] = DOUBLE;
strcpy(tag[nt], "CoolingType");
addr[nt] = &All.CoolingType;
id[nt++] = DOUBLE;
#endif
#ifdef CHIMIE
strcpy(tag[nt], "ChimieNumberOfParameterFiles");
addr[nt] = &All.ChimieNumberOfParameterFiles;
id[nt++] = INT;
strcpy(tag[nt], "ChimieParameterFile");
addr[nt] = All.ChimieParameterFile;
id[nt++] = STRING;
strcpy(tag[nt], "ChimieSupernovaEnergy");
addr[nt] = &All.ChimieSupernovaEnergy;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ChimieKineticFeedbackFraction");
addr[nt] = &All.ChimieKineticFeedbackFraction;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ChimieWindSpeed");
addr[nt] = &All.ChimieWindSpeed;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ChimieWindTime");
addr[nt] = &All.ChimieWindTime;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ChimieThermalTime");
addr[nt] = &All.ChimieThermalTime;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ChimieMaxSizeTimestep");
addr[nt] = &All.ChimieMaxSizeTimestep;
id[nt++] = DOUBLE;
#endif
#if defined (HEATING_PE)
strcpy(tag[nt], "HeatingPeElectronFraction");
addr[nt] = &All.HeatingPeElectronFraction;
id[nt++] = DOUBLE;
#endif
#if defined (HEATING_PE) || defined (STELLAR_FLUX) || defined (EXTERNAL_FLUX)
strcpy(tag[nt], "HeatingPeSolarEnergyDensity");
addr[nt] = &All.HeatingPeSolarEnergyDensity;
id[nt++] = DOUBLE;
#endif
#if defined (HEATING_PE) || defined (STELLAR_FLUX)
strcpy(tag[nt], "HeatingPeLMRatioGas");
addr[nt] = &All.HeatingPeLMRatioGas;
id[nt++] = DOUBLE;
strcpy(tag[nt], "HeatingPeLMRatioHalo");
addr[nt] = &All.HeatingPeLMRatioHalo;
id[nt++] = DOUBLE;
strcpy(tag[nt], "HeatingPeLMRatioDisk");
addr[nt] = &All.HeatingPeLMRatioDisk;
id[nt++] = DOUBLE;
strcpy(tag[nt], "HeatingPeLMRatioBulge");
addr[nt] = &All.HeatingPeLMRatioBulge;
id[nt++] = DOUBLE;
strcpy(tag[nt], "HeatingPeLMRatioStars");
addr[nt] = &All.HeatingPeLMRatioStars;
id[nt++] = DOUBLE;
strcpy(tag[nt], "HeatingPeLMRatioBndry");
addr[nt] = &All.HeatingPeLMRatioBndry;
id[nt++] = DOUBLE;
#endif
#ifdef EXTERNAL_FLUX
strcpy(tag[nt], "HeatingExternalFLuxEnergyDensity");
addr[nt] = &All.HeatingExternalFLuxEnergyDensity;
id[nt++] = DOUBLE;
#endif
#ifdef MULTIPHASE
strcpy(tag[nt], "CriticalTemperature");
addr[nt] = &All.CriticalTemperature;
id[nt++] = DOUBLE;
strcpy(tag[nt], "CriticalNonCollisionalTemperature");
addr[nt] = &All.CriticalNonCollisionalTemperature;
id[nt++] = DOUBLE;
strcpy(tag[nt], "StickyUseGridForCollisions");
addr[nt] = &All.StickyUseGridForCollisions;
id[nt++] = INT;
strcpy(tag[nt], "StickyTime");
addr[nt] = &All.StickyTime;
id[nt++] = DOUBLE;
strcpy(tag[nt], "StickyCollisionTime");
addr[nt] = &All.StickyCollisionTime;
id[nt++] = DOUBLE;
strcpy(tag[nt], "StickyIdleTime");
addr[nt] = &All.StickyIdleTime;
id[nt++] = DOUBLE;
strcpy(tag[nt], "StickyMinVelocity");
addr[nt] = &All.StickyMinVelocity;
id[nt++] = DOUBLE;
strcpy(tag[nt], "StickyMaxVelocity");
addr[nt] = &All.StickyMaxVelocity;
id[nt++] = DOUBLE;
strcpy(tag[nt], "StickyBetaR");
addr[nt] = &All.StickyBetaR;
id[nt++] = DOUBLE;
strcpy(tag[nt], "StickyBetaT");
addr[nt] = &All.StickyBetaT;
id[nt++] = DOUBLE;
strcpy(tag[nt], "StickyGridNx");
addr[nt] = &All.StickyGridNx;
id[nt++] = INT;
strcpy(tag[nt], "StickyGridNy");
addr[nt] = &All.StickyGridNy;
id[nt++] = INT;
strcpy(tag[nt], "StickyGridNz");
addr[nt] = &All.StickyGridNz;
id[nt++] = INT;
strcpy(tag[nt], "StickyGridXmin");
addr[nt] = &All.StickyGridXmin;
id[nt++] = DOUBLE;
strcpy(tag[nt], "StickyGridXmax");
addr[nt] = &All.StickyGridXmax;
id[nt++] = DOUBLE;
strcpy(tag[nt], "StickyGridYmin");
addr[nt] = &All.StickyGridYmin;
id[nt++] = DOUBLE;
strcpy(tag[nt], "StickyGridYmax");
addr[nt] = &All.StickyGridYmax;
id[nt++] = DOUBLE;
strcpy(tag[nt], "StickyGridZmin");
addr[nt] = &All.StickyGridZmin;
id[nt++] = DOUBLE;
strcpy(tag[nt], "StickyGridZmax");
addr[nt] = &All.StickyGridZmax;
id[nt++] = DOUBLE;
strcpy(tag[nt], "StickyDensity");
addr[nt] = &All.StickyDensity;
id[nt++] = DOUBLE;
strcpy(tag[nt], "StickyDensityPower");
addr[nt] = &All.StickyDensityPower;
id[nt++] = DOUBLE;
strcpy(tag[nt], "StickyRsphFact");
addr[nt] = &All.StickyRsphFact;
id[nt++] = DOUBLE;
#ifdef COLDGAS_CYCLE
strcpy(tag[nt], "ColdGasCycleTransitionTime");
addr[nt] = &All.ColdGasCycleTransitionTime;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ColdGasCycleTransitionParameter");
addr[nt] = &All.ColdGasCycleTransitionParameter;
id[nt++] = DOUBLE;
#endif
#endif
#ifdef OUTERPOTENTIAL
#ifdef NFW
strcpy(tag[nt], "HaloConcentration");
addr[nt] = &All.HaloConcentration;
id[nt++] = DOUBLE;
strcpy(tag[nt], "HaloMass");
addr[nt] = &All.HaloMass;
id[nt++] = DOUBLE;
strcpy(tag[nt], "GasMassFraction");
addr[nt] = &All.GasMassFraction;
id[nt++] = DOUBLE;
#endif
#ifdef PLUMMER
strcpy(tag[nt], "PlummerMass");
addr[nt] = &All.PlummerMass;
id[nt++] = DOUBLE;
strcpy(tag[nt], "PlummerSoftenning");
addr[nt] = &All.PlummerSoftenning;
id[nt++] = DOUBLE;
#endif
#ifdef MIYAMOTONAGAI
strcpy(tag[nt], "MiyamotoNagaiMass");
addr[nt] = &All.MiyamotoNagaiMass;
id[nt++] = DOUBLE;
strcpy(tag[nt], "MiyamotoNagaiHr");
addr[nt] = &All.MiyamotoNagaiHr;
id[nt++] = DOUBLE;
strcpy(tag[nt], "MiyamotoNagaiHz");
addr[nt] = &All.MiyamotoNagaiHz;
id[nt++] = DOUBLE;
#endif
#ifdef PISOTHERM
strcpy(tag[nt], "Rho0");
addr[nt] = &All.Rho0;
id[nt++] = DOUBLE;
strcpy(tag[nt], "Rc");
addr[nt] = &All.Rc;
id[nt++] = DOUBLE;
strcpy(tag[nt], "GasMassFraction");
addr[nt] = &All.GasMassFraction;
id[nt++] = DOUBLE;
#endif
#ifdef CORIOLIS
strcpy(tag[nt], "CoriolisOmegaX0");
addr[nt] = &All.CoriolisOmegaX0;
id[nt++] = DOUBLE;
strcpy(tag[nt], "CoriolisOmegaY0");
addr[nt] = &All.CoriolisOmegaY0;
id[nt++] = DOUBLE;
strcpy(tag[nt], "CoriolisOmegaZ0");
addr[nt] = &All.CoriolisOmegaZ0;
id[nt++] = DOUBLE;
#endif
#endif
#ifdef SFR
strcpy(tag[nt], "StarFormationNStarsFromGas");
addr[nt] = &All.StarFormationNStarsFromGas;
id[nt++] = INT;
strcpy(tag[nt], "StarFormationMgMsFraction");
addr[nt] = &All.StarFormationMgMsFraction;
id[nt++] = DOUBLE;
strcpy(tag[nt], "StarFormationStarMass");
addr[nt] = &All.StarFormationStarMass;
id[nt++] = DOUBLE;
strcpy(tag[nt], "StarFormationType");
addr[nt] = &All.StarFormationType;
id[nt++] = INT;
strcpy(tag[nt], "StarFormationCstar");
addr[nt] = &All.StarFormationCstar;
id[nt++] = DOUBLE;
strcpy(tag[nt], "StarFormationTime");
addr[nt] = &All.StarFormationTime;
id[nt++] = DOUBLE;
strcpy(tag[nt], "StarFormationDensity");
addr[nt] = &All.StarFormationDensity;
id[nt++] = DOUBLE;
strcpy(tag[nt], "StarFormationTemperature");
addr[nt] = &All.StarFormationTemperature;
id[nt++] = DOUBLE;
#endif
#ifdef FEEDBACK
strcpy(tag[nt], "SupernovaEgySpecPerMassUnit");
addr[nt] = &All.SupernovaEgySpecPerMassUnit;
id[nt++] = DOUBLE;
strcpy(tag[nt], "SupernovaFractionInEgyKin");
addr[nt] = &All.SupernovaFractionInEgyKin;
id[nt++] = DOUBLE;
strcpy(tag[nt], "SupernovaTime");
addr[nt] = &All.SupernovaTime;
id[nt++] = DOUBLE;
#endif
#ifdef FEEDBACK_WIND
strcpy(tag[nt], "SupernovaWindEgySpecPerMassUnit");
addr[nt] = &All.SupernovaWindEgySpecPerMassUnit;
id[nt++] = DOUBLE;
strcpy(tag[nt], "SupernovaWindFractionInEgyKin");
addr[nt] = &All.SupernovaWindFractionInEgyKin;
id[nt++] = DOUBLE;
strcpy(tag[nt], "SupernovaWindParameter");
addr[nt] = &All.SupernovaWindParameter;
id[nt++] = DOUBLE;
strcpy(tag[nt], "SupernovaWindIntAccuracy");
addr[nt] = &All.SupernovaWindIntAccuracy;
id[nt++] = DOUBLE;
#endif
#ifdef AGN_ACCRETION
strcpy(tag[nt], "TimeBetAccretion");
addr[nt] = &All.TimeBetAccretion;
id[nt++] = DOUBLE;
strcpy(tag[nt], "AccretionRadius");
addr[nt] = &All.AccretionRadius;
id[nt++] = DOUBLE;
strcpy(tag[nt], "AGNFactor");
addr[nt] = &All.AGNFactor;
id[nt++] = DOUBLE;
strcpy(tag[nt], "MinMTotInRa");
addr[nt] = &All.MinMTotInRa;
id[nt++] = DOUBLE;
#endif
#ifdef BUBBLES
strcpy(tag[nt], "BubblesDelta");
addr[nt] = &All.BubblesDelta;
id[nt++] = DOUBLE;
strcpy(tag[nt], "BubblesAlpha");
addr[nt] = &All.BubblesAlpha;
id[nt++] = DOUBLE;
strcpy(tag[nt], "BubblesRadiusFactor");
addr[nt] = &All.BubblesRadiusFactor;
id[nt++] = DOUBLE;
strcpy(tag[nt], "BubblesInitFile");
addr[nt] = All.BubblesInitFile;
id[nt++] = STRING;
#endif
#ifdef AGN_HEATING
strcpy(tag[nt], "AGNHeatingPower");
addr[nt] = &All.AGNHeatingPower;
id[nt++] = DOUBLE;
strcpy(tag[nt], "AGNHeatingRmax");
addr[nt] = &All.AGNHeatingRmax;
id[nt++] = DOUBLE;
#endif
#ifdef BONDI_ACCRETION
strcpy(tag[nt], "BondiEfficiency");
addr[nt] = &All.BondiEfficiency;
id[nt++] = DOUBLE;
strcpy(tag[nt], "BondiBlackHoleMass");
addr[nt] = &All.BondiBlackHoleMass;
id[nt++] = DOUBLE;
strcpy(tag[nt], "BondiHsmlFactor");
addr[nt] = &All.BondiHsmlFactor;
id[nt++] = DOUBLE;
strcpy(tag[nt], "BondiTimeBet");
addr[nt] = &All.BondiTimeBet;
id[nt++] = DOUBLE;
#endif
if((fd = fopen(fname, "r")))
{
sprintf(buf, "%s%s", fname, "-usedvalues");
if(!(fdout = fopen(buf, "w")))
{
printf("error opening file '%s' \n", buf);
errorFlag = 1;
}
else
{
while(!feof(fd))
{
*buf = 0;
fgets(buf, 200, fd);
if(sscanf(buf, "%s%s%s", buf1, buf2, buf3) < 2)
continue;
if(buf1[0] == '%')
continue;
for(i = 0, j = -1; i < nt; i++)
if(strcmp(buf1, tag[i]) == 0)
{
j = i;
tag[i][0] = 0;
break;
}
if(j >= 0)
{
switch (id[j])
{
case DOUBLE:
*((double *) addr[j]) = atof(buf2);
fprintf(fdout, "%-35s%g\n", buf1, *((double *) addr[j]));
break;
case STRING:
strcpy(addr[j], buf2);
fprintf(fdout, "%-35s%s\n", buf1, buf2);
break;
case INT:
*((int *) addr[j]) = atoi(buf2);
fprintf(fdout, "%-35s%d\n", buf1, *((int *) addr[j]));
break;
}
}
else
{
fprintf(stdout, "Error in file %s: Tag '%s' not allowed or multiple defined.\n",
fname, buf1);
errorFlag = 1;
}
}
fclose(fd);
fclose(fdout);
i = strlen(All.OutputDir);
if(i > 0)
if(All.OutputDir[i - 1] != '/')
strcat(All.OutputDir, "/");
/* copy parameters-usedvalues file*/
sprintf(buf1, "%s%s", fname, "-usedvalues");
sprintf(buf2, "%s%s", All.OutputDir, "parameters-usedvalues");
fd = fopen(buf1,"r");
fdout = fopen(buf2,"w");
while(1)
{
fgets(buf, 200, fd);
if (feof(fd)) break;
fprintf(fdout, buf, 200);
}
fclose(fd);
fclose(fdout);
}
}
else
{
printf("\nParameter file %s not found.\n\n", fname);
errorFlag = 2;
}
if(errorFlag != 2)
for(i = 0; i < nt; i++)
{
if(*tag[i])
{
printf("Error. I miss a value for tag '%s' in parameter file '%s'.\n", tag[i], fname);
errorFlag = 1;
}
}
if(All.OutputListOn && errorFlag == 0)
errorFlag += read_outputlist(All.OutputListFilename);
else
All.OutputListLength = 0;
}
MPI_Bcast(&errorFlag, 1, MPI_INT, 0, MPI_COMM_WORLD);
if(errorFlag)
{
MPI_Finalize();
exit(0);
}
/* now communicate the relevant parameters to the other processes */
MPI_Bcast(&All, sizeof(struct global_data_all_processes), MPI_BYTE, 0, MPI_COMM_WORLD);
if(All.NumFilesWrittenInParallel < 1)
{
if(ThisTask == 0)
printf("NumFilesWrittenInParallel MUST be at least 1\n");
endrun(0);
}
if(All.NumFilesWrittenInParallel > NTask)
{
if(ThisTask == 0)
printf("NumFilesWrittenInParallel MUST be smaller than number of processors\n");
endrun(0);
}
#ifdef PERIODIC
if(All.PeriodicBoundariesOn == 0)
{
if(ThisTask == 0)
{
printf("Code was compiled with periodic boundary conditions switched on.\n");
printf("You must set `PeriodicBoundariesOn=1', or recompile the code.\n");
}
endrun(0);
}
#else
if(All.PeriodicBoundariesOn == 1)
{
if(ThisTask == 0)
{
printf("Code was compiled with periodic boundary conditions switched off.\n");
printf("You must set `PeriodicBoundariesOn=0', or recompile the code.\n");
}
endrun(0);
}
#endif
if(All.TypeOfTimestepCriterion >= 1)
{
if(ThisTask == 0)
{
printf("The specified timestep criterion\n");
printf("is not valid\n");
}
endrun(0);
}
#if defined(LONG_X) || defined(LONG_Y) || defined(LONG_Z)
#ifndef NOGRAVITY
if(ThisTask == 0)
{
printf("Code was compiled with LONG_X/Y/Z, but not with NOGRAVITY.\n");
printf("Stretched periodic boxes are not implemented for gravity yet.\n");
}
endrun(0);
#endif
#endif
#undef DOUBLE
#undef STRING
#undef INT
#undef MAXTAGS
}
/*! this function reads a table with a list of desired output times. The
* table does not have to be ordered in any way, but may not contain more
* than MAXLEN_OUTPUTLIST entries.
*/
int read_outputlist(char *fname)
{
FILE *fd;
if(!(fd = fopen(fname, "r")))
{
printf("can't read output list in file '%s'\n", fname);
return 1;
}
All.OutputListLength = 0;
do
{
if(fscanf(fd, " %lg ", &All.OutputListTimes[All.OutputListLength]) == 1)
All.OutputListLength++;
else
break;
}
while(All.OutputListLength < MAXLEN_OUTPUTLIST);
fclose(fd);
printf("\nfound %d times in output-list.\n", All.OutputListLength);
return 0;
}
/*! If a restart from restart-files is carried out where the TimeMax
* variable is increased, then the integer timeline needs to be
* adjusted. The approach taken here is to reduce the resolution of the
* integer timeline by factors of 2 until the new final time can be
* reached within TIMEBASE.
*/
void readjust_timebase(double TimeMax_old, double TimeMax_new)
{
int i;
long long ti_end;
if(ThisTask == 0)
{
printf("\nAll.TimeMax has been changed in the parameterfile\n");
printf("Need to adjust integer timeline\n\n\n");
}
if(TimeMax_new < TimeMax_old)
{
if(ThisTask == 0)
printf("\nIt is not allowed to reduce All.TimeMax\n\n");
endrun(556);
}
if(All.ComovingIntegrationOn)
ti_end = log(TimeMax_new / All.TimeBegin) / All.Timebase_interval;
else
ti_end = (TimeMax_new - All.TimeBegin) / All.Timebase_interval;
while(ti_end > TIMEBASE)
{
All.Timebase_interval *= 2.0;
ti_end /= 2;
All.Ti_Current /= 2;
#ifdef PMGRID
All.PM_Ti_begstep /= 2;
All.PM_Ti_endstep /= 2;
#endif
for(i = 0; i < NumPart; i++)
{
P[i].Ti_begstep /= 2;
P[i].Ti_endstep /= 2;
}
}
All.TimeMax = TimeMax_new;
}
diff --git a/chimie.c b/chimie.c
index c45f5d3..9d82908 100644
--- a/chimie.c
+++ b/chimie.c
@@ -1,2672 +1,2672 @@
#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 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];
FILE *fd;
int i,j;
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 */
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);
}
/* 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));
/* 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(Elts[it][i].label,&Elts[it][i].label[2]);
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(label,&label[2]);
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(label,&label[2]);
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);
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);
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");
/* 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
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
}
/* `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);
+ 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);
+ 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);
+ 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;
+ 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);
+ 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;
+ 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,m2)*M0;
+ NSNIa = SNIa_rate(m1/All.HubbleParam,m2/All.HubbleParam)*M0/All.HubbleParam;
/* number of SNII */
- NSNII = SNII_rate(m1,m2)*M0;
+ NSNII = SNII_rate(m1/All.HubbleParam,m2/All.HubbleParam)*M0/All.HubbleParam;
NSNIa_totlocal += NSNIa;
NSNII_totlocal += NSNII;
/* compute ejectas */
- Total_mass_ejection(m1,m2,M0,metals);
+ Total_mass_ejection(m1/All.HubbleParam,m2/All.HubbleParam,M0/All.HubbleParam,metals);
- StP[m].TotalEjectedGasMass = EjectedMass[0]; /* gas mass */
+ StP[m].TotalEjectedGasMass = EjectedMass[0]*All.HubbleParam; /* gas mass */
for (k=0;k<NELEMENTS;k++)
- StP[m].TotalEjectedEltMass[k] = EjectedMass[k+2]; /* metal mass */
+ 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/cooling.c b/cooling.c
index 6b13b4a..0613198 100644
--- a/cooling.c
+++ b/cooling.c
@@ -1,2054 +1,2056 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <mpi.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_roots.h>
#include "allvars.h"
#include "proto.h"
#ifdef COOLING
/*! initialize cooling function (the metallicity is fixed)
*
* T = temperature
* L0 = m000 primordial metallicity
* L1 = m-30
* L2 = m-20
* L3 = m-10
* L4 = m-05
* L5 = m-00 solar metallicity
* L6 = m+05
*/
int init_cooling(FLOAT metallicity)
{
FILE *fd;
int n,i;
char line[72];
float T,L0,L1,L2,L3,L4,L5,L6;
int MetallicityIndex=4;
/* find the right index */
if (All.InitGasMetallicity<-3)
MetallicityIndex = 0;
else
{
if (All.InitGasMetallicity<-2)
MetallicityIndex = 1;
else
{
if (All.InitGasMetallicity<-1)
MetallicityIndex = 2;
else
{
if (All.InitGasMetallicity<-0.5)
MetallicityIndex = 3;
else
{
if (All.InitGasMetallicity<0)
MetallicityIndex = 4;
else
{
MetallicityIndex = 5;
}
}
}
}
}
fd = fopen(All.CoolingFile,"r");
fscanf(fd, "# %6d\n", &n);
/* allocate memory */
All.logT = malloc(n * sizeof(double));
All.logL = malloc(n * sizeof(double));
/* read empty line */
fgets(line, sizeof(line), fd);
/* read file */
for (i=0;i<n;i++){
fscanf(fd, "%f %f %f %f %f %f %f %f\n",&T,&L0,&L1,&L2,&L3,&L4,&L5,&L6);
//printf("%8.3f %8.3f\n",T,L0);
/* keep only solar values */
All.logT[i] = (double)T;
switch (MetallicityIndex)
{
case 0:
All.logL[i] = (double)L0;
break;
case 1:
All.logL[i] = (double)L1;
break;
case 2:
All.logL[i] = (double)L2;
break;
case 3:
All.logL[i] = (double)L3;
break;
case 4:
All.logL[i] = (double)L4;
break;
case 5:
All.logL[i] = (double)L5;
break;
case 6:
All.logL[i] = (double)L6;
break;
}
}
fclose(fd);
/* init interpolation */
All.acc_cooling_spline = gsl_interp_accel_alloc ();
All.cooling_spline = gsl_spline_alloc (gsl_interp_cspline, n);
gsl_spline_init (All.cooling_spline, All.logT, All.logL, n);
#ifdef OUTPUT_COOLING_FUNCTION
/* test cooling */
double logT;
double l;
logT = 1.;
while(logT<8)
{
T = pow(10,logT);
l = log10(cooling_function(T));
if(ThisTask == 0)
printf("%8.3f %8.3f\n",logT,l);
logT = logT + 0.05;
}
#endif
return 0;
}
/*! This function return the normalized cooling function (no metallicity dependency)
*/
double cooling_function(double temperature)
{
double logT;
if (temperature >= All.CutofCoolingTemperature)
{
logT = log10(temperature);
if (logT>8.5)
logT = 8.5;
return pow(10,gsl_spline_eval (All.cooling_spline, logT, All.acc_cooling_spline));
}
else
return 1e-100;
}
/***************************************************************************
METALLICITY DEPENDENT COOLING
**************************************************************************/
int init_cooling_with_metals()
{
/*
zmin zmax slz
tmin tmax slt
FeHSolar
p k
*/
FILE *fd;
int p,k,i,j;
float zmin,zmax,slz,tmin,tmax,slt,FeHSolar;
float lbd;
fd = fopen(All.CoolingFile,"r");
fscanf(fd, "%f %f %f\n", &zmin,&zmax,&slz);
fscanf(fd, "%f %f %f\n", &tmin,&tmax,&slt);
fscanf(fd, "%f\n" , &FeHSolar);
fscanf(fd, "%d %d\n" , &p,&k);
All.CoolingParameters_zmin = zmin;
All.CoolingParameters_zmax = zmax;
All.CoolingParameters_slz = slz;
All.CoolingParameters_tmin = tmin;
All.CoolingParameters_tmax = tmax;
All.CoolingParameters_slt = slt;
//All.CoolingParameters_FeHSolar = FEH_SOLAR; /* instead of FeHSolar*/
All.CoolingParameters_cooling_data_max = k-2;
for (i=0;i<p;i++)
for (j=0;j<k;j++)
{
fscanf(fd, "%f\n" ,&lbd);
All.CoolingParameters_cooling_data[i][j]=lbd;
}
fclose(fd);
#ifdef OUTPUT_COOLING_FUNCTION
/* test cooling */
double logT,T;
double l;
double metal;
logT = 1.;
metal = (pow(10,All.InitGasMetallicity)-1e-10)*All.CoolingParameters_FeHSolar;
while(logT<8)
{
T = pow(10,logT);
l = log10(cooling_function_with_metals(T,metal));
if(ThisTask == 0)
printf("%8.3f %8.3f\n",logT,l);
logT = logT + 0.05;
}
#endif
return 0;
}
/*! This function return the normalized cooling function, that depends on metallicity
*/
double cooling_function_with_metals(double temperature,double metal)
{
double cooling;
double T,Z;
double rt, rz, ft, fz, v1, v2, v;
int it,iz,itp,izp;
double zmin,zmax,slz,tmin,tmax,slt,FeHSolar,cooling_data_max;
zmin = All.CoolingParameters_zmin;
zmax = All.CoolingParameters_zmax;
slz = All.CoolingParameters_slz;
tmin = All.CoolingParameters_tmin;
tmax = All.CoolingParameters_tmax;
slt = All.CoolingParameters_slt;
FeHSolar = All.CoolingParameters_FeHSolar;
cooling_data_max = All.CoolingParameters_cooling_data_max;
cooling = 0.0;
T = log10( temperature );
Z = log10( metal/FeHSolar + 1.e-10 );
if (Z>zmax)
{
/*print *,'Warning: Z>Zmax for',i*/
Z=zmax;
}
if (Z < zmin)
{
rt = (T-tmin)/slt;
it = (int)rt;
if (it < cooling_data_max )
it = (int)rt;
else
it = cooling_data_max;
itp = it+1;
ft = rt - it;
fz = ( 10. + Z )/( 10. + zmin);
v1 = ft*( All.CoolingParameters_cooling_data[1][itp] -All.CoolingParameters_cooling_data[1][it] ) + All.CoolingParameters_cooling_data[1][it];
v2 = ft*( All.CoolingParameters_cooling_data[0][itp] -All.CoolingParameters_cooling_data[0][it] ) + All.CoolingParameters_cooling_data[0][it];
v = v2 + fz*(v1-v2);
}
else
{
rt = (T-tmin)/slt;
rz = (Z-zmin)/slz+1.0;
it = (int)rt;
if (it < cooling_data_max )
it = (int)rt;
else
it = cooling_data_max;
iz = (int)rz;
itp = it+1;
izp = iz+1;
ft = rt - it;
fz = rz - iz;
v1 = ft*(All.CoolingParameters_cooling_data[izp][itp] - All.CoolingParameters_cooling_data[izp][it]) + All.CoolingParameters_cooling_data[izp][it];
v2 = ft*(All.CoolingParameters_cooling_data[iz][itp] - All.CoolingParameters_cooling_data[iz][it]) + All.CoolingParameters_cooling_data[iz][it];
v = v2 + fz*(v1-v2);
}
cooling = pow(10,v);
return cooling;
}
/***************************************************************************
END OF METALLICITY DEPENDENT COOLING
**************************************************************************/
/*! \file cooling.c
* \brief Compute gas cooling
*
*/
static double hubble_a, a3inv;
static double eV = 1.6022000e-12;
static double normfacJ0 = 0.74627;
static double J0min = 1.e-29;
static double alpha = 1.0;
static int Norderweinberg = 7; /* polynom order+1 */
static double coefweinberg[7][6];
static double z;
static double J0;
static double Cte_G_gHI;
static double Cte_G_gHeI;
static double Cte_G_gHeII;
static double Cte_heating_radiative_HI;
static double Cte_heating_radiative_HeI;
static double Cte_heating_radiative_HeII;
/*
* init some variables that depends only on redshift
*/
void init_from_new_redshift(double Redshift)
{
/* init weinberg coeff */
coefweinberg[0][0] = -0.31086729929951613e+002;
coefweinberg[1][0] = 0.34803667059463761e+001;
coefweinberg[2][0] = -0.15145716066316397e+001;
coefweinberg[3][0] = 0.54649951450632972e+000;
coefweinberg[4][0] = -0.16395924120387340e+000;
coefweinberg[5][0] = 0.25197466148524143e-001;
coefweinberg[6][0] = -0.15352763785487806e-002;
coefweinberg[0][1] = -0.31887274113252204e+002;
coefweinberg[1][1] = 0.44178493140927095e+001;
coefweinberg[2][1] = -0.20158132553082293e+001;
coefweinberg[3][1] = 0.64080497292269134e+000;
coefweinberg[4][1] = -0.15981267091909040e+000;
coefweinberg[5][1] = 0.22056900050237707e-001;
coefweinberg[6][1] = -0.12837570029562849e-002;
coefweinberg[0][2] = -0.35693331167978656e+002;
coefweinberg[1][2] = 0.20207245722165794e+001;
coefweinberg[2][2] = -0.76856976101363744e-001;
coefweinberg[3][2] = -0.75691470654320359e-001;
coefweinberg[4][2] = -0.54502220282734729e-001;
coefweinberg[5][2] = 0.20633345104660583e-001;
coefweinberg[6][2] = -0.18410307456285177e-002;
coefweinberg[0][3] = -0.56967559787460921e+002;
coefweinberg[1][3] = 0.38601174525546353e+001;
coefweinberg[2][3] = -0.18318926655684415e+001;
coefweinberg[3][3] = 0.67360594266440688e+000;
coefweinberg[4][3] = -0.18983466813215341e+000;
coefweinberg[5][3] = 0.27768907786915147e-001;
coefweinberg[6][3] = -0.16330066969315893e-002;
coefweinberg[0][4] = -0.56977907250821026e+002;
coefweinberg[1][4] = 0.38686249565302266e+001;
coefweinberg[2][4] = -0.13330942368518774e+001;
coefweinberg[3][4] = 0.33988839029092172e+000;
coefweinberg[4][4] = -0.98997915675929332e-001;
coefweinberg[5][4] = 0.16781612113050747e-001;
coefweinberg[6][4] = -0.11514328893746039e-002;
coefweinberg[0][5] = -0.59825233828609278e+002;
coefweinberg[1][5] = 0.21898162706563347e+001;
coefweinberg[2][5] = -0.42982055888598525e+000;
coefweinberg[3][5] = 0.50312144291614215e-001;
coefweinberg[4][5] = -0.61550639239553132e-001;
coefweinberg[5][5] = 0.18017109270959387e-001;
coefweinberg[6][5] = -0.15438891584271634e-002;
z = Redshift;
J0 = J_0();
/* here, we initialize the ctes that uses J_nu(z) */
/* Tessier */
/*
Cte_G_gHI = G_gHI();
Cte_G_gHeI = G_gHeI();
Cte_G_gHeII = G_gHeII();
Cte_heating_radiative_HI = heating_radiative_HI();
Cte_heating_radiative_HeI = heating_radiative_HeI();
Cte_heating_radiative_HeII = heating_radiative_HeII();
*/
/* Theuns */
/*
Cte_G_gHI = G_gHI_t(J0);
Cte_G_gHeI = G_gHeI_t(J0);
Cte_G_gHeII = G_gHeII_t(J0);
Cte_heating_radiative_HI = heating_radiative_HI_t(J0);
Cte_heating_radiative_HeI = heating_radiative_HeI_t(J0);
Cte_heating_radiative_HeII = heating_radiative_HeII_t(J0);
*/
/* Weinberg */
Cte_G_gHI = G_gHI_w();
Cte_G_gHeI = G_gHeI_w();
Cte_G_gHeII = G_gHeII_w();
Cte_heating_radiative_HI = heating_radiative_HI_w();
Cte_heating_radiative_HeI = heating_radiative_HeI_w();
Cte_heating_radiative_HeII = heating_radiative_HeII_w();
}
/*
* J0
*/
double J_0()
{
double Fz;
if (z > 6)
Fz = 0;
else
{
if (z > 3)
Fz = 4/(z+1);
else
{
if (z > 2)
Fz = 1;
else
Fz = pow(((1+z)/3.),3);
}
}
return 1.0e-22*Fz;
}
/*
* UV background intensity
*/
double J_nu(double e)
{
double e_L;
e_L = 13.598*eV;
return (e_L/e)*J_0();
}
/*
* sigma_rad
*/
double sigma_rad_HI(double e)
{
double xxx,alph,e_i;
e_i = 13.598 *eV;
xxx = e/e_i;
alph = sqrt(xxx-1.0);
return 6.30e-18/pow(xxx,4)*exp(4.0-4.0*atan(alph)/alph) /(1.0-exp(-TWOPI/alph));
}
double sigma_rad_HeI(double e)
{
double xxx,alph,e_i;
e_i = 24.587 *eV;
xxx = e/e_i;
alph = sqrt(xxx-1.0);
return 7.42e-18*(1.660/pow(xxx,2.050)-0.660/pow(xxx,3.050));
}
double sigma_rad_HeII(double e)
{
double xxx,alph,e_i;
e_i = 54.416 *eV;
xxx = e/e_i;
alph = sqrt(xxx-1.0);
return 1.58e-18/pow(xxx,4)*exp(4.0-4.0*atan(alph)/alph)/(1.0-exp(-TWOPI/alph));
}
/*
* cooling rates
*/
/* Bremstrahlung */
double cooling_bremstrahlung_HI(double T)
{
return 1.42e-27*sqrt(T)*(1.10+0.340*exp(-pow((5.50-log10(T)),2) /3.0));
}
double cooling_bremstrahlung_HeI(double T)
{
return 1.42e-27*sqrt(T)*(1.10+0.340*exp(-pow((5.50-log10(T)),2) /3.0));
}
double cooling_bremstrahlung_HeII(double T)
{
return 5.68e-27*sqrt(T)*(1.10+0.340*exp(-pow((5.50-log10(T)),2) /3.0));
}
/* Ionization */
double cooling_ionization_HI(double T)
{
double T5;
T5 = T/1e5;
return 2.54e-21*sqrt(T)*exp(-157809.1/T)/(1+sqrt(T5));
}
double cooling_ionization_HeI(double T)
{
double T5;
T5 = T/1e5;
return 1.88e-21*sqrt(T)*exp(-285335.4/T)/(1+sqrt(T5));
}
double cooling_ionization_HeII(double T)
{
double T5;
T5 = T/1e5;
return 9.90e-22*sqrt(T)*exp(-631515.0/T)/(1+sqrt(T5));
}
/* Recombination */
double cooling_recombination_HI(double T)
{
double T3,T6;
T3 = T/1e3;
T6 = T/1e6;
return 8.70e-27*sqrt(T)/pow(T3,0.2)/(1.0+pow(T6,0.7));
}
double cooling_recombination_HeI(double T)
{
return 1.55e-26*pow(T,0.3647);
}
double cooling_recombination_HeII(double T)
{
double T3,T6;
T3 = T/1e3;
T6 = T/1e6;
return 3.48e-26*sqrt(T)/pow(T3,0.2)/(1.0+pow(T6,0.7));
}
/* Dielectric Recombination */
double cooling_dielectric_recombination(double T)
{
return 1.24e-13*pow(T,-1.5)*exp(-470000.0/T)*(1.0+0.3*exp(-94000.0/T));
}
/* Ecitation cooling (line cooling) */
double cooling_excitation_HI(double T)
{
double T5;
T5 = T/1e5;
return 7.50e-19*exp(-118348.0/T)/(1+sqrt(T5));
}
double cooling_excitation_HII(double T)
{
double T5;
T5 = T/1e5;
return 5.54e-17/pow(T,0.397)*exp(-473638.0/T)/(1+sqrt(T5));
}
/* Compton cooling */
double cooling_compton(double T)
{
return 5.406e-36*(T-2.7*(1+z))*pow((1+z),4);
}
/*
* recombination rates (taux_rec)
*/
double A_HII(double T)
{
double T3,T6;
T3 = T/1e3;
T6 = T/1e6;
return 6.30e-11/sqrt(T)/pow(T3,0.2)/(1+pow(T6,0.7));
}
double A_HeIId(double T)
{
return 1.9e-3/pow(T,1.50)*exp(-470000.0/T)*(1.0+0.30*exp(-94000.0/T));
}
double A_HeII(double T)
{
return 1.5e-10/pow(T,0.6353) + A_HeIId(T);
}
double A_HeIII(double T)
{
double T3,T6;
T3 = T/1e3;
T6 = T/1e6;
return 3.36e-10/sqrt(T)/pow(T3,0.2)/(1.0+pow(T6,0.7));
}
/*
* collisional rates (taux_ion)
*/
double G_HI(double T)
{
double T5;
T5 = T/1e5;
return 1.17e-10*sqrt(T)*exp(-157809.1/T)/(1.0+sqrt(T5));
}
double G_HeI(double T)
{
double T5;
T5 = T/1e5;
return 2.38e-11*sqrt(T)*exp(-285335.4/T)/(1.0+sqrt(T5));
}
double G_HeII(double T)
{
double T5;
T5 = T/1e5;
return 5.68e-12*sqrt(T)*exp(-631515.0/T)/(1.0+sqrt(T5));
}
/*
* photoionisation rates (depend only on z)
*/
double G_gHI()
{
double e_i,integ,e,de,error;
e_i = 13.598*eV;
integ = 0.0;
e = e_i;
de = e/100.0;
error = 1.0;
while (error>1.e-6)
{
e = e + de;
de = e/100.0;
error = 2*TWOPI*J_nu(e)*sigma_rad_HI(e)*de/e;
integ = integ + error;
error = error/fabs(integ);
}
return integ/PLANCK;
}
double G_gHeI()
{
double e_i,integ,e,de,error;
e_i = 24.587*eV;
integ = 0.0;
e = e_i;
de = e/100.0;
error = 1.0;
while (error>1.e-6)
{
e = e + de;
de = e/100.0;
error = 2*TWOPI*J_nu(e)*sigma_rad_HeI(e)*de/e;
integ = integ + error;
error = error/fabs(integ);
}
return integ/PLANCK;
}
double G_gHeII()
{
double e_i,integ,e,de,error;
e_i = 54.416*eV;
integ = 0.0;
e = e_i;
de = e/100.0;
error = 1.0;
while (error>1.e-6)
{
e = e + de;
de = e/100.0;
error = 2*TWOPI*J_nu(e)*sigma_rad_HeII(e)*de/e;
integ = integ + error;
error = error/fabs(integ);
}
return integ/PLANCK;
}
double G_gHI_t(double J0)
{
return 1.26e10*J0/(3.0+alpha);
}
double G_gHeI_t(double J0)
{
return 1.48e10*J0*pow(0.5530,alpha) *(1.660/(alpha+2.050)-0.660/(alpha+3.050));
}
double G_gHeII_t(double J0)
{
return 3.34e9*J0*pow(0.2490,alpha)/(3.0+alpha);
}
double G_gHI_w()
{
double taux_rad_weinbergint;
double hh,tt,zz;
int i;
if (z < 8.50)
{
hh=0.0;
zz=dmax(z,1.0e-15);
for (i=0;i<Norderweinberg;i++)
hh=hh+coefweinberg[i][0]*pow(zz,i);
taux_rad_weinbergint=normfacJ0*exp(hh);
}
else
taux_rad_weinbergint=0.0;
tt=G_gHI_t(J0min);
if (taux_rad_weinbergint < tt)
taux_rad_weinbergint=tt;
return taux_rad_weinbergint;
}
double G_gHeI_w()
{
double taux_rad_weinbergint;
double hh,tt,zz;
int i;
if (z < 8.50)
{
hh=0.0;
zz=dmax(z,1.0e-15);
for (i=0;i<Norderweinberg;i++)
hh=hh+coefweinberg[i][1]*pow(zz,i);
taux_rad_weinbergint=normfacJ0*exp(hh);
}
else
taux_rad_weinbergint=0.0;
tt=G_gHeI_t(J0min);
if (taux_rad_weinbergint < tt)
taux_rad_weinbergint=tt;
return taux_rad_weinbergint;
}
double G_gHeII_w()
{
double taux_rad_weinbergint;
double hh,tt,zz;
int i;
if (z < 8.50)
{
hh=0.0;
zz=dmax(z,1.0e-15);
for (i=0;i<Norderweinberg;i++)
hh=hh+coefweinberg[i][2]*pow(zz,i);
taux_rad_weinbergint=normfacJ0*exp(hh);
}
else
taux_rad_weinbergint=0.0;
tt=G_gHeII_t(J0min);
if (taux_rad_weinbergint < tt)
taux_rad_weinbergint=tt;
return taux_rad_weinbergint;
}
/*
* heating rates (depend only on z)
*/
double heating_radiative_HI() /* use J_nu */
{
double e_i,integ,e,de,error;
e_i = 13.598*eV;
integ = 0.0;
e = e_i;
de = e/100.0;
error = 1.0;
while(error>1.e-6)
{
e = e + de;
de = e/100.0;
error = 2.0*TWOPI*J_nu(e)*sigma_rad_HI(e)*(e/e_i-1.0)*de/e;
integ = integ + error;
error=error/fabs(integ);
}
return integ/PLANCK*e_i;
}
double heating_radiative_HeI() /* use J_nu */
{
double e_i,integ,e,de,error;
e_i = 24.587*eV;
integ = 0.0;
e = e_i;
de = e/100.0;
error = 1.0;
while(error>1.e-6)
{
e = e + de;
de = e/100.0;
error = 2.0*TWOPI*J_nu(e)*sigma_rad_HeI(e)*(e/e_i-1.0)*de/e;
integ = integ + error;
error=error/fabs(integ);
}
return integ/PLANCK*e_i;
}
double heating_radiative_HeII() /* use J_nu */
{
double e_i,integ,e,de,error;
e_i = 54.416*eV;
integ = 0.0;
e = e_i;
de = e/100.0;
error = 1.0;
while(error>1.e-6)
{
e = e + de;
de = e/100.0;
error = 2.0*TWOPI*J_nu(e)*sigma_rad_HeII(e)*(e/e_i-1.0)*de/e;
integ = integ + error;
error=error/fabs(integ);
}
return integ/PLANCK*e_i;
}
double heating_radiative_HI_t(double J0) /* use Theuns */
{
return (2.91e-1*J0/(2.0+alpha))/(3.0+alpha);
}
double heating_radiative_HeI_t(double J0) /* use Theuns */
{
return 5.84e-1*J0*pow(0.5530,alpha)*(1.660/(alpha+1.050)-2.320/(alpha+2.050)+0.660/(alpha+3.050));
}
double heating_radiative_HeII_t(double J0) /* use Theuns */
{
return (2.92e-1*J0*pow(0.2490,alpha)/(2.0+alpha))/(3.0+alpha);
}
double heating_radiative_HI_w() /* use weinberg coeff */
{
double heat_rad_weinbergint;
double hh,tt,zz;
int i;
if (z < 8.50)
{
hh=0.0;
zz=dmax(z,1.0e-15);
for (i=0;i<Norderweinberg;i++)
hh=hh+coefweinberg[i][3]*pow(zz,i);
heat_rad_weinbergint=normfacJ0*exp(hh);
}
else
heat_rad_weinbergint=0.0;
tt=heating_radiative_HI_t(J0min);
if (heat_rad_weinbergint < tt)
heat_rad_weinbergint=tt;
return heat_rad_weinbergint;
}
double heating_radiative_HeI_w() /* use weinberg coeff */
{
double heat_rad_weinbergint;
double hh,tt,zz;
int i;
if (z < 8.50)
{
hh=0.0;
zz=dmax(z,1.0e-15);
for (i=0;i<Norderweinberg;i++)
hh=hh+coefweinberg[i][4]*pow(zz,i);
heat_rad_weinbergint=normfacJ0*exp(hh);
}
else
heat_rad_weinbergint=0.0;
tt=heating_radiative_HeI_t(J0min);
if (heat_rad_weinbergint < tt)
heat_rad_weinbergint=tt;
return heat_rad_weinbergint;
}
double heating_radiative_HeII_w() /* use weinberg coeff */
{
double heat_rad_weinbergint;
double hh,tt,zz;
int i;
if (z < 8.50)
{
hh=0.0;
zz=dmax(z,1.0e-15);
for (i=0;i<Norderweinberg;i++)
hh=hh+coefweinberg[i][5]*pow(zz,i);
heat_rad_weinbergint=normfacJ0*exp(hh);
}
else
heat_rad_weinbergint=0.0;
tt=heating_radiative_HeII_t(J0min);
if (heat_rad_weinbergint < tt)
heat_rad_weinbergint=tt;
return heat_rad_weinbergint;
}
double heating_compton()
{
/* Abel, Tom; Haehnelt, Martin G.Apj 520 */
//return 5.406e-36*2.726*pow((1+z),5); /* from Ramses */
//if (z>6)
// return 0;
//else
// return 1.25e-31*pow((1+z),13/3.);
return 0;
}
void compute_densities(double T,double X,double *pn_H, double *pn_HI,double *pn_HII,double *pn_HEI,double *pn_HEII,double *pn_HEIII,double *pn_E,double *pmu)
{
double Y,yy,x1;
double t_rad_HI,t_rec_HI,t_ion_HI;
double t_rad_HEI,t_rec_HEI,t_ion_HEI;
double t_rad_HEII,t_rec_HEII,t_ion_HEII;
double t_ion2_HI,t_ion2_HEI,t_ion2_HEII;
double err_nE;
double n_T;
double n_H,n_HI,n_HII,n_HEI,n_HEII,n_HEIII,n_E,mu;
Y = 1-X;
yy = Y/(4-4*Y);
t_rad_HI = Cte_G_gHI;
t_rec_HI = A_HII(T);
t_ion_HI = G_HI(T);
t_rad_HEI = Cte_G_gHeI;
t_rec_HEI = A_HeII(T);
t_ion_HEI = G_HeI(T);
t_rad_HEII = Cte_G_gHeII;
t_rec_HEII = A_HeIII(T);
t_ion_HEII = G_HeII(T);
n_H = *pn_H;
n_E = n_H;
err_nE = 1.;
while(err_nE > 1.e-8)
{
/* compute densities (Ramses implementation) */
t_ion2_HI = t_ion_HI + t_rad_HI /dmax(n_E,1e-15*n_H);
t_ion2_HEI = t_ion_HEI + t_rad_HEI /dmax(n_E,1e-15*n_H);
t_ion2_HEII = t_ion_HEII + t_rad_HEII/dmax(n_E,1e-15*n_H);
n_HI = t_rec_HI/(t_ion2_HI+t_rec_HI)*n_H;
n_HII = t_ion2_HI/(t_ion2_HI+t_rec_HI)*n_H;
x1 = (t_rec_HEII*t_rec_HEI+t_ion2_HEI*t_rec_HEII+t_ion2_HEII*t_ion2_HEI);
n_HEIII = yy*t_ion2_HEII*t_ion2_HEI/x1*n_H;
n_HEII = yy*t_ion2_HEI *t_rec_HEII/x1*n_H;
n_HEI = yy*t_rec_HEII *t_rec_HEI /x1*n_H;
err_nE = fabs((n_E - (n_HII + n_HEII + 2.*n_HEIII))/n_H);
n_E = 0.5*n_E+0.5*(n_HII + n_HEII + 2.*n_HEIII);
}
n_T = n_HI + n_HII+ n_HEI+ n_HEII+ n_HEIII+ n_E;
mu = n_H/X/n_T;
*pn_H = n_H;
*pn_HI = n_HI;
*pn_HII = n_HII;
*pn_HEI = n_HEI;
*pn_HEII = n_HEII;
*pn_HEIII = n_HEIII;
*pn_E = n_E;
*pmu = mu;
}
void print_cooling(double T,
double c1,double c2,double c3,double c4,double c5,double c6,double c7,double c8,double c9,
double c10,double c11,double c12,double c13,double h1, double h2, double h3, double h4)
{
double ctot,htot,chtot;
ctot = c1+c2+c3+c4+c5+c6+c7+c8+c9+c10+c11+c12+c13;
htot = h1+h2+h3+h4;
chtot= ctot - htot;
printf("%g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g\n",T,c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13,h1,h2,h3,h4,ctot,htot,chtot);
}
void compute_cooling_from_T_and_Nh(double T,double X,double n_H,
double *c1,double *c2,double *c3,double *c4,double *c5,double *c6,double *c7,double *c8,double *c9,
double *c10,double *c11,double *c12,double *c13,double *h1, double *h2, double *h3, double *h4)
{
double n_HI,n_HII,n_HEI,n_HEII,n_HEIII,n_E,mu;
double nH2;
//double c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13;
//double h1,h2,h3,h4;
compute_densities(T,X,&n_H,&n_HI,&n_HII,&n_HEI,&n_HEII,&n_HEIII,&n_E,&mu);
nH2 = n_H*n_H;
/*
* compute cooling
*/
/* Bremstrahlung (cool_bre) */
*c1 = cooling_bremstrahlung_HI(T) *n_E*n_HII /nH2;
*c2 = cooling_bremstrahlung_HeI(T) *n_E*n_HEII /nH2;
*c3 = cooling_bremstrahlung_HeII(T) *n_E*n_HEIII/nH2;
/* Ionization cooling (cool_ion) */
*c4 = cooling_ionization_HI(T) *n_E*n_HI /nH2;
*c5 = cooling_ionization_HeI(T) *n_E*n_HEI /nH2;
*c6 = cooling_ionization_HeII(T) *n_E*n_HEII /nH2;
/* Recombination cooling (cool_rec) */
*c7 = cooling_recombination_HI(T) *n_E*n_HII /nH2;
*c8 = cooling_recombination_HeI(T) *n_E*n_HEII /nH2;
*c9 = cooling_recombination_HeII(T) *n_E*n_HEIII/nH2;
/* Dielectric recombination cooling (cool_die) */
*c10 = cooling_dielectric_recombination(T) *n_E*n_HEII /nH2;
/* Line cooling (cool_exc) */
*c11 = cooling_excitation_HI(T) *n_E*n_HI /nH2;
*c12 = cooling_excitation_HII(T) *n_E*n_HEII /nH2;
/* Compton cooling (cool_com) */
*c13 = cooling_compton(T) *n_E /nH2; /* !! dep on z */
/*
* compute heating
*/
/* Radiative heating (h_rad_spec) */
*h1 = Cte_heating_radiative_HI *n_HI /nH2;
*h2 = Cte_heating_radiative_HeI *n_HEI /nH2;
*h3 = Cte_heating_radiative_HeII *n_HEII /nH2;
/* Compton heating (heat_com) */
*h4 = heating_compton() *n_E /nH2; /* !! dep on z */
}
double compute_cooling_from_Egyspec_and_Density(double Egyspec,double Density,double *MeanWeight)
{
double T,mu,n_H;
double n_HI,n_HII,n_HEI,n_HEII,n_HEIII,n_E;
double err_mu,mu_left,mu_right,mu_old;
int niter;
double c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13;
double h1,h2,h3,h4;
double nH2;
/* Hydrogen density (cgs) */
n_H = HYDROGEN_MASSFRAC * Density/ PROTONMASS;
/* itterate to find the right mu and T */
err_mu=1.;
mu_left=0.5;
mu_right=1.3;
niter=0;
while ( (err_mu > 1.e-4) && (niter <= 50) )
{
mu_old=0.5*(mu_left+mu_right);
/* compute temperature */
T = GAMMA_MINUS1 *mu_old*PROTONMASS/BOLTZMANN *Egyspec;
/* compute all */
compute_densities(T,HYDROGEN_MASSFRAC,&n_H,&n_HI,&n_HII,&n_HEI,&n_HEII,&n_HEIII,&n_E,&mu);
err_mu = (mu-mu_old)/mu_old;
if(err_mu>0.)
{
mu_left =0.5*(mu_left+mu_right);
mu_right=mu_right;
}
else
{
mu_left =mu_left;
mu_right=0.5*(mu_left+mu_right);
}
err_mu=fabs(err_mu);
niter=niter+1;
}
if (niter > 50)
printf("ERROR : too many iterations.");
*MeanWeight = 0.5*(mu_left+mu_right);
/* now, compute cooling */
nH2 = n_H*n_H;
/*
* compute cooling
*/
/* Bremstrahlung (cool_bre) */
c1 = cooling_bremstrahlung_HI(T) *n_E*n_HII /nH2;
c2 = cooling_bremstrahlung_HeI(T) *n_E*n_HEII /nH2;
c3 = cooling_bremstrahlung_HeII(T) *n_E*n_HEIII/nH2;
/* Ionization cooling (cool_ion) */
c4 = cooling_ionization_HI(T) *n_E*n_HI /nH2;
c5 = cooling_ionization_HeI(T) *n_E*n_HEI /nH2;
c6 = cooling_ionization_HeII(T) *n_E*n_HEII /nH2;
/* Recombination cooling (cool_rec) */
c7 = cooling_recombination_HI(T) *n_E*n_HII /nH2;
c8 = cooling_recombination_HeI(T) *n_E*n_HEII /nH2;
c9 = cooling_recombination_HeII(T) *n_E*n_HEIII/nH2;
/* Dielectric recombination cooling (cool_die) */
c10 = cooling_dielectric_recombination(T) *n_E*n_HEII /nH2;
/* Line cooling (cool_exc) */
c11 = cooling_excitation_HI(T) *n_E*n_HI /nH2;
c12 = cooling_excitation_HII(T) *n_E*n_HEII /nH2;
/* Compton cooling (cool_com) */
c13 = cooling_compton(T) *n_E /nH2; /* !! dep on z */
/*
* compute heating
*/
/* Radiative heating (h_rad_spec) */
h1 = Cte_heating_radiative_HI *n_HI /nH2;
h2 = Cte_heating_radiative_HeI *n_HEI /nH2;
h3 = Cte_heating_radiative_HeII *n_HEII /nH2;
/* Compton heating (heat_com) */
h4 = heating_compton() *n_E /nH2; /* !! dep on z */
/* output info */
//print_cooling(T,c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13,h1,h2,h3,h4);
c1 = dmax(c1,0);
c2 = dmax(c2,0);
c3 = dmax(c3,0);
c4 = dmax(c4,0);
c5 = dmax(c5,0);
c6 = dmax(c6,0);
c7 = dmax(c7,0);
c8 = dmax(c8,0);
c9 = dmax(c9,0);
c10 = dmax(c10,0);
c11 = dmax(c11,0);
c12 = dmax(c12,0);
c13 = dmax(c13,0);
h1 = dmax(h1,0);
h2 = dmax(h2,0);
h3 = dmax(h3,0);
h4 = dmax(h4,0);
return (c1+c2+c3+c4+c5+c6+c7+c8+c9+c10+c11+c12+c13) - (h1+h2+h3+h4);
}
struct cooling_solver_params
{
double Entropy;
double Density;
int Phase;
int i;
double DtEntropyVisc;
double dt;
double hubble_a;
};
double cooling_solver_function(double EntropyVar, void *params)
{
struct cooling_solver_params *p = (struct cooling_solver_params *) params;
double Entropy = p->Entropy;
double Density = p->Density;
int Phase = p->Phase;
int i = p->i;
double DtEntropyVisc = p->DtEntropyVisc;
double dt = p->dt;
double hubble_a = p->hubble_a;
double DtEntropyRadSph=0;
#ifdef MULTIPHASE
switch (Phase)
{
case GAS_SPH:
DtEntropyRadSph = -GAMMA_MINUS1*pow(Density,-GAMMA)*lambda(Density,EntropyVar,Phase,i)/hubble_a;
break;
case GAS_STICKY:
case GAS_DARK:
DtEntropyRadSph = -1/(Density * a3inv) *lambda(Density,EntropyVar,Phase,i)/hubble_a;
break;
}
#else
DtEntropyRadSph = -GAMMA_MINUS1*pow(Density,-GAMMA)*lambda(Density,EntropyVar,Phase,i)/hubble_a;
#endif
return Entropy + (DtEntropyVisc + DtEntropyRadSph)*dt - EntropyVar;
};
/*! This function compute the new Entropy due to isochoric cooling
* using an implicit iteration scheme
*
* !!! here Density is already expressed in comobile coord
*
*/
double DoCooling(FLOAT Density,FLOAT Entropy,int Phase,int i,FLOAT DtEntropyVisc, double dt, double hubble_a)
{
double EntropyNew;
double Entropy_lo=0, Entropy_hi=0;
double lo,hi;
int status;
int iter = 0;
int max_iter = 100;
const gsl_root_fsolver_type *T;
gsl_root_fsolver *s;
gsl_function F;
struct cooling_solver_params params = {(double)Entropy,(double)Density,(int)Phase,(int)i,(double)DtEntropyVisc,(double)dt,(double)hubble_a};
F.function = &cooling_solver_function;
F.params = &params;
T = gsl_root_fsolver_brent;
s = gsl_root_fsolver_alloc (T);
Entropy_lo = 0.5*Entropy;
Entropy_hi = 1.1*Entropy;
lo = cooling_solver_function(Entropy_lo,&params);
hi = cooling_solver_function(Entropy_hi,&params);
if (lo*hi>0)
{
do
{
Entropy_hi = 2* Entropy_hi;
Entropy_lo = 0.5*Entropy_lo;
lo = cooling_solver_function(Entropy_lo,&params);
hi = cooling_solver_function(Entropy_hi,&params);
//printf("here, we need to iterate...\n");
}
while (lo*hi>0);
}
gsl_root_fsolver_set (s, &F, Entropy_lo, Entropy_hi);
do
{
iter++;
status = gsl_root_fsolver_iterate (s);
EntropyNew = gsl_root_fsolver_root (s);
Entropy_lo = gsl_root_fsolver_x_lower (s);
Entropy_hi = gsl_root_fsolver_x_upper (s);
status = gsl_root_test_interval (Entropy_lo, Entropy_hi,0, 0.001);
}
while (status == GSL_CONTINUE && iter < max_iter);
gsl_root_fsolver_free (s);
if (status!=GSL_SUCCESS)
{
printf("WARNING, HERE WE DO NOT CONVERGE...%g %g\n",Entropy_lo,Entropy_hi);
endrun(3737);
}
return EntropyNew;
}
/*! This function computes the entropy variation due to the cooling.
* Cooling is computed only for sph active particles.
*/
void cooling()
{
int i;
double dt=0;
double EntropyNew;
/* set the right Redshift and compute value indep of Temperature */
if (All.CoolingType==1)
init_from_new_redshift(1.0 / (All.Time) - 1);
if(All.ComovingIntegrationOn)
{
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);
a3inv = 1 / (All.Time * All.Time * All.Time);
}
else
a3inv = hubble_a = 1;
for(i = 0; i < NumPart; i++)
{
if(P[i].Ti_endstep == All.Ti_Current) /* active particles */
{
if(P[i].Type == 0) /* SPH stuff */
{
//DtEntropyRadSph=0.;
//SphP[i].DtEntropyRadSph = 0;
#ifdef MULTIPHASE
if (SphP[i].Phase == GAS_SPH)
{
#endif
/* note : SphP[i].DtEntropyRadSph should not be necessary */
dt = (All.Ti_Current - P[i].Ti_begstep) * All.Timebase_interval;
//SphP[i].DtEntropyRadSph = -GAMMA_MINUS1*pow(SphP[i].Density * a3inv,-GAMMA)*lambda(SphP[i].Density *a3inv,SphP[i].Entropy,0,i)/hubble_a;
//if (fabs((SphP[i].DtEntropyRadSph+SphP[i].DtEntropy)*dt) > 0.1*fabs(SphP[i].Entropy))
{
/* do implicit isochoric cooling */
EntropyNew = DoCooling(SphP[i].Density*a3inv,SphP[i].Entropy,0,i,SphP[i].DtEntropy,dt,hubble_a);
if(dt > 0)
SphP[i].DtEntropy = (EntropyNew - SphP[i].Entropy)/dt;
}
//else
{
// SphP[i].DtEntropy += SphP[i].DtEntropyRadSph;
}
//SphP[i].DtEgySpecRadSph = - 1/GAMMA_MINUS1 * pow(SphP[i].Density * a3inv,GAMMA_MINUS1) * (SphP[i].DtEntropyRadSph);
#ifdef MULTIPHASE
}
else /* STICKY OR DARK */
{
//SphP[i].DtEntropyRadSph = -1/(SphP[i].Density * a3inv)*lambda(SphP[i].Density *a3inv,SphP[i].Entropy,SphP[i].Phase,i)/hubble_a;
//SphP[i].DtEntropy += SphP[i].DtEntropyRadSph;
/* do implicit isochoric cooling */
dt = (All.Ti_Current - P[i].Ti_begstep) * All.Timebase_interval;
EntropyNew = DoCooling(SphP[i].Density*a3inv,SphP[i].Entropy,SphP[i].Phase,i,SphP[i].DtEntropy,dt,hubble_a);
if(dt > 0)
SphP[i].DtEntropy = (EntropyNew - SphP[i].Entropy)/dt;
/* !!! here, we do not take into account the energy variation !!! */
/* SphP[i].DtEgySpecRadSph = SphP[i].DtEntropy, no ?*/
}
#endif
/* finally sum to the entropy variation */
/* WARNING : we do not compute DtEntropy here, it is updated in timestep.c */
/* no, because, it is updated juste above, no ? */
//SphP[i].DtEntropy += SphP[i].DtEntropyRadSph;
//SphP[i].DtEntropy += SphP[i].DtEgySpecRadSph / (-1/GAMMA_MINUS1 * pow(SphP[i].Density * a3inv,GAMMA_MINUS1));
}
}
}
}
/*! This function computes the new entropy due to the cooling,
* between step t0 and t1.
*/
void CoolingForOne(int i,int tstart,int tend,double a3inv,double hubble_a)
{
double dt,dadt,tcool,dt_entr;
double MinSizeTimestep,ErrTolIntAccuracy;
int ti_current,istep;
int ti_step;
double minentropy;
FLOAT Entropy,DEntropy,DtEntropy,DtEgySpec;
if(All.MinEgySpec)
minentropy = All.MinEgySpec * GAMMA_MINUS1 / pow(SphP[i].Density * a3inv, GAMMA_MINUS1);
/* compute dt */
/* here we use the convention of Gadget */
/* this assume that DtEntropy = dA/dt/hubble_a */
/* and not only dA/dt */
dt_entr = (tend - tstart) * All.Timebase_interval;
ErrTolIntAccuracy = 0.02;
MinSizeTimestep = 0.01*dt_entr;
/* compute da/dt */
//dadt = fabs( -GAMMA_MINUS1*pow(SphP[i].Density * a3inv,-GAMMA)*lambda(SphP[i].Density *a3inv,SphP[i].Entropy,0,i)/hubble_a );
/* compute cooling time */
//tcool = SphP[i].Entropy / dadt;
//if (ErrTolIntAccuracy*tcool/dt_entr < 1)
// printf("** %g %g\n",ErrTolIntAccuracy*tcool,dt_entr); /* --> verifier le cooling time */
/***************************************/
/* integrate with adaptative timesteps */
/***************************************/
Entropy = SphP[i].Entropy;
ti_current = tstart;
istep = 0;
#ifdef CHIMIE_THERMAL_FEEDBACK
int no_cooling;
int Tis,Tic;
double td;
no_cooling=0;
if (All.ComovingIntegrationOn)
{
Tis = log(SphP[i].ThermalTime/All.TimeBegin) / All.Timebase_interval;
Tic = All.Ti_Current;
td = get_cosmictime_difference(Tis,Tic);
if (td<All.ChimieThermalTime)
no_cooling=1;
}
else
{
if ((All.Time-SphP[i].ThermalTime)<All.ChimieThermalTime)
no_cooling=1;
}
//if (SphP[i].ThermalTime > (All.Time-All.ChimieThermalTime))
if(no_cooling)
{
Entropy = Entropy + SphP[i].DtEntropy* dt_entr;
/* avoid Entropy to be less than minentropy */
if(All.MinEgySpec)
if(Entropy < minentropy)
Entropy = minentropy;
/* update particle */
SphP[i].DtEntropy = (Entropy-SphP[i].Entropy)/dt_entr;
SphP[i].Entropy = Entropy;
return ;
}
#endif
while (ti_current<tend)
{
/* compute da/dt */
dadt = fabs( -GAMMA_MINUS1*pow(SphP[i].Density * a3inv,-GAMMA)*lambda(SphP[i].Density *a3inv,Entropy,0,i)/hubble_a );
/* compute cooling time */
/* this is similar in comobile integraction */
tcool = Entropy / dadt;
/* find dt */
dt = dmax(MinSizeTimestep, tcool*ErrTolIntAccuracy);
dt = dmin(dt,dt_entr);
ti_step = dt / All.Timebase_interval;
ti_step = imax(1,ti_step);
ti_step = imin(ti_step,tend-ti_current);
dt = ti_step* All.Timebase_interval;
#ifndef IMPLICIT_COOLING_INTEGRATION
/* normal integration of Entropy */
Entropy += SphP[i].DtEntropy* dt; /* viscosity */
Entropy += -GAMMA_MINUS1*pow(SphP[i].Density * a3inv,-GAMMA)*lambda(SphP[i].Density *a3inv,Entropy,0,i)/hubble_a *dt; /* cooling */
#else
/* or use implicit integration of Entropy */
/* need this if there is also heating like UV */
if(All.ComovingIntegrationOn)
{
printf("CoolingForOne : this must be checked !\n");
endrun(123321);
}
Entropy = DoCooling(SphP[i].Density*a3inv,Entropy,0,i,SphP[i].DtEntropy,dt,hubble_a);
#endif
/* avoid Entropy to be less than minentropy */
if(All.MinEgySpec)
if(Entropy < minentropy)
{
Entropy = minentropy;
break;
}
ti_current += ti_step;
istep = istep+1;
}
/* entropy only due to cooling */
DEntropy = Entropy-SphP[i].Entropy - SphP[i].DtEntropy* dt_entr;
DtEntropy = DEntropy/dt_entr;
//if (istep>1)
// printf("* %d %d %d %g %g\n",istep,ti_current,tend,SphP[i].DtEntropy,DtEntropy);
/* update particle */
SphP[i].Entropy = Entropy;
SphP[i].DtEntropy = SphP[i].DtEntropy + DtEntropy;
DtEgySpec = - 1/GAMMA_MINUS1 * pow(SphP[i].Density * a3inv,GAMMA_MINUS1) * (DtEntropy);
LocalSysState.RadiatedEnergy += DtEgySpec * dt_entr * P[i].Mass;
#ifdef CHECK_ENTROPY_SIGN
if (SphP[i].Entropy < 0)
{
printf("\ntask=%d: entropy less than zero in CoolingForOne !\n", ThisTask);
printf("ID=%d Entropy=%g EntropyPred=%g DtEntropy=%g\n",P[i].ID,SphP[i].Entropy,SphP[i].EntropyPred,SphP[i].DtEntropy);
fflush(stdout);
endrun(444001);
}
#endif
}
/*! cooling function
*
*/
double lambda(FLOAT Density,FLOAT Entropy,int phase,int i)
{
/*
* These function returns the Lambda (not the Lambda_n)
* Here, we assume that Lambda may also contain the heating term.
*
* Here, the Entropy and Density are physical, but in h units
*
* The function is used only in cooling.c
*
*/
double EgySpec;
double MeanWeight;
double T=0,nH=0,nH2=0,l=0;
double nHcgs=0,nH2cgs=0;
#ifdef HEATING
double Gpe=0;
double X,XTne,eps,ne,flux_in_cgs;
#endif
/* number of Hydrogen atoms per unit volume (user units, not corrected from h : [nH] = h2/cm^3 ) */
#ifndef DO_NO_USE_HYDROGEN_MASSFRAC_IN_COOLING
nH = HYDROGEN_MASSFRAC*Density/All.ProtonMass;
#else
nH = 1 *Density/All.ProtonMass;
#endif
nH2 = nH*nH;
-
+
/* in cgs, corrected from h */
- nHcgs = nH/pow(All.UnitLength_in_cm, 3);
- //if(All.ComovingIntegrationOn)
- // nHcgs *= (All.HubbleParam*All.HubbleParam);
+ nHcgs = nH/pow(All.UnitLength_in_cm, 3)*(All.HubbleParam*All.HubbleParam);
nH2cgs = nHcgs*nHcgs;
/* compute temperature */
#ifdef MULTIPHASE
switch(phase)
{
case GAS_SPH:
T = All.mumh/All.Boltzmann * Entropy * pow(Density,GAMMA_MINUS1);
break;
case GAS_STICKY:
case GAS_DARK:
T = All.mumh/All.Boltzmann * GAMMA_MINUS1 * Entropy;
break;
}
#else
T = All.mumh/All.Boltzmann * Entropy * pow(Density,GAMMA_MINUS1);
#endif
/*******************
* * * COOLING * * *
*******************/
if (All.CoolingType==0 || All.CoolingType==2)
{
/**************/
/* Sutherland */
/**************/
#ifdef MULTIPHASE
switch(phase)
{
case GAS_SPH:
if (T > All.CutofCoolingTemperature)
if (All.CoolingType==0)
l = cooling_function(T);
else
#ifdef CHIMIE
l = cooling_function_with_metals(T,SphP[i].Metal[FE]);
#else
l = cooling_function_with_metals(T,(pow(10,All.InitGasMetallicity)-1e-10)*All.CoolingParameters_FeHSolar);
#endif
else
l = 0;
break;
case GAS_STICKY:
case GAS_DARK:
if (T > All.CutofCoolingTemperature)
if (All.CoolingType==0)
l = cooling_function(T);
else
#ifdef CHIMIE
l = cooling_function_with_metals(T,SphP[i].Metal[FE]);
#else
l = cooling_function_with_metals(T,(pow(10,All.InitGasMetallicity)-1e-10)*All.CoolingParameters_FeHSolar);
#endif
else
l = 0;
break;
}
#else
/* here, lambda' is in erg*cm^3/s = kg*m^5/s^3 */
if (T > All.CutofCoolingTemperature)
if (All.CoolingType==0)
l = cooling_function(T);
else
#ifdef CHIMIE
l = cooling_function_with_metals(T,SphP[i].Metal[FE]);
#else
l = cooling_function_with_metals(T,(pow(10,All.InitGasMetallicity)-1e-10)*All.CoolingParameters_FeHSolar);
#endif
else
l = 0;
#endif
}
else
{
/******************************/
/* cooling with UV background */
/******************************/
/* get the right density and egyspec in cgs */
/* entropy and density are already physical */
#ifdef MULTIPHASE
/* WARNING, HERE, WE MUST DIFERENCIATE ACORDING TO THE PHASE... */
printf("WARNING, HERE, WE MUST DIFERENCIATE ACORDING TO THE PHASE...\n");
exit(0);
// if (phase == GAS_SPH)
// EgySpec = Entropy / GAMMA_MINUS1 * pow(Density, GAMMA_MINUS1);
// else
// EgySpec = Entropy;
#else
EgySpec = Entropy / GAMMA_MINUS1 * pow(Density, GAMMA_MINUS1);
#endif
/* into cgs, corrected from h */
EgySpec *= All.UnitEnergy_in_cgs/All.UnitMass_in_g;
Density *= All.UnitDensity_in_cgs;
//if(All.ComovingIntegrationOn)
// Density *= (All.HubbleParam*All.HubbleParam);
/* compute cooling from EnergySpec and Density */
l = compute_cooling_from_Egyspec_and_Density(EgySpec,Density,&MeanWeight);
/* compute temperature */
/*
Temperature = GAMMA_MINUS1 *MeanWeight*PROTONMASS/BOLTZMANN *EgySpec;
//printf("%g %g %g\n",Temperature,MeanWeight,Lambda);
logT = log10(Temperature);
*/
}
/*******************
* * * HEATING * * *
*******************/
#ifdef HEATING
#ifdef HEATING_PE
/**************************/
/* Photo-electric heating */ /* all must be in cgs */
/**************************/
X = 0;
#ifdef STELLAR_FLUX
flux_in_cgs = SphP[i].EnergyFlux* All.UnitEnergy_in_cgs/All.UnitTime_in_s/pow(All.UnitLength_in_cm, 2);
X = X + flux_in_cgs/C / All.HeatingPeSolarEnergyDensity;
#endif
#ifdef EXTERNAL_FLUX
X = X + All.HeatingExternalFLuxEnergyDensity/All.HeatingPeSolarEnergyDensity ;
#endif
ne = nHcgs*All.HeatingPeElectronFraction;
XTne = X*sqrt(T)/ne;
eps = 4.87e-2/(1+4e-3*pow(XTne,0.73)) + 3.65e-2*(T/1e4)/(1+2e-4*XTne);
Gpe = (1e-24 * eps * X * nHcgs)/ nH2cgs ;
l = l - Gpe;
#endif /*HEATING_PE*/
#endif
/**********************************
* * * final unit conversions * * *
***********************************/
/* convert lambda' in user units */
l = l / All.UnitEnergy_in_cgs /pow(All.UnitLength_in_cm,3) * All.UnitTime_in_s;
+
+ /* in unit with h */
+ l = l*All.HubbleParam;
+
/* correct from h */
/*
* [ Lambda / H / rho_p ] = [u] = cm^2/s^2
*
* [H] = h/s
* [rho_p] = g/cm^3 * h^2
* [Lambda_n] = g * m^5 / s^3
* [n] = h^2/m^5
*
* => Lambda_n must be multiplied by h (in order to remove one h !! not a unit !!)
*
*/
//if(All.ComovingIntegrationOn)
// l = l * All.HubbleParam;
/* get the final lambda by multiplying lambda' by nH2 (all in user units) */
l = l*nH2;
return l;
}
#endif
diff --git a/domain.c b/domain.c
index e6aab56..ff54a09 100644
--- a/domain.c
+++ b/domain.c
@@ -1,1818 +1,1817 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <mpi.h>
#include "allvars.h"
#include "proto.h"
/*! \file domain.c
* \brief code for domain decomposition
*
* This file contains the code for the domain decomposition of the
* simulation volume. The domains are constructed from disjoint subsets
* of the leaves of a fiducial top-level tree that covers the full
* simulation volume. Domain boundaries hence run along tree-node
* divisions of a fiducial global BH tree. As a result of this method, the
* tree force are in principle strictly independent of the way the domains
* are cut. The domain decomposition can be carried out for an arbitrary
* number of CPUs. Individual domains are not cubical, but spatially
* coherent since the leaves are traversed in a Peano-Hilbert order and
* individual domains form segments along this order. This also ensures
* that each domain has a small surface to volume ratio, which minimizes
* communication.
*/
#define TOPNODEFACTOR 20.0
#define REDUC_FAC 0.98
/*! toGo[task*NTask + partner] gives the number of particles in task 'task'
* that have to go to task 'partner'
*/
static int *toGo, *toGoSph;
static int *local_toGo, *local_toGoSph;
static int *list_NumPart;
static int *list_N_gas;
static int *list_load;
static int *list_loadsph;
static double *list_work;
#ifdef STELLAR_PROP
static int *toGoSt;
static int *local_toGoSt;
static int *list_N_stars;
#endif
static long long maxload, maxloadsph;
static struct topnode_exchange
{
peanokey Startkey;
int Count;
}
*toplist, *toplist_local;
/*! This is the main routine for the domain decomposition. It acts as a
* driver routine that allocates various temporary buffers, maps the
* particles back onto the periodic box if needed, and then does the
* domain decomposition, and a final Peano-Hilbert order of all particles
* as a tuning measure.
*/
void domain_Decomposition(void)
{
double t0, t1;
int i;
#ifdef PMGRID
if(All.PM_Ti_endstep == All.Ti_Current)
{
All.NumForcesSinceLastDomainDecomp = 1 + All.TotNumPart * All.TreeDomainUpdateFrequency;
/* to make sure that we do a domain decomposition before the PM-force is evaluated.
this is needed to make sure that the particles are wrapped into the box */
}
#endif
/* Check whether it is really time for a new domain decomposition */
if(All.NumForcesSinceLastDomainDecomp > All.TotNumPart * All.TreeDomainUpdateFrequency)
{
t0 = second();
#ifdef PERIODIC
do_box_wrapping(); /* map the particles back onto the box */
#endif
All.NumForcesSinceLastDomainDecomp = 0;
#ifdef SFR
rearrange_particle_sequence();
#endif
TreeReconstructFlag = 1; /* ensures that new tree will be constructed */
if(ThisTask == 0)
{
printf("start domain decomposition... \n");
fflush(stdout);
}
Key = malloc(sizeof(peanokey) * All.MaxPart);
KeySorted = malloc(sizeof(peanokey) * All.MaxPart);
toGo = malloc(sizeof(int) * NTask * NTask);
toGoSph = malloc(sizeof(int) * NTask * NTask);
local_toGo = malloc(sizeof(int) * NTask);
local_toGoSph = malloc(sizeof(int) * NTask);
list_NumPart = malloc(sizeof(int) * NTask);
list_N_gas = malloc(sizeof(int) * NTask);
list_load = malloc(sizeof(int) * NTask);
list_loadsph = malloc(sizeof(int) * NTask);
list_work = malloc(sizeof(double) * NTask);
MPI_Allgather(&NumPart, 1, MPI_INT, list_NumPart, 1, MPI_INT, MPI_COMM_WORLD);
MPI_Allgather(&N_gas, 1, MPI_INT, list_N_gas, 1, MPI_INT, MPI_COMM_WORLD);
#ifdef STELLAR_PROP
toGoSt = malloc(sizeof(int) * NTask * NTask);
local_toGoSt = malloc(sizeof(int) * NTask);
list_N_stars = malloc(sizeof(int) * NTask);
MPI_Allgather(&N_stars, 1, MPI_INT, list_N_stars, 1, MPI_INT, MPI_COMM_WORLD);
#endif
maxload = All.MaxPart * REDUC_FAC;
maxloadsph = All.MaxPartSph * REDUC_FAC;
#ifdef CHECK_ID_CORRESPONDENCE
if (ThisTask==0)
printf("Check id correspondence before decomposition...\n");
rearrange_particle_sequence();
for(i = N_gas; i < N_gas+N_stars; i++)
{
if( StP[P[i].StPIdx].PIdx != i )
{
printf("\nP/StP correspondance error\n");
printf("(%d) (in domain before) N_stars=%d N_gas=%d i=%d id=%d P[i].StPIdx=%d StP[P[i].StPIdx].PIdx=%d\n\n",ThisTask,N_stars,N_gas,i,P[i].ID,P[i].StPIdx,StP[P[i].StPIdx].PIdx);
endrun(888001);
}
if(StP[P[i].StPIdx].ID != P[i].ID)
{
printf("\nP/StP correspondance error\n");
printf("(%d) (in domain before) N_gas=%d N_stars=%d i=%d Type=%d P.Id=%d P[i].StPIdx=%d StP[P[i].StPIdx].ID=%d \n\n",ThisTask,N_gas,N_stars,i,P[i].Type,P[i].ID, P[i].StPIdx, StP[P[i].StPIdx].ID);
endrun(888002);
}
}
if (ThisTask==0)
printf("Check id correspondence before decomposition done...\n");
#endif
domain_decompose();
free(list_work);
free(list_loadsph);
free(list_load);
free(list_N_gas);
free(list_NumPart);
free(local_toGoSph);
free(local_toGo);
free(toGoSph);
free(toGo);
#ifdef STELLAR_PROP
free(list_N_stars);
free(local_toGoSt);
free(toGoSt);
#endif
#ifdef CHECK_BLOCK_ORDER
int typenow;
typenow = 0;
for(i = 0; i < NumPart; i++)
{
if ((P[i].Type<typenow)&&(typenow<=ST))
{
printf("\nBlock order error\n");
printf("(%d) i=%d Type=%d typenow=%d\n\n",ThisTask,i,P[i].Type,typenow);
endrun(888003);
}
typenow = P[i].Type;
}
#endif
#ifdef CHECK_ID_CORRESPONDENCE
if (ThisTask==0)
printf("Check id correspondence after decomposition...\n");
rearrange_particle_sequence();
for(i = N_gas; i < N_gas+N_stars; i++)
{
if( StP[P[i].StPIdx].PIdx != i )
{
printf("\nP/StP correspondance error\n");
printf("(%d) (in domain after) N_stars=%d N_gas=%d i=%d id=%d P[i].StPIdx=%d StP[P[i].StPIdx].PIdx=%d\n\n",ThisTask,N_stars,N_gas,i,P[i].ID,P[i].StPIdx,StP[P[i].StPIdx].PIdx);
endrun(888004);
}
if(StP[P[i].StPIdx].ID != P[i].ID)
{
printf("\nP/StP correspondance error\n");
printf("(%d) (in domain after) N_gas=%d N_stars=%d i=%d Type=%d P.Id=%d P[i].StPIdx=%d StP[P[i].StPIdx].ID=%d \n\n",ThisTask,N_gas,N_stars,i,P[i].Type,P[i].ID, P[i].StPIdx, StP[P[i].StPIdx].ID);
endrun(888005);
}
}
if (ThisTask==0)
printf("Check id correspondence after decomposition done...\n");
#endif
if(ThisTask == 0)
{
printf("domain decomposition done. \n");
fflush(stdout);
}
t1 = second();
All.CPU_Domain += timediff(t0, t1);
#ifdef PEANOHILBERT
t0 = second();
peano_hilbert_order();
t1 = second();
All.CPU_Peano += timediff(t0, t1);
#endif
free(KeySorted);
free(Key);
}
}
/*! This function carries out the actual domain decomposition for all
* particle types. It will try to balance the work-load for each domain,
* as estimated based on the P[i]-GravCost values. The decomposition will
* respect the maximum allowed memory-imbalance given by the value of
* PartAllocFactor.
*/
void domain_decompose(void)
{
int i, j, status;
int ngrp, task, partner, sendcount, recvcount;
long long sumtogo, sumload;
int maxload, *temp;
double sumwork, maxwork;
#ifdef DETAILED_CPU_DOMAIN
double t0, t1;
#endif
for(i = 0; i < 6; i++)
NtypeLocal[i] = 0;
for(i = 0; i < NumPart; i++)
NtypeLocal[P[i].Type]++;
/* because Ntype[] 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(NtypeLocal, 6, MPI_INT, temp, 6, MPI_INT, MPI_COMM_WORLD);
for(i = 0; i < 6; i++)
{
Ntype[i] = 0;
for(j = 0; j < NTask; j++)
Ntype[i] += temp[j * 6 + i];
}
free(temp);
#ifndef UNEQUALSOFTENINGS
for(i = 0; i < 6; i++)
if(Ntype[i] > 0)
break;
for(ngrp = i + 1; ngrp < 6; ngrp++)
{
if(Ntype[ngrp] > 0)
if(All.SofteningTable[ngrp] != All.SofteningTable[i])
{
if(ThisTask == 0)
{
fprintf(stdout, "Code was not compiled with UNEQUALSOFTENINGS, but some of the\n");
fprintf(stdout, "softening lengths are unequal nevertheless.\n");
fprintf(stdout, "This is not allowed.\n");
}
endrun(0);
}
}
#endif
/* determine global dimensions of domain grid */
#ifdef DETAILED_CPU_DOMAIN
t0 = second();
#endif
domain_findExtent();
#ifdef DETAILED_CPU_DOMAIN
t1 = second();
All.CPU_Domain_findExtend += timediff(t0, t1);
#endif
#ifdef DETAILED_CPU_DOMAIN
t0 = second();
#endif
domain_determineTopTree();
#ifdef DETAILED_CPU_DOMAIN
t1 = second();
All.CPU_Domain_determineTopTree += timediff(t0, t1);
#endif
/* determine cost distribution in domain grid */
#ifdef DETAILED_CPU_DOMAIN
t0 = second();
#endif
domain_sumCost();
#ifdef DETAILED_CPU_DOMAIN
t1 = second();
All.CPU_Domain_sumCost += timediff(t0, t1);
#endif
/* find the split of the domain grid recursively */
#ifdef DETAILED_CPU_DOMAIN
t0 = second();
#endif
#ifdef SPLIT_DOMAIN_USING_TIME
status = domain_findSplityr(0, NTask, 0, NTopleaves - 1);
#else
status = domain_findSplit(0, NTask, 0, NTopleaves - 1);
#endif
#ifdef DETAILED_CPU_DOMAIN
t1 = second();
All.CPU_Domain_findSplit += timediff(t0, t1);
#endif
if(status != 0)
{
if(ThisTask == 0)
printf("\nNo domain decomposition that stays within memory bounds is possible (status=%d).\n",status);
endrun(0);
}
/* now try to improve the work-load balance of the split */
#ifdef DETAILED_CPU_DOMAIN
t0 = second();
#endif
#ifdef SPLIT_DOMAIN_USING_TIME
domain_shiftSplityr();
#else
domain_shiftSplit();
#endif
#ifdef DETAILED_CPU_DOMAIN
t1 = second();
All.CPU_Domain_shiftSplit += timediff(t0, t1);
#endif
DomainMyStart = DomainStartList[ThisTask];
DomainMyLast = DomainEndList[ThisTask];
if(ThisTask == 0)
{
sumload = maxload = 0;
sumwork = maxwork = 0;
for(i = 0; i < NTask; i++)
{
sumload += list_load[i];
sumwork += list_work[i];
if(list_load[i] > maxload)
maxload = list_load[i];
if(list_work[i] > maxwork)
maxwork = list_work[i];
}
printf("work-load balance=%g memory-balance=%g\n",
maxwork / (sumwork / NTask), maxload / (((double) sumload) / NTask));
}
/* determine for each cpu how many particles have to be shifted to other cpus */
#ifdef DETAILED_CPU_DOMAIN
t0 = second();
#endif
domain_countToGo();
#ifdef DETAILED_CPU_DOMAIN
t1 = second();
All.CPU_Domain_countToGo += timediff(t0, t1);
#endif
#ifdef DETAILED_CPU_DOMAIN
t0 = second();
#endif
for(i = 0, sumtogo = 0; i < NTask * NTask; i++)
sumtogo += toGo[i];
while(sumtogo > 0)
{
if(ThisTask == 0)
{
printf("exchange of %d%09d particles\n", (int) (sumtogo / 1000000000),
(int) (sumtogo % 1000000000));
fflush(stdout);
}
for(ngrp = 1; ngrp < (1 << PTask); ngrp++)
{
for(task = 0; task < NTask; task++)
{
partner = task ^ ngrp;
if(partner < NTask && task < partner)
{
/* treat SPH separately */
if(All.TotN_gas > 0)
{
domain_findExchangeNumbers(task, partner, 0, &sendcount, &recvcount);
list_NumPart[task] += recvcount - sendcount;
list_NumPart[partner] -= recvcount - sendcount;
list_N_gas[task] += recvcount - sendcount;
list_N_gas[partner] -= recvcount - sendcount;
toGo[task * NTask + partner] -= sendcount;
toGo[partner * NTask + task] -= recvcount;
toGoSph[task * NTask + partner] -= sendcount;
toGoSph[partner * NTask + task] -= recvcount;
//if (sendcount>0)
// printf("(%d) gas --> %d (%d)\n",ThisTask,sendcount,N_gas);
//if (recvcount>0)
// printf("(%d) gas <-- %d (%d)\n",ThisTask,recvcount,N_gas);
//printf("(%d) N_gas=%d P[N_gas].ID=%d %d (%d %d)\n",ThisTask,N_gas,P[N_gas].ID,P[N_gas].Type,sendcount,recvcount);
if(task == ThisTask) /* actually carry out the exchange */
domain_exchangeParticles(partner, 0, sendcount, recvcount);
if(partner == ThisTask)
domain_exchangeParticles(task, 0, recvcount, sendcount);
//if (sendcount>0)
// printf("(%d) (after) gas --> %d (%d)\n",ThisTask,sendcount,N_gas);
//if (recvcount>0)
// printf("(%d) (after) gas <-- %d (%d)\n",ThisTask,recvcount,N_gas);
//printf("(%d) (after) N_gas=%d P[N_gas].ID=%d %d (%d %d)\n",ThisTask,N_gas,P[N_gas].ID,P[N_gas].Type,sendcount,recvcount);
}
#ifdef STELLAR_PROP
/* treat STARS separately */
if(All.TotN_stars > 0)
{
domain_findExchangeNumbers(task, partner, 1, &sendcount, &recvcount);
list_NumPart[task] += recvcount - sendcount;
list_NumPart[partner] -= recvcount - sendcount;
list_N_stars[task] += recvcount - sendcount;
list_N_stars[partner] -= recvcount - sendcount;
toGo[task * NTask + partner] -= sendcount;
toGo[partner * NTask + task] -= recvcount;
toGoSt[task * NTask + partner] -= sendcount;
toGoSt[partner * NTask + task] -= recvcount;
//if (sendcount>0)
// printf("(%d) stars --> %d (%d)\n",ThisTask,sendcount,N_stars);
//if (recvcount>0)
// printf("(%d) stars <-- %d (%d)\n",ThisTask,recvcount,N_stars);
if(task == ThisTask) /* actually carry out the exchange */
domain_exchangeParticles(partner, 1, sendcount, recvcount);
if(partner == ThisTask)
domain_exchangeParticles(task, 1, recvcount, sendcount);
//if (sendcount>0)
// printf("(%d) stars --> %d (%d)\n",ThisTask,sendcount,N_stars);
//if (recvcount>0)
// printf("(%d) stars <-- %d (%d)\n",ThisTask,recvcount,N_stars);
}
#endif
domain_findExchangeNumbers(task, partner, -1, &sendcount, &recvcount);
list_NumPart[task] += recvcount - sendcount;
list_NumPart[partner] -= recvcount - sendcount;
toGo[task * NTask + partner] -= sendcount;
toGo[partner * NTask + task] -= recvcount;
if(task == ThisTask) /* actually carry out the exchange */
domain_exchangeParticles(partner, -1, sendcount, recvcount);
if(partner == ThisTask)
domain_exchangeParticles(task, -1, recvcount, sendcount);
}
}
}
for(i = 0, sumtogo = 0; i < NTask * NTask; i++)
sumtogo += toGo[i];
}
#ifdef SFR
#ifndef STELLAR_PROP
/* count the new N_stars : in case STELLAR_PROP is on,
N_stars is already updated during the domain decomposition */
int nstars;
for(i = N_gas, nstars = 0; i < NumPart; i++)
{
if (P[i].Type==ST)
nstars++;
}
N_stars = nstars;
#endif
#endif
#ifdef DETAILED_CPU_DOMAIN
t1 = second();
All.CPU_Domain_exchange += timediff(t0, t1);
#endif
}
/*! This function tries to find a split point in a range of cells in the
* domain-grid. The range of cells starts at 'first', and ends at 'last'
* (inclusively). The number of cpus that holds the range is 'ncpu', with
* the first cpu given by 'cpustart'. If more than 2 cpus are to be split,
* the function calls itself recursively. The division tries to achieve a
* best particle-load balance under the constraint that 'maxload' and
* 'maxloadsph' may not be exceeded, and that each cpu holds at least one
* cell from the domaingrid. If such a decomposition cannot be achieved, a
* non-zero error code is returned.
*
* After successful completion, DomainMyStart[] and DomainMyLast[] contain
* the first and last cell of the domaingrid assigned to the local task
* for the given type. Also, DomainTask[] contains for each cell the task
* it was assigned to.
*/
int domain_findSplit(int cpustart, int ncpu, int first, int last)
{
int i, split, ok_left, ok_right;
long long load, sphload, load_leftOfSplit, sphload_leftOfSplit;
int ncpu_leftOfSplit;
double maxAvgLoad_CurrentSplit, maxAvgLoad_NewSplit;
ncpu_leftOfSplit = ncpu / 2;
for(i = first, load = 0, sphload = 0; i <= last; i++)
{
load += DomainCount[i];
sphload += DomainCountSph[i];
}
split = first + ncpu_leftOfSplit;
for(i = first, load_leftOfSplit = sphload_leftOfSplit = 0; i < split; i++)
{
load_leftOfSplit += DomainCount[i];
sphload_leftOfSplit += DomainCountSph[i];
}
/* find the best split point in terms of work-load balance */
while(split < last - (ncpu - ncpu_leftOfSplit - 1) && split > 0)
{
maxAvgLoad_CurrentSplit =
dmax(load_leftOfSplit / ncpu_leftOfSplit, (load - load_leftOfSplit) / (ncpu - ncpu_leftOfSplit));
maxAvgLoad_NewSplit =
dmax((load_leftOfSplit + DomainCount[split]) / ncpu_leftOfSplit,
(load - load_leftOfSplit - DomainCount[split]) / (ncpu - ncpu_leftOfSplit));
if(maxAvgLoad_NewSplit <= maxAvgLoad_CurrentSplit)
{
load_leftOfSplit += DomainCount[split];
sphload_leftOfSplit += DomainCountSph[split];
split++;
}
else
break;
}
/* we will now have to check whether this solution is possible given the restrictions on the maximum load */
for(i = first, load_leftOfSplit = 0, sphload_leftOfSplit = 0; i < split; i++)
{
load_leftOfSplit += DomainCount[i];
sphload_leftOfSplit += DomainCountSph[i];
}
if(load_leftOfSplit > maxload * ncpu_leftOfSplit ||
(load - load_leftOfSplit) > maxload * (ncpu - ncpu_leftOfSplit))
{
/* we did not find a viable split */
printf("(%d) error -1 ",ThisTask);
return -1;
}
if(sphload_leftOfSplit > maxloadsph * ncpu_leftOfSplit ||
(sphload - sphload_leftOfSplit) > maxloadsph * (ncpu - ncpu_leftOfSplit))
{
/* we did not find a viable split */
printf("(%d) error -2 ",ThisTask);
return -2;
}
if(ncpu_leftOfSplit >= 2)
ok_left = domain_findSplit(cpustart, ncpu_leftOfSplit, first, split - 1);
else
ok_left = 0;
if((ncpu - ncpu_leftOfSplit) >= 2)
ok_right = domain_findSplit(cpustart + ncpu_leftOfSplit, ncpu - ncpu_leftOfSplit, split, last);
else
ok_right = 0;
if(ok_left == 0 && ok_right == 0)
{
/* found a viable split */
if(ncpu_leftOfSplit == 1)
{
for(i = first; i < split; i++)
DomainTask[i] = cpustart;
list_load[cpustart] = load_leftOfSplit;
list_loadsph[cpustart] = sphload_leftOfSplit;
DomainStartList[cpustart] = first;
DomainEndList[cpustart] = split - 1;
}
if((ncpu - ncpu_leftOfSplit) == 1)
{
for(i = split; i <= last; i++)
DomainTask[i] = cpustart + ncpu_leftOfSplit;
list_load[cpustart + ncpu_leftOfSplit] = load - load_leftOfSplit;
list_loadsph[cpustart + ncpu_leftOfSplit] = sphload - sphload_leftOfSplit;
DomainStartList[cpustart + ncpu_leftOfSplit] = split;
DomainEndList[cpustart + ncpu_leftOfSplit] = last;
}
return 0;
}
/* we did not find a viable split */
return -3;
}
#ifdef SPLIT_DOMAIN_USING_TIME
/*! This function tries to find a split point in a range of cells
*/
int domain_findSplityr(int cpustart, int ncpu, int first, int last)
{
int i, split, ok_left, ok_right;
long long load, sphload, load_leftOfSplit, sphload_leftOfSplit;
int ncpu_leftOfSplit;
double maxAvgLoad_CurrentSplit, maxAvgLoad_NewSplit;
/************************************/
/* find the number of part per proc */
/************************************/
double sumCPU_Gravity,meanCPU_Gravity;
double imb;
double ImbFactor;
int NumPartDiff,sumNumPartDiff,DesiredNumPart;
int *list_DesiredNumPart;
MPI_Allreduce(&CPU_Gravity, &sumCPU_Gravity, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
meanCPU_Gravity = sumCPU_Gravity/NTask;
if (sumCPU_Gravity>0)
{
imb = CPU_Gravity/meanCPU_Gravity;
NumPartDiff = (int) ((meanCPU_Gravity-CPU_Gravity)/meanCPU_Gravity * All.TotNumPart/NTask * 0.5);
ImbFactor=0;
}
else
{
imb = 0;
ImbFactor=0;
NumPartDiff=0;
}
//NumPartDiff = (int)NumPart*ImbFactor;
MPI_Reduce(&NumPartDiff, &sumNumPartDiff, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
if (ThisTask==0)
{
NumPartDiff-= sumNumPartDiff;
- printf("--------> %d\n",sumNumPartDiff);
}
/* check */
MPI_Reduce(&NumPartDiff, &sumNumPartDiff, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
if (ThisTask==0)
if (sumNumPartDiff != 0)
{
printf("we are in trouble here...\n");
endrun(89897676);
}
DesiredNumPart = NumPart + NumPartDiff;
/* create a list */
list_DesiredNumPart= malloc(sizeof(double) * NTask);
MPI_Allgather(&DesiredNumPart, 1, MPI_INT, list_DesiredNumPart, 1, MPI_INT, MPI_COMM_WORLD);
printf("(%04d) Step=%04d Imbalance : %12g %12g %12g %12g %12d %12d %12d\n",ThisTask,All.NumCurrentTiStep,CPU_Gravity,sumCPU_Gravity/NTask, imb ,ImbFactor,NumPart,NumPartDiff,DesiredNumPart);
/************************************/
/* find the splits */
/************************************/
int task;
int domain;
/* loop over all top leaves */
for(task = 0, domain = 0; task < NTask-1; task++)
{
DomainStartList[task] = domain;
list_load[task] =0;
list_loadsph[task]=0;
while( (list_load[task]+DomainCount[domain] < list_DesiredNumPart[task]) || ((list_load[task]+DomainCount[domain] - list_DesiredNumPart[task]) < (list_DesiredNumPart[task]-list_load[task])) )
{
/* add the domain to the task */
list_load[task] += DomainCount[domain];
list_loadsph[task]+= DomainCountSph[domain];
DomainTask[domain] = task;
DomainEndList[task] = domain;
/* move to next domain */
domain++;
if (domain==NTopleaves)
{
printf("not enought domains...\n");
endrun(77665566);
}
}
}
/* now, do the last task */
task = NTask-1;
DomainStartList[task] = domain;
list_load[task] =0;
list_loadsph[task]=0;
for(domain = domain; domain < NTopleaves; domain++)
{
list_load[task] += DomainCount[domain];
list_loadsph[task]+= DomainCountSph[domain];
DomainTask[domain] = task;
DomainEndList[task] = domain;
}
free(list_DesiredNumPart);
return 0;
}
#endif
/*! This function tries to improve the domain decomposition found by
* domain_findSplit() with respect to work-load balance. To this end, the
* boundaries in the existing domain-split solution (which was found by
* trying to balance the particle load) are shifted as long as this leads
* to better work-load while still remaining within the allowed
* memory-imbalance constraints.
*/
void domain_shiftSplit(void)
{
int i, task, iter = 0, moved;
double maxw, newmaxw;
for(task = 0; task < NTask; task++)
list_work[task] = 0;
for(i = 0; i < NTopleaves; i++)
list_work[DomainTask[i]] += DomainWork[i];
if (ThisTask==0)
{
fprintf(FdLog,"1 %12g ",All.Time);
for(task = 0; task < NTask; task++)
fprintf(FdLog,"%12g ",list_work[task]);
fprintf(FdLog,"\n");
fflush(FdLog);
}
do
{
for(task = 0, moved = 0; task < NTask - 1; task++)
{
maxw = dmax(list_work[task], list_work[task + 1]);
if(list_work[task] < list_work[task + 1])
{
newmaxw = dmax(list_work[task] + DomainWork[DomainStartList[task + 1]],
list_work[task + 1] - DomainWork[DomainStartList[task + 1]]);
if(newmaxw <= maxw)
{
if(list_load[task] + DomainCount[DomainStartList[task + 1]] <= maxload)
{
if(list_loadsph[task] + DomainCountSph[DomainStartList[task + 1]] > maxloadsph)
continue;
/* ok, we can move one domain cell from right to left */
list_work[task] += DomainWork[DomainStartList[task + 1]];
list_load[task] += DomainCount[DomainStartList[task + 1]];
list_loadsph[task] += DomainCountSph[DomainStartList[task + 1]];
list_work[task + 1] -= DomainWork[DomainStartList[task + 1]];
list_load[task + 1] -= DomainCount[DomainStartList[task + 1]];
list_loadsph[task + 1] -= DomainCountSph[DomainStartList[task + 1]];
DomainTask[DomainStartList[task + 1]] = task;
DomainStartList[task + 1] += 1;
DomainEndList[task] += 1;
moved++;
}
}
}
else
{
newmaxw = dmax(list_work[task] - DomainWork[DomainEndList[task]],
list_work[task + 1] + DomainWork[DomainEndList[task]]);
if(newmaxw <= maxw)
{
if(list_load[task + 1] + DomainCount[DomainEndList[task]] <= maxload)
{
if(list_loadsph[task + 1] + DomainCountSph[DomainEndList[task]] > maxloadsph)
continue;
/* ok, we can move one domain cell from left to right */
list_work[task] -= DomainWork[DomainEndList[task]];
list_load[task] -= DomainCount[DomainEndList[task]];
list_loadsph[task] -= DomainCountSph[DomainEndList[task]];
list_work[task + 1] += DomainWork[DomainEndList[task]];
list_load[task + 1] += DomainCount[DomainEndList[task]];
list_loadsph[task + 1] += DomainCountSph[DomainEndList[task]];
DomainTask[DomainEndList[task]] = task + 1;
DomainEndList[task] -= 1;
DomainStartList[task + 1] -= 1;
moved++;
}
}
}
}
iter++;
}
while(moved > 0 && iter < 10 * NTopleaves);
if (ThisTask==0)
{
fprintf(FdLog,"2 %12g ",All.Time);
for(task = 0; task < NTask; task++)
fprintf(FdLog,"%12g ",list_work[task]);
fprintf(FdLog,"\n");
fflush(FdLog);
}
}
#ifdef SPLIT_DOMAIN_USING_TIME
/*! This function tries to improve the domain decomposition found by
* domain_findSplit() with respect to work-load balance. To this end, the
* boundaries in the existing domain-split solution (which was found by
* trying to balance the particle load) are shifted as long as this leads
* to better work-load while still remaining within the allowed
* memory-imbalance constraints.
*/
void domain_shiftSplityr(void)
{
}
#endif
/*! This function counts how many particles have to be exchanged between
* two CPUs according to the domain split. If the CPUs are already quite
* full and hold data from other CPUs as well, not all the particles may
* be exchanged at once. In this case the communication phase has to be
* repeated, until enough of the third-party particles have been moved
* away such that the decomposition can be completed.
*/
void domain_findExchangeNumbers(int task, int partner, int sphflag, int *send, int *recv)
{
int numpartA, numpartsphA, ntobesentA, maxsendA, maxsendA_old;
int numpartB, numpartsphB, ntobesentB, maxsendB, maxsendB_old;
#ifdef STELLAR_PROP
int numpartstA;
int numpartstB;
#endif
numpartA = list_NumPart[task];
numpartsphA = list_N_gas[task];
#ifdef STELLAR_PROP
numpartstA = list_N_stars[task];
#endif
numpartB = list_NumPart[partner];
numpartsphB = list_N_gas[partner];
#ifdef STELLAR_PROP
numpartstB = list_N_stars[partner];
#endif
switch (sphflag)
{
case 0:
ntobesentA = toGoSph[task * NTask + partner];
ntobesentB = toGoSph[partner * NTask + task];
break;
#ifdef STELLAR_PROP
case 1:
ntobesentA = toGoSt[task * NTask + partner];
ntobesentB = toGoSt[partner * NTask + task];
break;
#endif
default:
#ifdef STELLAR_PROP
ntobesentA = toGo[task * NTask + partner] - toGoSph[task * NTask + partner] - toGoSt[task * NTask + partner];
ntobesentB = toGo[partner * NTask + task] - toGoSph[partner * NTask + task] - toGoSt[partner * NTask + task];
#else
ntobesentA = toGo[task * NTask + partner] - toGoSph[task * NTask + partner];
ntobesentB = toGo[partner * NTask + task] - toGoSph[partner * NTask + task];
#endif
break;
}
maxsendA = imin(ntobesentA, All.BunchSizeDomain);
maxsendB = imin(ntobesentB, All.BunchSizeDomain);
do
{
maxsendA_old = maxsendA;
maxsendB_old = maxsendB;
maxsendA = imin(All.MaxPart - numpartB + maxsendB, maxsendA);
maxsendB = imin(All.MaxPart - numpartA + maxsendA, maxsendB);
}
while((maxsendA != maxsendA_old) || (maxsendB != maxsendB_old));
/* now make also sure that there is enough space for SPH particles */
switch (sphflag)
{
case 0:
do
{
maxsendA_old = maxsendA;
maxsendB_old = maxsendB;
maxsendA = imin(All.MaxPartSph - numpartsphB + maxsendB, maxsendA);
maxsendB = imin(All.MaxPartSph - numpartsphA + maxsendA, maxsendB);
}
while((maxsendA != maxsendA_old) || (maxsendB != maxsendB_old));
break;
#ifdef STELLAR_PROP
case 1:
do
{
maxsendA_old = maxsendA;
maxsendB_old = maxsendB;
maxsendA = imin(All.MaxPartStars - numpartstB + maxsendB, maxsendA);
maxsendB = imin(All.MaxPartStars - numpartstA + maxsendA, maxsendB);
}
while((maxsendA != maxsendA_old) || (maxsendB != maxsendB_old));
break;
#endif
default:
break;
}
*send = maxsendA;
*recv = maxsendB;
}
/*! This function exchanges particles between two CPUs according to the
* domain split. In doing this, the memory boundaries which may restrict
* the exhange process are observed.
*/
void domain_exchangeParticles(int partner, int sphflag, int send_count, int recv_count)
{
int i, no, n, count, rep;
MPI_Status status;
#ifdef STELLAR_PROP
int m;
#endif
for(n = 0, count = 0; count < send_count && n < NumPart; n++)
{
switch (sphflag)
{
case 0:
if(P[n].Type != 0)
continue;
break;
#ifdef STELLAR_PROP
case 1:
if(P[n].Type != 1)
continue;
break;
#endif
default:
#ifdef STELLAR_PROP
if((P[n].Type == 0)||(P[n].Type == 1))
#else
if(P[n].Type == 0)
#endif
continue;
break;
}
no = 0;
while(TopNodes[no].Daughter >= 0)
no = TopNodes[no].Daughter + (Key[n] - TopNodes[no].StartKey) / (TopNodes[no].Size / 8);
no = TopNodes[no].Leaf;
if(DomainTask[no] == partner)
{
switch (sphflag)
{
case 0: /* special reorder routine for SPH particles (need to stay at beginning) */
#ifndef STELLAR_PROP
DomainPartBuf[count] = P[n]; /* copy particle and collect in contiguous memory */
DomainKeyBuf[count] = Key[n];
DomainSphBuf[count] = SphP[n];
P[n] = P[N_gas - 1];
P[N_gas - 1] = P[NumPart - 1];
Key[n] = Key[N_gas - 1];
Key[N_gas - 1] = Key[NumPart - 1];
SphP[n] = SphP[N_gas - 1];
N_gas--;
break;
#else
DomainPartBuf[count] = P[n]; /* copy particle and collect in contiguous memory */
DomainKeyBuf[count] = Key[n];
DomainSphBuf[count] = SphP[n];
P[n] = P[N_gas - 1];
P[N_gas - 1] = P[N_gas+N_stars - 1];
P[N_gas+N_stars - 1] = P[NumPart - 1];
Key[n] = Key[N_gas - 1];
Key[N_gas - 1] = Key[N_gas+N_stars - 1];
Key[N_gas+N_stars - 1] = Key[NumPart - 1];
SphP[n] = SphP[N_gas - 1];
StP[P[N_gas - 1].StPIdx].PIdx = N_gas - 1;
N_gas--;
break;
#endif
#ifdef STELLAR_PROP
case 1:
DomainPartBuf[count] = P[n]; /* copy particle and collect in contiguous memory */
DomainKeyBuf[count] = Key[n];
DomainStBuf[count] = StP[P[n].StPIdx];
m = P[n].StPIdx;
//printf("(%d) sending P .... n=%d id=%d\n",ThisTask,n,P[n].ID);
//printf("(%d) replacing P using .... n=%d id=%d\n",ThisTask,N_gas+N_stars - 1,P[N_gas+N_stars - 1].ID);
//printf("(%d) sending Stp .... n=%d id=%d\n",ThisTask,m,StP[m].ID);
//printf("(%d) replacing StP using .... n=%d id=%d\n",ThisTask,N_stars - 1,StP[N_stars - 1].ID);
P[n] = P[N_gas+N_stars - 1];
StP[P[n].StPIdx].PIdx = n; /* create correct link */
P[N_gas+N_stars - 1] = P[NumPart - 1];
Key[n] = Key[N_gas+N_stars - 1];
Key[N_gas+N_stars - 1] = Key[NumPart - 1];
if (m!=(N_stars - 1))
{
StP[m] = StP[N_stars - 1]; /* replace by the last one -> avoid a hole in Stp */
P[StP[m].PIdx].StPIdx = m; /* create correct link */
}
N_stars--;
break;
#endif
default:
DomainPartBuf[count] = P[n]; /* copy particle and collect in contiguous memory */
DomainKeyBuf[count] = Key[n];
P[n] = P[NumPart - 1];
Key[n] = Key[NumPart - 1];
break;
}
count++;
NumPart--;
n--;
}
}
if(count != send_count)
{
printf("Houston, we got a problem... (sphflag=%d)\n",sphflag);
printf("ThisTask=%d count=%d send_count=%d\n", ThisTask, count, send_count);
endrun(88);
}
/* transmit */
for(rep = 0; rep < 2; rep++)
{
if((rep == 0 && ThisTask < partner) || (rep == 1 && ThisTask > partner))
{
if(send_count > 0)
{
MPI_Ssend(&DomainPartBuf[0], send_count * sizeof(struct particle_data), MPI_BYTE, partner,
TAG_PDATA, MPI_COMM_WORLD);
MPI_Ssend(&DomainKeyBuf[0], send_count * sizeof(peanokey), MPI_BYTE, partner, TAG_KEY,
MPI_COMM_WORLD);
if(sphflag==0)
MPI_Ssend(&DomainSphBuf[0], send_count * sizeof(struct sph_particle_data), MPI_BYTE, partner,
TAG_SPHDATA, MPI_COMM_WORLD);
#ifdef STELLAR_PROP
if(sphflag==ST)
MPI_Ssend(&DomainStBuf[0], send_count * sizeof(struct st_particle_data), MPI_BYTE, partner,
TAG_STDATA, MPI_COMM_WORLD);
#endif
}
}
if((rep == 1 && ThisTask < partner) || (rep == 0 && ThisTask > partner))
{
if(recv_count > 0)
{
switch (sphflag)
{
case 0:
#ifndef STELLAR_PROP
if((NumPart - N_gas) > recv_count)
{
for(i = 0; i < recv_count; i++)
{
P[NumPart + i] = P[N_gas + i];
Key[NumPart + i] = Key[N_gas + i];
}
}
else
{
for(i = NumPart - 1; i >= N_gas; i--)
{
P[i + recv_count] = P[i];
Key[i + recv_count] = Key[i];
}
}
#else
/* A : move elts of last block */
if((NumPart - N_gas - N_stars) > recv_count)
{
for(i = 0; i < recv_count; i++)
{
P[NumPart + i] = P[N_gas + N_stars + i];
Key[NumPart + i] = Key[N_gas + N_stars + i];
}
}
else
{
for(i = NumPart - 1; i >= N_gas + N_stars; i--)
{
P[i + recv_count] = P[i];
Key[i + recv_count] = Key[i];
}
}
/* B : move stars */
if (N_stars > 0)
{
if((N_stars) > recv_count)
{
for(i = 0; i < recv_count; i++)
{
P[N_gas + N_stars + i] = P[N_gas + i];
Key[N_gas + N_stars + i] = Key[N_gas + i];
StP[P[N_gas + N_stars + i].StPIdx].PIdx = N_gas + N_stars + i;
}
}
else
{
for(i = N_gas + N_stars - 1; i >= N_gas; i--)
{
P[i + recv_count] = P[i];
Key[i + recv_count] = Key[i];
StP[P[i + recv_count].StPIdx].PIdx = i + recv_count;
}
}
}
#endif
MPI_Recv(&P[N_gas], recv_count * sizeof(struct particle_data), MPI_BYTE, partner, TAG_PDATA,
MPI_COMM_WORLD, &status);
MPI_Recv(&Key[N_gas], recv_count * sizeof(peanokey), MPI_BYTE, partner, TAG_KEY,
MPI_COMM_WORLD, &status);
MPI_Recv(&SphP[N_gas], recv_count * sizeof(struct sph_particle_data), MPI_BYTE, partner,
TAG_SPHDATA, MPI_COMM_WORLD, &status);
N_gas += recv_count;
break;
#ifdef STELLAR_PROP
case 1:
if((NumPart - N_gas - N_stars) > recv_count)
{
for(i = 0; i < recv_count; i++)
{
P[NumPart + i] = P[N_gas + N_stars + i];
Key[NumPart + i] = Key[N_gas + N_stars + i];
}
}
else
{
for(i = NumPart - 1; i >= N_gas + N_stars; i--)
{
P[i + recv_count] = P[i];
Key[i + recv_count] = Key[i];
}
}
MPI_Recv(&P[N_gas+N_stars], recv_count * sizeof(struct particle_data), MPI_BYTE, partner, TAG_PDATA,
MPI_COMM_WORLD, &status);
MPI_Recv(&Key[N_gas+N_stars], recv_count * sizeof(peanokey), MPI_BYTE, partner, TAG_KEY,
MPI_COMM_WORLD, &status);
MPI_Recv(&StP[N_stars], recv_count * sizeof(struct st_particle_data), MPI_BYTE, partner, TAG_STDATA,
MPI_COMM_WORLD, &status);
/* set right links */
for(i = 0; i < recv_count; i++)
{
P[N_gas + N_stars + i].StPIdx = N_stars + i;
StP[N_stars + i].PIdx = N_gas + N_stars + i;
}
N_stars += recv_count;
break;
#endif
default:
MPI_Recv(&P[NumPart], recv_count * sizeof(struct particle_data), MPI_BYTE, partner,
TAG_PDATA, MPI_COMM_WORLD, &status);
MPI_Recv(&Key[NumPart], recv_count * sizeof(peanokey), MPI_BYTE, partner,
TAG_KEY, MPI_COMM_WORLD, &status);
break;
}
NumPart += recv_count;
}
}
}
}
/*! This function determines how many particles that are currently stored
* on the local CPU have to be moved off according to the domain
* decomposition.
*/
void domain_countToGo(void)
{
int n, no;
for(n = 0; n < NTask; n++)
{
local_toGo[n] = 0;
local_toGoSph[n] = 0;
#ifdef STELLAR_PROP
local_toGoSt[n] = 0;
#endif
}
for(n = 0; n < NumPart; n++)
{
no = 0;
while(TopNodes[no].Daughter >= 0)
no = TopNodes[no].Daughter + (Key[n] - TopNodes[no].StartKey) / (TopNodes[no].Size / 8);
no = TopNodes[no].Leaf;
if(DomainTask[no] != ThisTask)
{
local_toGo[DomainTask[no]] += 1;
if(P[n].Type == 0)
local_toGoSph[DomainTask[no]] += 1;
#ifdef STELLAR_PROP
if(P[n].Type == 1)
local_toGoSt[DomainTask[no]] += 1;
#endif
}
}
MPI_Allgather(local_toGo, NTask, MPI_INT, toGo, NTask, MPI_INT, MPI_COMM_WORLD);
MPI_Allgather(local_toGoSph, NTask, MPI_INT, toGoSph, NTask, MPI_INT, MPI_COMM_WORLD);
#ifdef STELLAR_PROP
MPI_Allgather(local_toGoSt, NTask, MPI_INT, toGoSt, NTask, MPI_INT, MPI_COMM_WORLD);
#endif
}
/*! This function walks the global top tree in order to establish the
* number of leaves it has. These leaves are distributed to different
* processors.
*/
void domain_walktoptree(int no)
{
int i;
if(TopNodes[no].Daughter == -1)
{
TopNodes[no].Leaf = NTopleaves;
NTopleaves++;
}
else
{
for(i = 0; i < 8; i++)
domain_walktoptree(TopNodes[no].Daughter + i);
}
}
/*! This routine bins the particles onto the domain-grid, i.e. it sums up the
* total number of particles and the total amount of work in each of the
* domain-cells. This information forms the basis for the actual decision on
* the adopted domain decomposition.
*/
void domain_sumCost(void)
{
int i, n, no;
double *local_DomainWork;
int *local_DomainCount;
int *local_DomainCountSph;
local_DomainWork = malloc(NTopnodes * sizeof(double));
local_DomainCount = malloc(NTopnodes * sizeof(int));
local_DomainCountSph = malloc(NTopnodes * sizeof(int));
NTopleaves = 0;
domain_walktoptree(0);
for(i = 0; i < NTopleaves; i++)
{
local_DomainWork[i] = 0;
local_DomainCount[i] = 0;
local_DomainCountSph[i] = 0;
}
if(ThisTask == 0)
printf("NTopleaves= %d\n", NTopleaves);
for(n = 0; n < NumPart; n++)
{
no = 0;
while(TopNodes[no].Daughter >= 0)
no = TopNodes[no].Daughter + (Key[n] - TopNodes[no].StartKey) / (TopNodes[no].Size / 8);
no = TopNodes[no].Leaf;
if(P[n].Ti_endstep > P[n].Ti_begstep)
local_DomainWork[no] += (1.0 + P[n].GravCost) / (P[n].Ti_endstep - P[n].Ti_begstep);
else
local_DomainWork[no] += (1.0 + P[n].GravCost);
local_DomainCount[no] += 1;
if(P[n].Type == 0)
local_DomainCountSph[no] += 1;
}
MPI_Allreduce(local_DomainWork, DomainWork, NTopleaves, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(local_DomainCount, DomainCount, NTopleaves, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(local_DomainCountSph, DomainCountSph, NTopleaves, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
free(local_DomainCountSph);
free(local_DomainCount);
free(local_DomainWork);
}
/*! This routine finds the extent of the global domain grid.
*/
void domain_findExtent(void)
{
int i, j;
double len, xmin[3], xmax[3], xmin_glob[3], xmax_glob[3];
/* determine local extension */
for(j = 0; j < 3; j++)
{
xmin[j] = MAX_REAL_NUMBER;
xmax[j] = -MAX_REAL_NUMBER;
}
for(i = 0; i < NumPart; i++)
{
for(j = 0; j < 3; j++)
{
if(xmin[j] > P[i].Pos[j])
xmin[j] = P[i].Pos[j];
if(xmax[j] < P[i].Pos[j])
xmax[j] = P[i].Pos[j];
}
}
MPI_Allreduce(xmin, xmin_glob, 3, MPI_DOUBLE, MPI_MIN, MPI_COMM_WORLD);
MPI_Allreduce(xmax, xmax_glob, 3, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);
len = 0;
for(j = 0; j < 3; j++)
if(xmax_glob[j] - xmin_glob[j] > len)
len = xmax_glob[j] - xmin_glob[j];
len *= 1.001;
#ifdef DOMAIN_AT_ORIGIN
for(j = 0; j < 3; j++)
{
DomainCenter[j] = 0.0;
DomainCorner[j] = - 0.5 * len;
}
#else
for(j = 0; j < 3; j++)
{
DomainCenter[j] = 0.5 * (xmin_glob[j] + xmax_glob[j]);
DomainCorner[j] = 0.5 * (xmin_glob[j] + xmax_glob[j]) - 0.5 * len;
}
#endif
DomainLen = len;
DomainFac = 1.0 / len * (((peanokey) 1) << (BITS_PER_DIMENSION));
#ifdef OTHERINFO
if(ThisTask == 0)
{
printf("xmin_glob = %g %g %g\n",xmin_glob[0],xmin_glob[1],xmin_glob[2]);
printf("xmax_glob = %g %g %g\n",xmax_glob[0],xmax_glob[1],xmax_glob[2]);
printf("DomainCenter = %g %g %g\n",DomainCenter[0], DomainCenter[1], DomainCenter[2]);
printf("DomainCorner = %g %g %g\n",DomainCorner[0], DomainCorner[1], DomainCorner[2]);
printf("DomainLen = %g\n",DomainLen);
}
#endif
}
/*! This function constructs the global top-level tree node that is used
* for the domain decomposition. This is done by considering the string of
* Peano-Hilbert keys for all particles, which is recursively chopped off
* in pieces of eight segments until each segment holds at most a certain
* number of particles.
*/
void domain_determineTopTree(void)
{
int i, ntop_local, ntop;
int *ntopnodelist, *ntopoffset;
for(i = 0; i < NumPart; i++)
{
KeySorted[i] = Key[i] = peano_hilbert_key((P[i].Pos[0] - DomainCorner[0]) * DomainFac,
(P[i].Pos[1] - DomainCorner[1]) * DomainFac,
(P[i].Pos[2] - DomainCorner[2]) * DomainFac,
BITS_PER_DIMENSION);
}
qsort(KeySorted, NumPart, sizeof(peanokey), domain_compare_key);
NTopnodes = 1;
TopNodes[0].Daughter = -1;
TopNodes[0].Size = PEANOCELLS;
TopNodes[0].StartKey = 0;
TopNodes[0].Count = NumPart;
TopNodes[0].Pstart = 0;
domain_topsplit_local(0, 0);
toplist_local = malloc(NTopnodes * sizeof(struct topnode_exchange));
for(i = 0, ntop_local = 0; i < NTopnodes; i++)
{
if(TopNodes[i].Daughter == -1) /* only use leaves */
{
toplist_local[ntop_local].Startkey = TopNodes[i].StartKey;
toplist_local[ntop_local].Count = TopNodes[i].Count;
ntop_local++;
}
}
ntopnodelist = malloc(sizeof(int) * NTask);
ntopoffset = malloc(sizeof(int) * NTask);
MPI_Allgather(&ntop_local, 1, MPI_INT, ntopnodelist, 1, MPI_INT, MPI_COMM_WORLD);
for(i = 0, ntop = 0, ntopoffset[0] = 0; i < NTask; i++)
{
ntop += ntopnodelist[i];
if(i > 0)
ntopoffset[i] = ntopoffset[i - 1] + ntopnodelist[i - 1];
}
toplist = malloc(ntop * sizeof(struct topnode_exchange));
for(i = 0; i < NTask; i++)
{
ntopnodelist[i] *= sizeof(struct topnode_exchange);
ntopoffset[i] *= sizeof(struct topnode_exchange);
}
MPI_Allgatherv(toplist_local, ntop_local * sizeof(struct topnode_exchange), MPI_BYTE,
toplist, ntopnodelist, ntopoffset, MPI_BYTE, MPI_COMM_WORLD);
qsort(toplist, ntop, sizeof(struct topnode_exchange), domain_compare_toplist);
NTopnodes = 1;
TopNodes[0].Daughter = -1;
TopNodes[0].Size = PEANOCELLS;
TopNodes[0].StartKey = 0;
TopNodes[0].Count = All.TotNumPart;
TopNodes[0].Pstart = 0;
TopNodes[0].Blocks = ntop;
domain_topsplit(0, 0);
free(toplist);
free(ntopoffset);
free(ntopnodelist);
free(toplist_local);
}
/*! This function is responsible for constructing the local top-level
* Peano-Hilbert segments. A segment is cut into 8 pieces recursively
* until the number of particles in the segment has fallen below
* All.TotNumPart / (TOPNODEFACTOR * NTask * NTask).
*/
void domain_topsplit_local(int node, peanokey startkey)
{
int i, p, sub, bin;
if(TopNodes[node].Size >= 8)
{
TopNodes[node].Daughter = NTopnodes;
for(i = 0; i < 8; i++)
{
if(NTopnodes < MAXTOPNODES)
{
sub = TopNodes[node].Daughter + i;
TopNodes[sub].Size = TopNodes[node].Size / 8;
TopNodes[sub].Count = 0;
TopNodes[sub].Daughter = -1;
TopNodes[sub].StartKey = startkey + i * TopNodes[sub].Size;
TopNodes[sub].Pstart = TopNodes[node].Pstart;
NTopnodes++;
}
else
{
printf("task=%d: We are out of Topnodes. Increasing the constant MAXTOPNODES might help.\n",
ThisTask);
fflush(stdout);
endrun(13213);
}
}
for(p = TopNodes[node].Pstart; p < TopNodes[node].Pstart + TopNodes[node].Count; p++)
{
bin = (KeySorted[p] - startkey) / (TopNodes[node].Size / 8);
if(bin < 0 || bin > 7)
{
printf("task=%d: something odd has happened here. bin=%d\n", ThisTask, bin);
fflush(stdout);
endrun(13123123);
}
sub = TopNodes[node].Daughter + bin;
if(TopNodes[sub].Count == 0)
TopNodes[sub].Pstart = p;
TopNodes[sub].Count++;
}
for(i = 0; i < 8; i++)
{
sub = TopNodes[node].Daughter + i;
//if(TopNodes[sub].Count > All.TotNumPart / (TOPNODEFACTOR * NTask * NTask))
if(TopNodes[sub].Count > All.TotNumPart / (TOPNODEFACTOR * NTask))
domain_topsplit_local(sub, TopNodes[sub].StartKey);
}
}
}
/*! This function is responsible for constructing the global top-level tree
* segments. Starting from a joint list of all local top-level segments,
* in which mulitple occurences of the same spatial segment have been
* combined, a segment is subdivided into 8 pieces recursively until the
* number of particles in each segment has fallen below All.TotNumPart /
* (TOPNODEFACTOR * NTask).
*/
void domain_topsplit(int node, peanokey startkey)
{
int i, p, sub, bin;
if(TopNodes[node].Size >= 8)
{
TopNodes[node].Daughter = NTopnodes;
for(i = 0; i < 8; i++)
{
if(NTopnodes < MAXTOPNODES)
{
sub = TopNodes[node].Daughter + i;
TopNodes[sub].Size = TopNodes[node].Size / 8;
TopNodes[sub].Count = 0;
TopNodes[sub].Blocks = 0;
TopNodes[sub].Daughter = -1;
TopNodes[sub].StartKey = startkey + i * TopNodes[sub].Size;
TopNodes[sub].Pstart = TopNodes[node].Pstart;
NTopnodes++;
}
else
{
printf("Task=%d: We are out of Topnodes. Increasing the constant MAXTOPNODES might help.\n",
ThisTask);
fflush(stdout);
endrun(137213);
}
}
for(p = TopNodes[node].Pstart; p < TopNodes[node].Pstart + TopNodes[node].Blocks; p++)
{
bin = (toplist[p].Startkey - startkey) / (TopNodes[node].Size / 8);
sub = TopNodes[node].Daughter + bin;
if(bin < 0 || bin > 7)
endrun(77);
if(TopNodes[sub].Blocks == 0)
TopNodes[sub].Pstart = p;
TopNodes[sub].Count += toplist[p].Count;
TopNodes[sub].Blocks++;
}
for(i = 0; i < 8; i++)
{
sub = TopNodes[node].Daughter + i;
if(TopNodes[sub].Count > All.TotNumPart / (TOPNODEFACTOR * NTask))
domain_topsplit(sub, TopNodes[sub].StartKey);
}
}
}
/*! This is a comparison kernel used in a sort routine.
*/
int domain_compare_toplist(const void *a, const void *b)
{
if(((struct topnode_exchange *) a)->Startkey < (((struct topnode_exchange *) b)->Startkey))
return -1;
if(((struct topnode_exchange *) a)->Startkey > (((struct topnode_exchange *) b)->Startkey))
return +1;
return 0;
}
/*! This is a comparison kernel used in a sort routine.
*/
int domain_compare_key(const void *a, const void *b)
{
if(*(peanokey *) a < *(peanokey *) b)
return -1;
if(*(peanokey *) a > *(peanokey *) b)
return +1;
return 0;
}

Event Timeline