Page MenuHomec4science

No OneTemporary

File Metadata

Created
Tue, Dec 3, 03:38
This file is larger than 256 KB, so syntax highlighting was skipped.
diff --git a/src/allocate.c b/src/allocate.c
index 01354e0..f3c0fd9 100644
--- a/src/allocate.c
+++ b/src/allocate.c
@@ -1,286 +1,291 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "allvars.h"
#include "proto.h"
/*! \file allocate.c
* \brief routines for allocating particle and tree storage
*/
/*! Allocates a number of small buffers and arrays, the largest one being
* the communication buffer. The communication buffer itself is mapped
* onto various tables used in the different parts of the force
* algorithms. We further allocate space for the top-level tree nodes, and
* auxiliary arrays for the domain decomposition algorithm.
*/
void allocate_commbuffers(void)
{
size_t bytes;
Exportflag = malloc(NTask * sizeof(char));
DomainStartList = malloc(NTask * sizeof(int));
DomainEndList = malloc(NTask * sizeof(int));
TopNodes = malloc(MAXTOPNODES * sizeof(struct topnode_data));
DomainWork = malloc(MAXTOPNODES * sizeof(double));
DomainCount = malloc(MAXTOPNODES * sizeof(int));
DomainCountSph = malloc(MAXTOPNODES * sizeof(int));
DomainTask = malloc(MAXTOPNODES * sizeof(int));
DomainNodeIndex = malloc(MAXTOPNODES * sizeof(int));
DomainTreeNodeLen = malloc(MAXTOPNODES * sizeof(FLOAT));
DomainHmax = malloc(MAXTOPNODES * sizeof(FLOAT));
DomainMoment = malloc(MAXTOPNODES * sizeof(struct DomainNODE));
if(!(CommBuffer = malloc(bytes = All.BufferSize * 1024 * 1024)))
{
printf("failed to allocate memory for `CommBuffer' (%g MB).\n", bytes / (1024.0 * 1024.0));
endrun(2);
}
All.BunchSizeForce =
(All.BufferSize * 1024 * 1024) / (sizeof(struct gravdata_index) + 2 * sizeof(struct gravdata_in));
if(All.BunchSizeForce & 1)
All.BunchSizeForce -= 1; /* make sure that All.BunchSizeForce is an even number
--> 8-byte alignment for 64bit processors */
GravDataIndexTable = (struct gravdata_index *) CommBuffer;
GravDataIn = (struct gravdata_in *) (GravDataIndexTable + All.BunchSizeForce);
GravDataGet = GravDataIn + All.BunchSizeForce;
GravDataOut = GravDataIn; /* this will overwrite the GravDataIn-Table */
GravDataResult = GravDataGet; /* this will overwrite the GravDataGet-Table */
All.BunchSizeDensity =
(All.BufferSize * 1024 * 1024) / (2 * sizeof(struct densdata_in) + 2 * sizeof(struct densdata_out));
DensDataIn = (struct densdata_in *) CommBuffer;
DensDataGet = DensDataIn + All.BunchSizeDensity;
DensDataResult = (struct densdata_out *) (DensDataGet + All.BunchSizeDensity);
DensDataPartialResult = DensDataResult + All.BunchSizeDensity;
All.BunchSizeHydro =
(All.BufferSize * 1024 * 1024) / (2 * sizeof(struct hydrodata_in) + 2 * sizeof(struct hydrodata_out));
HydroDataIn = (struct hydrodata_in *) CommBuffer;
HydroDataGet = HydroDataIn + All.BunchSizeHydro;
HydroDataResult = (struct hydrodata_out *) (HydroDataGet + All.BunchSizeHydro);
HydroDataPartialResult = HydroDataResult + All.BunchSizeHydro;
#ifdef PY_INTERFACE
All.BunchSizeSph =
(All.BufferSize * 1024 * 1024) / (2 * sizeof(struct sphdata_in) + 2 * sizeof(struct sphdata_out));
SphDataIn = (struct sphdata_in *) CommBuffer;
SphDataGet = SphDataIn + All.BunchSizeSph;
SphDataResult = (struct sphdata_out *) (SphDataGet + All.BunchSizeSph);
SphDataPartialResult = SphDataResult + All.BunchSizeSph;
All.BunchSizeDensitySph =
(All.BufferSize * 1024 * 1024) / (2 * sizeof(struct denssphdata_in) + 2 * sizeof(struct denssphdata_out));
DensSphDataIn = (struct denssphdata_in *) CommBuffer;
DensSphDataGet = DensSphDataIn + All.BunchSizeDensitySph;
DensSphDataResult = (struct denssphdata_out *) (DensSphDataGet + All.BunchSizeDensitySph);
DensSphDataPartialResult = DensSphDataResult + All.BunchSizeDensitySph;
#endif
#ifdef MULTIPHASE
All.BunchSizeSticky =
(All.BufferSize * 1024 * 1024) / (2 * sizeof(struct stickydata_in) + 2 * sizeof(struct stickydata_out));
StickyDataIn = (struct stickydata_in *) CommBuffer;
StickyDataGet = StickyDataIn + All.BunchSizeSticky;
StickyDataResult = (struct stickydata_out *) (StickyDataGet + All.BunchSizeSticky);
StickyDataPartialResult = StickyDataResult + All.BunchSizeSticky;
#endif
#ifdef CHIMIE
All.BunchSizeChimie =
(All.BufferSize * 1024 * 1024) / (2 * sizeof(struct chimiedata_in) + 2 * sizeof(struct chimiedata_out));
ChimieDataIn = (struct chimiedata_in *) CommBuffer;
ChimieDataGet = ChimieDataIn + All.BunchSizeChimie;
ChimieDataResult = (struct chimiedata_out *) (ChimieDataGet + All.BunchSizeChimie);
ChimieDataPartialResult = ChimieDataResult + All.BunchSizeChimie;
All.BunchSizeStarsDensity =
(All.BufferSize * 1024 * 1024) / (2 * sizeof(struct starsdensdata_in) + 2 * sizeof(struct starsdensdata_out));
StarsDensDataIn = (struct starsdensdata_in *) CommBuffer;
StarsDensDataGet = StarsDensDataIn + All.BunchSizeStarsDensity;
StarsDensDataResult = (struct starsdensdata_out *) (StarsDensDataGet + All.BunchSizeStarsDensity);
StarsDensDataPartialResult = StarsDensDataResult + All.BunchSizeStarsDensity;
#endif
#ifdef DISSIPATION_FORCES
All.BunchSizeDissipationForces =
(All.BufferSize * 1024 * 1024) / (2 * sizeof(struct dissipationforcesdata_in) + 2 * sizeof(struct dissipationforcesdata_out));
DissipationForcesDataIn = (struct dissipationforcesdata_in *) CommBuffer;
DissipationForcesDataGet = DissipationForcesDataIn + All.BunchSizeDissipationForces;
DissipationForcesDataResult = (struct dissipationforcesdata_out *) (DissipationForcesDataGet + All.BunchSizeDissipationForces);
DissipationForcesDataPartialResult = DissipationForcesDataResult + All.BunchSizeDissipationForces;
#endif
#ifdef FOF
All.BunchSizeFOF =
(All.BufferSize * 1024 * 1024) / (2 * sizeof(struct FOFdata_in) + 2 * sizeof(struct FOFdata_out));
FOFDataIn = (struct FOFdata_in *) CommBuffer;
FOFDataGet = FOFDataIn + All.BunchSizeFOF;
FOFDataResult = (struct FOFdata_out *) (FOFDataGet + All.BunchSizeFOF);
FOFDataPartialResult = FOFDataResult + All.BunchSizeFOF;
#endif
#ifdef STELLAR_PROP
All.BunchSizeDomain =
(All.BufferSize * 1024 * 1024) / (sizeof(struct particle_data) + sizeof(struct sph_particle_data) +
sizeof(struct st_particle_data) + sizeof(peanokey));
#else
All.BunchSizeDomain =
(All.BufferSize * 1024 * 1024) / (sizeof(struct particle_data) + sizeof(struct sph_particle_data) +
sizeof(peanokey));
#endif
if(All.BunchSizeDomain & 1)
All.BunchSizeDomain -= 1; /* make sure that All.BunchSizeDomain is even
--> 8-byte alignment of DomainKeyBuf for 64bit processors */
DomainPartBuf = (struct particle_data *) CommBuffer;
DomainSphBuf = (struct sph_particle_data *) (DomainPartBuf + All.BunchSizeDomain);
DomainKeyBuf = (peanokey *) (DomainSphBuf + All.BunchSizeDomain);
#ifdef STELLAR_PROP
DomainStBuf = (struct st_particle_data *) (DomainKeyBuf + All.BunchSizeDomain);
#endif
#ifdef SYNCHRONIZE_NGB_TIMESTEP
All.BunchSizeSynchronizeNgBTimestep =
(All.BufferSize * 1024 * 1024) / (2 * sizeof(struct SynchroinzeNgbTimestepdata_in));
SynchroinzeNgbTimestepDataIn = (struct SynchroinzeNgbTimestepdata_in *) CommBuffer;
SynchroinzeNgbTimestepDataGet = SynchroinzeNgbTimestepDataIn + All.BunchSizeSynchronizeNgBTimestep;
#endif
#ifdef TESSEL
All.BunchSizeGhost =
(All.BufferSize * 1024 * 1024) / (2 * sizeof(struct ghostdata_in) + 2 * sizeof(struct ghostdata_out));
#endif
if(ThisTask == 0)
{
printf("\nAllocated %d MByte communication buffer per processor.\n\n", All.BufferSize);
printf("Communication buffer has room for %d particles in gravity computation\n", All.BunchSizeForce);
printf("Communication buffer has room for %d particles in density computation\n", All.BunchSizeDensity);
printf("Communication buffer has room for %d particles in hydro computation\n", All.BunchSizeHydro);
printf("Communication buffer has room for %d particles in domain decomposition\n", All.BunchSizeDomain);
printf("\n");
}
}
/*! This routine allocates memory for particle storage, both the
* collisionless and the SPH particles.
*/
void allocate_memory(void)
{
size_t bytes;
double bytes_tot = 0;
if(All.MaxPart > 0)
{
if(!(P = malloc(bytes = All.MaxPart * sizeof(struct particle_data))))
{
printf("failed to allocate memory for `P' (%g MB).\n", bytes / (1024.0 * 1024.0));
endrun(1);
}
bytes_tot += bytes;
if(ThisTask == 0)
printf("\nAllocated %g MByte for particle storage. %d\n\n", bytes_tot / (1024.0 * 1024.0), sizeof(struct particle_data));
}
if(All.MaxPartSph > 0)
{
bytes_tot = 0;
if(!(SphP = malloc(bytes = All.MaxPartSph * sizeof(struct sph_particle_data))))
{
printf("failed to allocate memory for `SphP' (%g MB) %d.\n", bytes / (1024.0 * 1024.0), sizeof(struct sph_particle_data));
endrun(1);
}
bytes_tot += bytes;
if(ThisTask == 0)
printf("Allocated %g MByte for storage of SPH data. %d\n", bytes_tot / (1024.0 * 1024.0), sizeof(struct sph_particle_data));
}
#ifdef STELLAR_PROP
if(All.MaxPartStars > 0)
{
bytes_tot = 0;
if(!(StP = malloc(bytes = All.MaxPartStars * sizeof(struct st_particle_data))))
{
printf("failed to allocate memory for `StP' (%g MB) %d.\n", bytes / (1024.0 * 1024.0),sizeof(struct st_particle_data));
endrun(1);
}
bytes_tot += bytes;
if(ThisTask == 0)
printf("\nAllocated %g MByte for star properties storage. %d\n\n", bytes_tot / (1024.0 * 1024.0), sizeof(struct st_particle_data));
}
#endif
}
/*! This routine frees the memory for the particle storage. Note: We don't
* actually bother to call it in the code... When the program terminats,
* the memory will be automatically freed by the operating system.
*/
void free_memory(void)
{
#ifdef GAS_ACCRETION
if(N_gas_acc > 0)
free(SphAcc);
if(NumPart_acc > 0)
free(Acc);
#endif
+#ifdef HOT_HALO
+ if(NumPart_HaloAcc > 0)
+ free(HaloAcc);
+#endif
+
#ifdef STELLAR_PROP
if(All.MaxPartStars > 0)
free(StP);
#endif
if(All.MaxPartSph > 0)
free(SphP);
if(All.MaxPart > 0)
free(P);
#ifdef COOLING_FCT_FROM_HDF5
freeMemory();
#endif
}
diff --git a/src/allvars.c b/src/allvars.c
index 779c8e8..e4308dc 100644
--- a/src/allvars.c
+++ b/src/allvars.c
@@ -1,535 +1,563 @@
/*! \file allvars.c
* \brief provides instances of all global variables.
*/
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include "tags.h"
#include "allvars.h"
#ifdef CHIMIE
int FE=0;
int METALS=0;
#endif
int SetMinTimeStepForActives=0;
int ThisTask; /*!< the rank of the local processor */
int NTask; /*!< number of processors */
int PTask; /*!< smallest integer such that NTask <= 2^PTask */
int NumPart; /*!< number of particles on the LOCAL processor */
int N_gas; /*!< number of gas particles on the LOCAL processor */
#if defined(SFR) || defined(STELLAR_PROP)
int N_stars; /*!< number of stars particle on the LOCAL processor */
#endif
#ifdef MULTIPHASE
int N_sph;
int N_sticky;
int N_stickyflaged;
int N_dark;
int NumColPotLocal; /*!< local number of potentially collisional particles */
int NumColPot; /*!< total number of potentially collisional particles */
int NumColLocal; /*!< local number of collisions */
int NumCol; /*!< total number of collisions */
int NumNoColLocal;
int NumNoCol;
#endif
#ifdef GAS_ACCRETION
int NumPart_acc;
int N_gas_acc;
#ifdef STELLAR_PROP
int N_stars_acc;
#endif
#endif
+#ifdef HOT_HALO
+int NumPart_HaloAcc;
+#endif
+
long long Ntype[6]; /*!< total number of particles of each type */
int NtypeLocal[6]; /*!< local number of particles of each type */
int NumForceUpdate; /*!< number of active particles on local processor in current timestep */
int NumSphUpdate; /*!< number of active SPH particles on local processor in current timestep */
#ifdef CHIMIE
int NumStUpdate;
#endif
#ifdef TESSEL
int NumPTUpdate;
#endif
double CPUThisRun; /*!< Sums the CPU time for the process (current submission only) */
#ifdef SPLIT_DOMAIN_USING_TIME
double CPU_Gravity;
#endif
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. */
char *Exportflag; /*!< Buffer used for flagging whether a particle needs to be exported to another process */
int *Ngblist; /*!< Buffer to hold indices of neighbours retrieved by the neighbour search routines */
int TreeReconstructFlag; /*!< Signals that a new tree needs to be constructed */
#ifdef SFR
int RearrangeParticlesFlag;/*!< Signals that particles must be rearanged */
#endif
int Flag_FullStep; /*!< This flag signals that the current step involves all particles */
gsl_rng *random_generator; /*!< the employed random number generator of the GSL library */
double RndTable[RNDTABLE]; /*!< Hold a table with random numbers, refreshed every timestep */
#ifdef SFR
double StarFormationRndTable[RNDTABLE]; /*!< Hold a table with random numbers, refreshed every timestep */
#endif
#ifdef FEEDBACK_WIND
double FeedbackWindRndTable[RNDTABLE]; /*!< Hold a table with random numbers, refreshed every timestep */
#endif
#ifdef CHIMIE
double ChimieRndTable[RNDTABLE]; /*!< Hold a table with random numbers, refreshed every timestep */
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
double ChimieKineticFeedbackRndTable[RNDTABLE]; /*!< Hold a table with random numbers, refreshed every timestep */
#endif
#ifdef GAS_ACCRETION
double gasAccretionRndTable[RNDTABLE]; /*!< Hold a table with random numbers, refreshed every timestep */
#endif
+#ifdef HOT_HALO
+double HaloRndTable[RNDTABLE]; /*!< Hold a table with random numbers, refreshed every timestep */
+#endif
+
#ifdef AB_TURB
//Ornstein-Uhlenbeck variables
double StOUVar;
double* StOUPhases;
gsl_rng* StRng;
//forcing field in fourie space
double* StAmpl;
double* StAka; //phases (real part)
double* StAkb; //phases (imag part)
double* StMode;
int StNModes;
//integertime StTPrev; (yr : ask ?)
int StTPrev;
double StSolWeightNorm;
#endif
#ifdef PY_INTERFACE
int NumPartQ;
int N_gasQ;
long long NtypeQ[6]; /*!< total number of particles of each type */
int NtypeLocalQ[6]; /*!< local number of particles of each type */
double DomainCornerQ[3]; /*!< gives the lower left corner of simulation volume */
double DomainCenterQ[3]; /*!< gives the center of simulation volume */
double DomainLenQ; /*!< gives the (maximum) side-length of simulation volume */
double DomainFacQ; /*!< factor used for converting particle coordinates to a Peano-Hilbert mesh covering the simulation volume */
int DomainMyStartQ; /*!< first domain mesh cell that resides on the local processor */
int DomainMyLastQ; /*!< last domain mesh cell that resides on the local processor */
int *DomainStartListQ; /*!< a table that lists the first domain mesh cell for all processors */
int *DomainEndListQ; /*!< a table that lists the last domain mesh cell for all processors */
double *DomainWorkQ; /*!< a table that gives the total "work" due to the particles stored by each processor */
int *DomainCountQ; /*!< a table that gives the total number of particles held by each processor */
int *DomainCountSphQ; /*!< a table that gives the total number of SPH particles held by each processor */
int *DomainTaskQ; /*!< this table gives for each leaf of the top-level tree the processor it was assigned to */
peanokey *DomainKeyBufQ; /*!< this points to a buffer used during the exchange of particle data */
int NTopnodesQ; /*!< total number of nodes in top-level tree */
int NTopleavesQ; /*!< number of leaves in top-level tree. Each leaf can be assigned to a different processor */
void *CommBufferQ; /*!< points to communication buffer, which is used in the domain decomposition, the
parallel tree-force computation, the SPH routines, etc. */
int NTopnodesQ; /*!< total number of nodes in top-level tree */
int NTopleavesQ; /*!< number of leaves in top-level tree. Each leaf can be assigned to a different processor */
#endif
double DomainCorner[3]; /*!< gives the lower left corner of simulation volume */
double DomainCenter[3]; /*!< gives the center of simulation volume */
double DomainLen; /*!< gives the (maximum) side-length of simulation volume */
double DomainFac; /*!< factor used for converting particle coordinates to a Peano-Hilbert mesh covering the simulation volume */
int DomainMyStart; /*!< first domain mesh cell that resides on the local processor */
int DomainMyLast; /*!< last domain mesh cell that resides on the local processor */
int *DomainStartList; /*!< a table that lists the first domain mesh cell for all processors */
int *DomainEndList; /*!< a table that lists the last domain mesh cell for all processors */
double *DomainWork; /*!< a table that gives the total "work" due to the particles stored by each processor */
int *DomainCount; /*!< a table that gives the total number of particles held by each processor */
int *DomainCountSph; /*!< a table that gives the total number of SPH particles held by each processor */
int *DomainTask; /*!< this table gives for each leaf of the top-level tree the processor it was assigned to */
int *DomainNodeIndex; /*!< this table gives for each leaf of the top-level tree the corresponding node of the gravitational tree */
FLOAT *DomainTreeNodeLen; /*!< this table gives for each leaf of the top-level tree the side-length of the corresponding node of the gravitational tree */
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 */
struct DomainNODE
*DomainMoment; /*!< this table stores for each node of the top-level tree corresponding node data from the gravitational tree */
peanokey *DomainKeyBuf; /*!< this points to a buffer used during the exchange of particle data */
peanokey *Key; /*!< a table used for storing Peano-Hilbert keys for particles */
peanokey *KeySorted; /*!< holds a sorted table of Peano-Hilbert keys for all particles, used to construct top-level tree */
int NTopnodes; /*!< total number of nodes in top-level tree */
int NTopleaves; /*!< number of leaves in top-level tree. Each leaf can be assigned to a different processor */
struct topnode_data
*TopNodes; /*!< points to the root node of the top-level tree */
#ifdef PY_INTERFACE
struct topnode_data
*TopNodesQ; /*!< points to the root node of the top-level tree */
#endif
double TimeOfLastTreeConstruction; /*!< holds what it says, only used in connection with FORCETEST */
/* variables for input/output, usually only used on process 0 */
char ParameterFile[MAXLEN_FILENAME]; /*!< file name of parameterfile used for starting the simulation */
FILE *FdInfo; /*!< file handle for info.txt log-file. */
FILE *FdLog ; /*!< file handle for log.txt log-file. */
FILE *FdEnergy; /*!< file handle for energy.txt log-file. */
#ifdef SYSTEMSTATISTICS
FILE *FdSystem;
#endif
FILE *FdTimings; /*!< file handle for timings.txt log-file. */
FILE *FdCPU; /*!< file handle for cpu.txt log-file. */
#ifdef FORCETEST
FILE *FdForceTest; /*!< file handle for forcetest.txt log-file. */
#endif
#ifdef SFR
FILE *FdSfr; /*!< file handle for sfr.txt log-file. */
#endif
#ifdef CHIMIE
FILE *FdChimie; /*!< file handle for chimie log-file. */
#ifdef CHIMIE_STATS
FILE *FdChimieStatsSNs; /*!< file handle for chimie stats-file. */
FILE *FdChimieStatsGas; /*!< file handle for chimie stats-file. */
#endif
#endif
#ifdef MULTIPHASE
FILE *FdPhase; /*!< file handle for phase.txt log-file. */
FILE *FdSticky; /*!< file handle for sticky.txt log-file. */
#endif
#ifdef AGN_ACCRETION
FILE *FdAccretion; /*!< file handle for accretion.txt log-file. */
#endif
#ifdef BONDI_ACCRETION
FILE *FdBondi; /*!< file handle for bondi.txt log-file. */
#endif
#ifdef BUBBLES
FILE *FdBubble; /*!< file handle for bubble.txt log-file. */
#endif
#ifdef GAS_ACCRETION
FILE *FdGasAccretion; /*!< file handle for gas_accretion.txt log-file. */
#endif
+#ifdef PERIODICOUTER
+FILE *FdTrace; /*!< file handle for trace.txt log-file. */
+#endif
+
double DriftTable[DRIFT_TABLE_LENGTH]; /*!< table for the cosmological drift factors */
double GravKickTable[DRIFT_TABLE_LENGTH]; /*!< table for the cosmological kick factor for gravitational forces */
double HydroKickTable[DRIFT_TABLE_LENGTH]; /*!< table for the cosmological kick factor for hydrodynmical forces */
#ifdef COSMICTIME
double CosmicTimeTable[COSMICTIME_TABLE_LENGTH]; /*!< table for the computation of cosmic time */
double FullCosmicTimeTable[COSMICTIME_TABLE_LENGTH]; /*!< table for the computation of cosmic time */
double FullCosmicTimeTableInv[COSMICTIME_TABLE_LENGTH]; /*!< table for the computation of cosmic time */
#endif
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.
*/
struct global_data_all_processes
All;
/*! This structure holds all the information that is
* stored for each particle of the simulation.
*/
struct particle_data
*P, /*!< holds particle data on local processor */
*DomainPartBuf; /*!< buffer for particle data used in domain decomposition */
#ifdef PY_INTERFACE
struct particle_data
*Q, /*!< holds particle data on local processor */
*DomainPartBufQ; /*!< buffer for particle data used in domain decomposition */
#endif
/* the following struture holds data that is stored for each SPH particle in addition to the collisionless
* variables.
*/
struct sph_particle_data
*SphP, /*!< holds SPH particle data on local processor */
*DomainSphBuf; /*!< buffer for SPH particle data in domain decomposition */
#ifdef FOF
struct fof_particles_in
*FoF_P,*FoF_P_local;
struct fof_groups_data
*Groups,*GroupsGet,*GroupsRecv;
int *Tot_HeadID_list;
int Tot_Ngroups;
int Tot_Ntgroups;
int Tot_Npgroups;
int Tot_Ntsfrgroups;
int Ngroups; /* true and pseudo groups */
int Ntgroups; /* true groups */
int Npgroups; /* pseudo groups */
int Ntsfrgroups; /* true groups that forms stars */
int Nsfrgroups; /* local number of groups flagged for sfr */
int Tot_Nsfrgroups; /* total number of groups flagged for sfr */
#endif
#ifdef GAS_ACCRETION
struct acc_particle_data
*Acc;
struct gas_acc_particle_data
*SphAcc;
#endif
+
+#ifdef HOT_HALO
+struct haloacc_pos_data
+ *HaloAcc;
+#endif
+
+#ifdef TRACE_ACC
+struct pot_index
+ *PotInd;
+#endif
+
+#ifdef TRACE_ACC
+struct pot_index
+ *PotInd;
+#endif
+
#ifdef PY_INTERFACE
struct sph_particle_data
*SphQ, /*!< holds SPH particle data on local processor */
*DomainSphBufQ; /*!< buffer for SPH particle data in domain decomposition */
#endif
#ifdef STELLAR_PROP
/* the following struture holds data that is stored for each SPH particle in addition to the collisionless
* variables.
*/
struct st_particle_data
*StP, /*!< holds ST particle data on local processor */
*DomainStBuf; /*!< buffer for ST particle data in domain decomposition */
#endif
/* Variables for Tree
*/
int MaxNodes; /*!< maximum allowed number of internal nodes */
int Numnodestree; /*!< number of (internal) nodes in each tree */
struct NODE
*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 */
int *Nextnode; /*!< gives next node in tree walk */
int *Father; /*!< gives parent node in tree */
struct extNODE /*!< this structure holds additional tree-node information which is not needed in the actual gravity computation */
*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.
*/
struct io_header
header; /*!< holds header for snapshot files */
#ifdef CHIMIE_EXTRAHEADER
/*! Header for the chimie part.
*/
struct io_chimie_extraheader
chimie_extraheader;
#endif
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
*/
struct state_of_system
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.
*/
struct local_state_of_system
LocalSysState; /*<! Structure for storing some local statistics about the simulation. */
/* Various structures for communication
*/
struct gravdata_in
*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 */
struct gravdata_index
*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 */
struct densdata_in
*DensDataIn, /*!< holds particle data for SPH density computation to be exported to other processors */
*DensDataGet; /*!< holds imported particle data for SPH density computation */
struct densdata_out
*DensDataResult, /*!< stores the locally computed SPH density results for imported particles */
*DensDataPartialResult; /*!< imported partial SPH density results from other processors */
struct hydrodata_in
*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 */
struct hydrodata_out
*HydroDataResult, /*!< stores the locally computed SPH hydro results for imported particles */
*HydroDataPartialResult; /*!< imported partial SPH hydro-force results from other processors */
#ifdef MULTIPHASE
struct stickydata_in
*StickyDataIn,
*StickyDataGet;
struct stickydata_out
*StickyDataResult,
*StickyDataPartialResult;
struct Sticky_index *StickyIndex;
#endif
#ifdef CHIMIE
struct chimiedata_in
*ChimieDataIn, /*!< holds particle data for Chimie computation to be exported to other processors */
*ChimieDataGet; /*!< holds imported particle data for Chimie computation */
struct chimiedata_out
*ChimieDataResult, /*!< stores the locally computed Chimie results for imported particles */
*ChimieDataPartialResult; /*!< imported partial Chimie results from other processors */
struct starsdensdata_in
*StarsDensDataIn, /*!< holds particle data for SPH density computation to be exported to other processors */
*StarsDensDataGet; /*!< holds imported particle data for SPH density computation */
struct starsdensdata_out
*StarsDensDataResult, /*!< stores the locally computed SPH density results for imported particles */
*StarsDensDataPartialResult; /*!< imported partial SPH density results from other processors */
#endif
#ifdef DISSIPATION_FORCES
struct dissipationforcesdata_in
*DissipationForcesDataIn, /*!< holds particle data for SPH hydro-force computation to be exported to other processors */
*DissipationForcesDataGet; /*!< holds imported particle data for SPH hydro-force computation */
struct dissipationforcesdata_out
*DissipationForcesDataResult, /*!< stores the locally computed SPH hydro results for imported particles */
*DissipationForcesDataPartialResult; /*!< imported partial SPH hydro-force results from other processors */
#endif /* DISSIPATION_FORCES */
#ifdef FOF
struct FOFdata_in
*FOFDataIn, /*!< holds particle data for SPH hydro-force computation to be exported to other processors */
*FOFDataGet; /*!< holds imported particle data for SPH hydro-force computation */
struct FOFdata_out
*FOFDataResult, /*!< stores the locally computed SPH hydro results for imported particles */
*FOFDataPartialResult; /*!< imported partial SPH hydro-force results from other processors */
#endif /* FOF */
#ifdef TESSEL
struct ghostdata_in
*GhostDataIn, /*!< holds particle data for SPH density computation to be exported to other processors */
*GhostDataGet; /*!< holds imported particle data for SPH density computation */
struct ghostdata_out
*GhostDataResult, /*!< stores the locally computed SPH density results for imported particles */
*GhostDataPartialResult; /*!< imported partial SPH density results from other processors */
//struct ghost_particle_data
// *gP;
int NumgPart;
#endif /* TESSEL */
#ifdef SYNCHRONIZE_NGB_TIMESTEP
struct SynchroinzeNgbTimestepdata_in
*SynchroinzeNgbTimestepDataIn,
*SynchroinzeNgbTimestepDataGet;
#endif
#ifdef PY_INTERFACE
struct sphdata_in
*SphDataIn,
*SphDataGet;
struct sphdata_out
*SphDataResult,
*SphDataPartialResult;
struct denssphdata_in
*DensSphDataIn, /*!< holds particle data for SPH density computation to be exported to other processors */
*DensSphDataGet; /*!< holds imported particle data for SPH density computation */
struct denssphdata_out
*DensSphDataResult, /*!< stores the locally computed SPH density results for imported particles */
*DensSphDataPartialResult; /*!< imported partial SPH density results from other processors */
#endif
diff --git a/src/allvars.h b/src/allvars.h
index 9662d5d..163c632 100644
--- a/src/allvars.h
+++ b/src/allvars.h
@@ -1,2443 +1,2545 @@
/*! \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 KPC_IN_CM 3.085678e+21
#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 10000 /*!< 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 10
#define MAXNELEMENTS 64
#endif
#ifdef COOLING
#define COOLING_NMETALICITIES 9
#define COOLING_NTEMPERATURES 171
#endif
#ifdef COMPUTE_VELOCITY_DISPERSION
#define VELOCITY_DISPERSION_SIZE 3
#endif
+
+#ifdef TRACE_ACC
+#define NUMTRACEAVG 64
+#endif
+
#ifdef CHIMIE
extern int FE;
extern int METALS;
#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
#ifdef GAS_ACCRETION
extern int NumPart_acc;
extern int N_gas_acc;
#ifdef STELLAR_PROP
extern int N_stars_acc;
#endif
#endif
+
+
+#ifdef HOT_HALO
+extern int NumPart_HaloAcc;
+#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
#ifdef TESSEL
extern int NumPTUpdate;
#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
#ifdef GAS_ACCRETION
extern double gasAccretionRndTable[RNDTABLE]; /*!< Hold a table with random numbers, refreshed every timestep */
#endif
+#ifdef HOT_HALO
+extern double HaloRndTable[RNDTABLE]; /*!< Hold a table with random numbers, refreshed every timestep */
+#endif
+
#ifdef AB_TURB
//Ornstein-Uhlenbeck variables
extern double StOUVar;
extern double* StOUPhases;
extern gsl_rng* StRng;
//forcing field in fourie space
extern double* StAmpl;
extern double* StAka; //phases (real part)
extern double* StAkb; //phases (imag part)
extern double* StMode;
extern int StNModes;
//integertime StTPrev; (yr : ask ?)
extern int StTPrev;
extern double StSolWeightNorm;
#endif
#ifdef PY_INTERFACE
extern int NumPartQ;
extern int N_gasQ;
extern long long NtypeQ[6]; /*!< total number of particles of each type */
extern int NtypeLocalQ[6]; /*!< local number of particles of each type */
extern double DomainCornerQ[3]; /*!< gives the lower left corner of simulation volume */
extern double DomainCenterQ[3]; /*!< gives the center of simulation volume */
extern double DomainLenQ; /*!< gives the (maximum) side-length of simulation volume */
extern double DomainFacQ; /*!< factor used for converting particle coordinates to a Peano-Hilbert mesh covering the simulation volume */
extern int DomainMyStartQ; /*!< first domain mesh cell that resides on the local processor */
extern int DomainMyLastQ; /*!< last domain mesh cell that resides on the local processor */
extern int *DomainStartListQ; /*!< a table that lists the first domain mesh cell for all processors */
extern int *DomainEndListQ; /*!< a table that lists the last domain mesh cell for all processors */
extern double *DomainWorkQ; /*!< a table that gives the total "work" due to the particles stored by each processor */
extern int *DomainCountQ; /*!< a table that gives the total number of particles held by each processor */
extern int *DomainCountSphQ; /*!< a table that gives the total number of SPH particles held by each processor */
extern int *DomainTaskQ; /*!< this table gives for each leaf of the top-level tree the processor it was assigned to */
extern peanokey *DomainKeyBufQ; /*!< this points to a buffer used during the exchange of particle data */
extern int NTopnodesQ; /*!< total number of nodes in top-level tree */
extern int NTopleavesQ; /*!< number of leaves in top-level tree. Each leaf can be assigned to a different processor */
extern void *CommBufferQ; /*!< points to communication buffer, which is used in the domain decomposition, the
parallel tree-force computation, the SPH routines, etc. */
#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 */
}
#ifdef PY_INTERFACE
*TopNodesQ,
#endif
*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. */
#ifdef CHIMIE_STATS
extern FILE *FdChimieStatsSNs; /*!< file handle for chimie stats-file. */
extern FILE *FdChimieStatsGas; /*!< file handle for chimie stats-file. */
#endif
#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
#ifdef GAS_ACCRETION
extern FILE *FdGasAccretion; /*!< file handle for gas_accretion.txt log-file. */
#endif
+#ifdef PERIODICOUTER
+extern FILE *FdTrace; /*!< file handle for trace.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 */
extern double FullCosmicTimeTable[COSMICTIME_TABLE_LENGTH]; /*!< table for the computation of cosmic time */
extern double FullCosmicTimeTableInv[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) */
#ifdef GAS_ACCRETION
long long TotNumPart_acc;
long long TotN_gas_acc;
#endif
+
+#ifdef HOT_HALO
+ long long TotNumPart_HaloAcc;
+#endif
#ifdef PY_INTERFACE
long long TotNumPartQ; /*!< total particle numbers (global value) */
long long TotN_gasQ; /*!< total gas particle number (global value) */
int MaxPartQ; /*!< This gives the maxmimum number of particles that can be stored on one processor. */
int MaxPartSphQ; /*!< This gives the maxmimum number of SPH particles that can be stored on one processor. */
int BunchSizeSph;
int BunchSizeDensitySph;
double ForceSofteningQ;
#endif
#if defined(SFR) || defined(STELLAR_PROP)
long long TotN_stars; /*!< total stars particle number (global value) */
#endif
#ifdef MULTIPHASE
long long TotN_sph; /*!< total sph particle number (global value) */
long long TotN_sticky; /*!< total sticky particle number (global value) */
long long TotN_stickyflaged; /*!< total sticky flaged particle number (global value) */
long long TotN_stickyactive; /*!< total sticky active particle number (global value) */
long long TotN_dark; /*!< total dark particle number (global value) */
#endif
int MaxPart; /*!< This gives the maxmimum number of particles that can be stored on one processor. */
int MaxPartSph; /*!< This gives the maxmimum number of SPH particles that can be stored on one processor. */
#ifdef TESSEL
int MaxgPart;
#endif
#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
#ifdef SYNCHRONIZE_NGB_TIMESTEP
int BunchSizeSynchronizeNgBTimestep;
#endif
#ifdef DISSIPATION_FORCES
int BunchSizeDissipationForces;
#endif
#ifdef FOF
int BunchSizeFOF;
#endif
#ifdef TESSEL
int BunchSizeGhost;
#endif
double PartAllocFactor; /*!< in order to maintain work-load balance, the particle load will usually
NOT be balanced. Each processor allocates memory for PartAllocFactor times
the average number of particles to allow for that */
double TreeAllocFactor; /*!< Each processor allocates a number of nodes which is TreeAllocFactor times
the maximum(!) number of particles. Note: A typical local tree for N
particles needs usually about ~0.65*N nodes. */
#ifdef SFR
double StarsAllocFactor; /*!< Estimated fraction of gas particles that will form stars during the simulation
This allow to reduce the memory stored for stellar particles */
#endif
/* some SPH parameters */
double DesNumNgb; /*!< Desired number of SPH neighbours */
double MaxNumNgbDeviation; /*!< Maximum allowed deviation neighbour number */
double ArtBulkViscConst; /*!< Sets the parameter \f$\alpha\f$ of the artificial viscosity */
#ifdef ART_CONDUCTIVITY
double ArtCondConst; /*!< Sets the parameter \f$\alpha\f$ of the artificial conductivity */
double ArtCondThreshold;
#endif
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;
#ifdef PYCOOL
char * CoolingFile;
#else
char CoolingFile[MAXLEN_FILENAME]; /*!< cooling file */
#endif
double CutofCoolingTemperature;
/*
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_ZHSolar;
double CoolingParameters_cooling_data_max;
double CoolingParameters_cooling_data[COOLING_NMETALICITIES][COOLING_NTEMPERATURES];
int CoolingParameters_p;
int CoolingParameters_q;
#ifdef COOLING_WIERSMA
char CoolingDirectory[MAXLEN_FILENAME]; /*!< cooling directory */
#endif
#ifdef COOLING_GRACKLE
char GrackleCloudyTable[MAXLEN_FILENAME]; /*!< cooling cloudy table */
int GrackleUVbackground;
double GrackleRedshift;
#endif
#ifdef COOLING_FCT_FROM_HDF5
// cooling tables loaded from HDF5 files
// (dimensions depend on the presence of nHe)
float*** COOLING_TABLES_METAL_FREE;
float** COOLING_TABLES_TOTAL_METAL;
float*** ELECTRON_DENSITY_OVER_N_H_TABLES;
float** ELECTRON_DENSITY_OVER_N_H_TABLES_SOLAR;
float* HYDROGEN_TABLES;
float* TEMPERATURE_TABLES;
float* HELIUM_ABOUNDANCE_TABLES;
//corresponding sizes
int SIZE_HYDROGEN_TABLES;
int SIZE_TEMPERATURE_TABLES;
int SIZE_HELIUM_ABOUNDANCE_TABLES;
// current redshift value determining the cooling file
// from which the data is interpolated
float CURRENT_TABLE_REDSHIFT;
#endif
#endif
#ifdef CHIMIE
int ChimieNumberOfParameterFiles;
#ifdef PYCHEM
char * ChimieParameterFile;
#else
char ChimieParameterFile[MAXLEN_FILENAME]; /*!< chimie parameter file */
#endif
double ChimieSupernovaEnergy;
double ChimieKineticFeedbackFraction;
double ChimieWindSpeed;
double ChimieWindTime;
double ChimieSNIaThermalTime;
double ChimieSNIIThermalTime;
double ChimieMaxSizeTimestep;
#ifdef CHIMIE_ONE_SN_ONLY /*!< explode only one sn>*/
int ChimieOneSN;
double ChimieOneSNMass;
#endif
#if CHIMIE_EJECTA_RADIUS == 1
double ChimieEjectaRadius;
#endif
#endif
#if defined (CHIMIE) || defined (COOLING)
double InitGasMetallicity; /*!< initial gas metallicity>*/
double GasMetal; /*!< gas metal fraction, used when CHIMIE is disabled >*/
#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 JEANS_PRESSURE_FLOOR
double JeansMassFactor;
#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;
#ifndef LONGIDS
unsigned int MaxID; /* max value of ID, this is used to set id of new stars */
#else
unsigned long long MaxID; /* max value of ID, this is used to set id of new stars */
#endif
#endif
#ifdef FOF
double FoF_ThresholdDensity; /* threshold density : particles with density below FoF_ThresholdDensity are excluded from the FoF */
double FoF_MinHeadDensity; /* keep only heads with density higher than this value */
double FoF_Density;
double FoF_ThresholdDensityFactor;
double FoF_MinHeadDensityFactor;
int FoF_MinGroupMembers; /* minimum members required to form stars */
double FoF_MinGroupMass; /* minimum mass required to form stars (in solar mass) */
double FoF_HsmlSearchRadiusFactor; /* friends are search in a radius given by hsml time this factor */
double FoF_HsmlMaxDistFactor; /* a particle may be linked to a head only if ``r < Hsml*FoF_HsmlMaxDistFactor``*/
int FoF_StarFormationType; /*!< allow to tune the sfr in FOF */
double FoF_TimeBetFoF; /*!< simulation time interval between computations of FoF */
double FoF_TimeLastFoF; /*!< simulation time when the FoF was computed the last time */
int FoF_SnapshotFileCount; /*!< number of snapshot that is written next */
char FoF_SnapshotFileBase[MAXLEN_FILENAME]; /*!< basename to construct the names of snapshotf files */
#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
#if defined(ART_VISCO_MM)|| defined(ART_VISCO_RO) || defined(ART_VISCO_CD)
double ArtBulkViscConstMin;
double ArtBulkViscConstMax;
double ArtBulkViscConstL;
#endif
#ifdef METAL_DIFFUSION
double MetalDiffusionConst;
#endif
#ifdef AB_TURB
double StDecay;
double StEnergy;
double StDtFreq;
double StKmin;
double StKmax;
double StSolWeight;
double StAmplFac;
int StSpectForm;
int StSeed;
#endif
#ifdef GAS_ACCRETION
double AccretionParticleMass[6];
#endif
#ifdef SYNCHRONIZE_NGB_TIMESTEP
int NgbFactorTimestep;
#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 */
double CPU_ChimieDensCompWalk;
double CPU_ChimieDensCommSumm;
double CPU_ChimieDensImbalance;
double CPU_ChimieDensEnsureNgb;
double CPU_ChimieCompWalk;
double CPU_ChimieCommSumm;
double CPU_ChimieImbalance;
#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
#ifdef GAS_ACCRETION
char GasAccretionFile[MAXLEN_FILENAME]; /*!< name of file with sfr 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
+#ifdef PERIODICOUTER
+ char TraceFile[MAXLEN_FILENAME];
+ double TracePos[3]; //trace particle position
+ double TraceVel[3]; //trace particle velocity
+ double TraceAcc[3]; //trace particle acceleration
+ double TracePeriodPos[3]; //trace particle position in periodic box
+ FLOAT TraceAngOld[3];
+ FLOAT TraceTheta;
+ FLOAT TracePotential;
+ double TraceAngular[4]; //trace particle Angular velocity
+ double TraceQuat[4]; //Trace quaternion
+ double TraceQuatConj[4]; //Easiest to store conjugate here to save repetitive calculation
+ FLOAT QuatOrig[4]; //Need an arbitrary direction of 0 theta, define it when velocity is -y
+ int InertialV;
+#ifdef TRACE_ACC
+#ifndef LONGIDS
+ unsigned int TraceMinPot[NUMTRACEAVG]; //Get minimum potential particle originally
+#else
+ unsigned long long TraceMinPot[NUMTRACEAVG];
+#endif
+#endif
+#endif
+
+#ifdef HOT_HALO
+ double HaloT; //Halo Temperature
+ double HaloPartMass; //Halo particle mass
+ double HaloScaleFactor; //Halo scale factor (the value at 0)
+ FLOAT Halocs; //Halo soundspeed
+ FLOAT HaloLast;
+ double HaloAccYBound;
+#endif
+
+
+#ifdef MERGE_SPLIT
+ double Dwarf_Split_Merge_Distance; //Distance to count as hsml for dwarf particles
+ int SplitThreshold;
+ int MergeThreshold;
+ int nZones;
+ int split_method;
+ double MinMassForParticleSplit[6];
+ double MaxMassForParticleMerger[6];
+#ifndef LONGIDS
+ unsigned int MergeID; /*!< particle identifier */
+#else
+ unsigned long long MergeID; /*!< particle identifier */
+#endif
+#endif
+
+
+
#if defined(CHIMIE) || defined(FOF)
double CMUtoMsol; /*!< convertion factor from Code Mass Unit to Solar Mass >*/
double MsoltoCMU; /*!< convertion factor from Solar Mass to Code Mass Unit >*/
#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 SYNCHRONIZE_NGB_TIMESTEP
int Old_Ti_endstep; /*!< marks start of old current timestep of particle on integer timeline */
int Old_Ti_begstep; /*!< marks end of old current timestep of particle on integer timeline */
#endif
#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
#ifdef TESSEL
int iT; /*!< index of a triangle to which the point belong to */
int IsDone;
int IsAdded; /*!< if the point has already be added in the tesselation */
int ivPoint; /*!< index of first voronoi point */
int nvPoints; /*!< number of voronoi points */
int iMedian;
int nMedians;
double Volume;
double Density;
double Pressure;
double Entropy;
double rSearch; /*!< radius in which particles must search for ngbs */
int iPref; /*!< for a ghost point, index of the reference point */
FLOAT tesselAccel[3];
#endif
# ifdef SYNCHRONIZE_NGB_TIMESTEP
int Ti_step;
#endif
#ifdef VANISHING_PARTICLES
int VanishingFlag;
#endif
#ifdef FOF_SFR
//int FoFidx; /* no longer used */
#endif
}
*P, /*!< holds particle data on local processor */
#ifdef PY_INTERFACE
*Q,
*DomainPartBufQ, /*!< buffer for particle data used in domain decomposition */
#endif
*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 COOLING
//FLOAT EntropyRad; /*!< current value of entropy resulting from the cooling */
FLOAT DtEntropyRad; /*!< rate of change of entropy due to cooling */
FLOAT DtEnergyRad;
#endif
#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 OUTPUTOPTVAR1
FLOAT OptVar1; /*!< optional variable 1 */
#endif
#ifdef OUTPUTOPTVAR2
FLOAT OptVar2; /*!< optional variable 2 */
#endif
#ifdef COMPUTE_VELOCITY_DISPERSION
FLOAT VelocityDispersion[VELOCITY_DISPERSION_SIZE]; /*!< velocity dispersion */
#endif
#ifdef CHIMIE
FLOAT Metal[NELEMENTS];
#ifdef CHIMIE_SMOOTH_METALS
FLOAT MassMetal[NELEMENTS]; /*!< old metal estimation (ratio of masses) */
FLOAT RhoMetal[NELEMENTS]; /*!< metal density of the particle */
#endif
FLOAT dMass; /*!< mass variation due to mass transfere */
#ifdef CHIMIE_THERMAL_FEEDBACK
FLOAT DeltaEgySpec;
FLOAT SNIaThermalTime; /*!< flag particles that got energy from SNIa */
FLOAT SNIIThermalTime; /*!< flag particles that got energy from SNII */
double NumberOfSNIa;
double NumberOfSNII;
#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
#ifdef ART_CONDUCTIVITY
FLOAT EnergyIntPred;
FLOAT GradEnergyInt[3];
#endif
#ifdef AB_TURB
FLOAT TurbAccel[3];
#endif
#if defined(ART_VISCO_MM)|| defined(ART_VISCO_RO) || defined(ART_VISCO_CD)
double ArtBulkViscConst;
#ifdef ART_VISCO_CD
double DmatCD[3][3];
double TmatCD[3][3];
double DiVelAccurate;
double DiVelTemp;
double ArtBulkViscConstOld;
double R_CD;
FLOAT MaxSignalVelCD;
#endif
#endif
#ifdef GAS_ACCRETION
int ActiveFlag;
#endif
#ifdef DISSIPATION_FORCES
FLOAT EnergyDissipationForces;
FLOAT DtEnergyDissipationForces;
FLOAT DissipationForcesAccel[3];
#endif
#if PY_INTERFACE
FLOAT Observable;
FLOAT ObsMoment0;
FLOAT ObsMoment1;
FLOAT GradObservable[3];
#endif
# ifdef SYNCHRONIZE_NGB_TIMESTEP
int Ti_minNgbStep;
#endif
#if defined(TIMESTEP_UPDATE_FOR_FEEDBACK) && defined(CHIMIE_THERMAL_FEEDBACK)
FLOAT FeedbackUpdatedAccel[3]; /*!< acceleration after feedback injection */
FLOAT MaxSignalVelFeedbackUpdated;
#endif
#ifdef DENSITY_INDEPENDENT_SPH
FLOAT EgyWtDensity; /*!< 'effective' rho to use in hydro equations */
FLOAT EntVarPred; /*!< predicted entropy variable */
FLOAT DhsmlEgyDensityFactor; /*!< correction factor for density-independent entropy formulation */
#endif
#ifdef FOF
int FOF_CPUHead; /*!< cpu ID of the first particle of the chain */
int FOF_CPUTail; /*!< cpu ID of the last particle of the chain */
int FOF_CPUNext; /*!< cpu ID of the next particle of the chain */
int FOF_CPUPrev; /*!< cpu ID of the previous particle of the chain */
int FOF_Head; /*!< first particle of the chain */
int FOF_Tail; /*!< last particle of the chain */
int FOF_Next; /*!< next particle in the chain */
int FOF_Prev; /*!< previous particle in the chain */
int FOF_gid; /*!< group id */
int FOF_Len; /*!< length of the chain */
int FOF_Done; /*!< the particle is done (used for pseudo heads) */
FLOAT FOF_DensMax;
FLOAT FOF_MassMax;
FLOAT FOF_MassMin;
FLOAT FOF_MassSSP;
FLOAT FOF_NStars;
#ifdef CHIMIE_OPTIMAL_SAMPLING
FLOAT OptIMF_k;
FLOAT OptIMF_CurrentMass;
#endif
#endif
#ifdef METAL_DIFFUSION
FLOAT RmsSpeed;
FLOAT MetalDiffusionCoeff;
FLOAT MetalDiffusionA;
FLOAT MetalDiffusionB[NELEMENTS];
#endif
}
*SphP, /*!< holds SPH particle data on local processor */
#ifdef PY_INTERFACE
*SphQ,
*DomainSphBufQ, /*!< buffer for SPH particle data in domain decomposition */
#endif
*DomainSphBuf; /*!< buffer for SPH particle data in domain decomposition */
#ifdef FOF
extern struct fof_particles_in
{
FLOAT Mass;
FLOAT MassNew;
FLOAT MassMax;
FLOAT MassMin;
FLOAT MassSSP;
FLOAT k;
FLOAT Pos[3];
int NStars;
int ID;
int Index;
int Task;
}
*FoF_P,*FoF_P_local;
extern struct fof_groups_data
{
int Index; /*!< group index (used when the group is send) */
int Head; /*!< head index */
int HeadID; /*!< head id, -1 if the head is not local */
int LocalHead; /*!< index to local head */
int Task; /*!< task hosting the true head */
int N; /*!< number of members */
int Nlocal; /*!< number of local members */
float Mass; /*!< total mass */
float MassCenter[3]; /*!< mass center */
float DensityMax; /*!< density max */
float DensityMin; /*!< density min */
float MV[3];
float MV2[3];
float RadiusMax;
float K;
float W;
float U;
float T;
float Density;
float HeadPos[3];
float HeadPotential;
int SfrFlag;
}
*Groups,*GroupsGet,*GroupsRecv;
extern int *Tot_HeadID_list;
extern int Tot_Ngroups;
extern int Tot_Ntgroups;
extern int Tot_Npgroups;
extern int Tot_Ntsfrgroups;
extern int Ngroups; /* true and pseudo groups */
extern int Ntgroups; /* true groups */
extern int Npgroups; /* pseudo groups */
extern int Ntsfrgroups; /* true groups that forms stars */
extern int Nsfrgroups; /* local number of groups flagged for sfr */
extern int Tot_Nsfrgroups; /* total number of groups flagged for sfr */
#endif
#ifdef GAS_ACCRETION
extern struct acc_particle_data
{
FLOAT Pos[3];
FLOAT Vel[3];
FLOAT Mass;
FLOAT Time;
int Type;
int ID;
}
*Acc;
extern struct gas_acc_particle_data
{
FLOAT Entropy;
#ifdef CHIMIE
FLOAT Metal[NELEMENTS];
#endif
}
*SphAcc;
#endif
+#ifdef HOT_HALO
+extern struct haloacc_pos_data
+{
+ FLOAT Pos[3];
+ FLOAT Vel[3];
+ FLOAT Mass;
+ FLOAT Time;
+ int Type;
+ int ID;
+}
+ *HaloAcc;
+#endif
+
+#ifdef TRACE_ACC
+extern struct pot_index
+{
+ FLOAT Potential;
+#ifndef LONGIDS
+ unsigned int ID;
+#else
+ unsigned long long ID;
+#endif
+ int index;
+}
+ *PotInd;
+#endif
+
+
#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 Y; /*!< elements weighting normalisation */
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;
double NumberOfSNIa;
double NumberOfSNII;
#ifdef CHIMIE_KINETIC_FEEDBACK
double NgbMass; /*!< mass of neighbours */
#endif
#ifdef CHIMIE
unsigned int Flag;
#endif
#ifdef CHIMIE_OPTIMAL_SAMPLING
float OptIMF_CurrentMass;
int OptIMF_N_WD;
float OptIMF_k; /*!< kroupa normalization */
float OptIMF_m_max; /*!< max mass of star in the "cluster">*/
#endif
#ifdef FOF_SFR
FLOAT MassMax; /*!< maximal stellar mass contained by the particle */
FLOAT MassMin; /*!< minimal stellar mass contained by the particle */
FLOAT MassSSP; /*!< mass of the total SSP */
int NStars; /*!< number of stars contained by the particle. If =-1, the particle represents a portion of the IMF */
#endif
#if CHIMIE_EJECTA_RADIUS == 2
FLOAT Pressure;
#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 SolarMassAbundances[NELEMENTS];
char labels[256-4-4*(NELEMENTS)];
}
chimie_extraheader;
#endif
#define IO_NBLOCKS 24 /*!< 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_METALS,
IO_STAR_FORMATIONTIME,
IO_INITIAL_MASS,
IO_STAR_IDPROJ,
IO_STAR_RHO,
IO_STAR_HSML,
IO_STAR_METALS,
IO_OPTVAR1,
IO_OPTVAR2
};
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 DISSIPATION_FORCES
double EnergyDissipationForces;
#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
#ifdef INTEGRAL_CONSERVING_DISSIPATION
double EnergyICDissipation;
#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];
#ifdef DISSIPATION_FORCES
double EnergyDissipationForcesComp[6];
#endif
#ifdef INTEGRAL_CONSERVING_DISSIPATION
double EnergyICDissipationComp[6];
#endif
}
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
#ifdef INTEGRAL_CONSERVING_DISSIPATION
double EnergyICDissipation;
#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;
#ifdef ART_CONDUCTIVITY
FLOAT EnergyIntPred;
#endif
}
*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;
#ifdef ART_CONDUCTIVITY
FLOAT GradEnergyInt[3];
#endif
#ifdef DENSITY_INDEPENDENT_SPH
FLOAT EgyRho;
FLOAT DhsmlEgyDensity;
#endif
#ifdef CHIMIE_SMOOTH_METALS
FLOAT RhoMetal[NELEMENTS];
#endif
#ifdef METAL_DIFFUSION
FLOAT RmsSpeed;
#endif
}
*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
#ifdef ART_CONDUCTIVITY
FLOAT NormGradEnergyInt;
#endif
#if defined(ART_VISCO_MM)|| defined(ART_VISCO_RO) || defined(ART_VISCO_CD)
double ArtBulkViscConst;
#endif
#ifdef DENSITY_INDEPENDENT_SPH
FLOAT EgyRho;
FLOAT EntVarPred;
#endif
#if defined(TIMESTEP_UPDATE_FOR_FEEDBACK) && defined(CHIMIE_THERMAL_FEEDBACK)
FLOAT PressureFeedbackUpdated;
FLOAT F1FeedbackUpdated;
#endif
#ifdef METAL_DIFFUSION
FLOAT MetalDiffusionCoeff;
#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
#ifdef OUTPUT_CONDUCTIVITY
FLOAT OptVar2;
#endif
#ifdef ART_VISCO_CD
double DmatCD[3][3];
double TmatCD[3][3];
double R_CD;
FLOAT MaxSignalVelCD;
#endif
#if defined(TIMESTEP_UPDATE_FOR_FEEDBACK) && defined(CHIMIE_THERMAL_FEEDBACK)
FLOAT AccFeedbackUpdated[3];
FLOAT maxSignalVelFeedbackUpdated;
#endif
#ifdef METAL_DIFFUSION
FLOAT MetalDiffusionA;
FLOAT MetalDiffusionB[NELEMENTS];
#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 Y;
FLOAT Pressure;
FLOAT F1;
FLOAT DhsmlDensityFactor;
int Timestep;
int Task;
int Index;
double TotalEjectedGasMass;
double TotalEjectedEltMass[NELEMENTS];
double TotalEjectedEgySpec;
double NumberOfSNIa;
double NumberOfSNII;
#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 Y;
FLOAT DhsmlDensity;
FLOAT Ngb;
#ifdef CHIMIE_KINETIC_FEEDBACK
FLOAT NgbMass;
#endif
#if CHIMIE_EJECTA_RADIUS == 2
FLOAT Pressure;
#endif
}
*StarsDensDataResult, /*!< stores the locally computed SPH density results for imported particles */
*StarsDensDataPartialResult; /*!< imported partial SPH density results from other processors */
#endif /*CHIMIE*/
#ifdef DISSIPATION_FORCES
extern struct dissipationforcesdata_in
{
FLOAT Pos[3];
FLOAT Vel[3];
FLOAT Hsml;
FLOAT Mass;
FLOAT Density;
int Task;
int Index;
}
*DissipationForcesDataIn, /*!< holds particle data for SPH hydro-force computation to be exported to other processors */
*DissipationForcesDataGet; /*!< holds imported particle data for SPH hydro-force computation */
extern struct dissipationforcesdata_out
{
FLOAT Acc[3];
FLOAT DtEnergy;
}
*DissipationForcesDataResult, /*!< stores the locally computed SPH hydro results for imported particles */
*DissipationForcesDataPartialResult; /*!< imported partial SPH hydro-force results from other processors */
#endif /* DISSIPATION_FORCES */
#ifdef FOF
extern struct FOFdata_in
{
FLOAT Pos[3];
FLOAT Hsml;
FLOAT Density;
int ID;
int FOF_Head;
int FOF_Tail;
int FOF_Prev;
int FOF_Next;
int FOF_CPUHead; /*!< index of the particle in its local proc */
int FOF_CPUPrev; /*!< index of the particle in its local proc */
int FOF_idx;
FLOAT FOF_DensMax;
int Task;
int Index;
}
*FOFDataIn, /*!< holds particle data for SPH hydro-force computation to be exported to other processors */
*FOFDataGet; /*!< holds imported particle data for SPH hydro-force computation */
extern struct FOFdata_out
{
int FOF_Head;
int FOF_Prev;
FLOAT FOF_DensMax;
int FOF_CPUHead;
int FOF_CPUPrev;
int FOF_Done;
}
*FOFDataResult, /*!< stores the locally computed SPH hydro results for imported particles */
*FOFDataPartialResult; /*!< imported partial SPH hydro-force results from other processors */
#endif /* FOF */
#ifdef TESSEL
extern struct ghostdata_in
{
FLOAT Pos[3];
FLOAT rSearch;
int Index;
int Task;
}
*GhostDataIn, /*!< holds particle data for SPH density computation to be exported to other processors */
*GhostDataGet; /*!< holds imported particle data for SPH density computation */
extern struct ghostdata_out
{
FLOAT Value;
}
*GhostDataResult, /*!< stores the locally computed SPH density results for imported particles */
*GhostDataPartialResult; /*!< imported partial SPH density results from other processors */
/* ghost particles */
//extern struct ghost_particle_data
//{
// FLOAT Pos[3]; /*!< particle position at its current time */
// FLOAT Mass; /*!< particle mass */
//}
// *gP;
extern int NumgPart;
#endif /* TESSEL */
#ifdef SYNCHRONIZE_NGB_TIMESTEP
extern struct SynchroinzeNgbTimestepdata_in
{
FLOAT Pos[3];
FLOAT Hsml;
int Ti_step;
int Ti_endstep;
int Index;
int Task;
#ifdef MULTIPHASE
int Phase;
#endif
}
*SynchroinzeNgbTimestepDataIn,
*SynchroinzeNgbTimestepDataGet;
#endif
#ifdef PY_INTERFACE
extern struct denssphdata_in
{
FLOAT Pos[3];
FLOAT Vel[3];
FLOAT Hsml;
FLOAT Density;
FLOAT DhsmlDensityFactor;
int Index;
int Task;
FLOAT Observable;
}
*DensSphDataIn, /*!< holds particle data for SPH density computation to be exported to other processors */
*DensSphDataGet; /*!< holds imported particle data for SPH density computation */
extern struct denssphdata_out
{
FLOAT Rho;
FLOAT Div, Rot[3];
FLOAT DhsmlDensity;
FLOAT Ngb;
FLOAT GradObservable[3];
}
*DensSphDataResult, /*!< stores the locally computed SPH density results for imported particles */
*DensSphDataPartialResult; /*!< imported partial SPH density results from other processors */
extern struct sphdata_in
{
FLOAT Pos[3];
FLOAT Vel[3];
FLOAT Hsml;
FLOAT Density;
FLOAT DhsmlDensityFactor;
FLOAT ObsMoment0;
FLOAT ObsMoment1;
FLOAT Observable;
int Task;
int Index;
}
*SphDataIn, /*!< holds particle data for SPH hydro-force computation to be exported to other processors */
*SphDataGet; /*!< holds imported particle data for SPH hydro-force computation */
extern struct sphdata_out
{
FLOAT ObsMoment0;
FLOAT ObsMoment1;
FLOAT GradObservable[3];
}
*SphDataResult, /*!< stores the locally computed SPH hydro results for imported particles */
*SphDataPartialResult; /*!< imported partial SPH hydro-force results from other processors */
#endif /*PY_INTERFACE*/
#endif
diff --git a/src/begrun.c b/src/begrun.c
index 26be96a..c148820 100644
--- a/src/begrun.c
+++ b/src/begrun.c
@@ -1,2467 +1,2560 @@
#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
if(ThisTask == 0)
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 = All.TimeBegin;
#endif
#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");
}
if (ThisTask==0)
printf("Initialize full cosmic table\n");
init_full_cosmictime_table();
if (ThisTask==0)
printf("Initialize full cosmic table done.\n");
#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");
#ifdef COOLING_WIERSMA
//InitWiersmaCooling("/home/epfl/revaz/code/gear/PyCool/tables_wiersma/coolingtables/");
InitWiersmaCooling(All.CoolingDirectory);
//SetRedshiftInterpolationOff();
#else
#ifdef COOLING_GRACKLE
init_cooling_GRACKLE();
#else
init_cooling_with_metals();
#endif
#endif
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 mass abundance %s\t= %g\n",get_Element(i),get_SolarMassAbundance(i));
}
if(ThisTask == 0) printf("Initialize chimie done...\n");
#endif
#ifdef COOLING
#ifdef CHIMIE
All.CoolingParameters_FeHSolar = get_SolarMassAbundance(FE); /* for consitency, use the value defined in chimie file */
#else
All.CoolingParameters_FeHSolar = FEH_SOLAR; /* use a default value */
#endif
#endif
#ifdef AB_TURB
init_turb();
#endif
#ifdef ART_VISCO_CD
art_visc_allocate();
#endif
#ifdef CHIMIE_ONE_SN_ONLY
All.ChimieOneSN=0;
#endif
+
+#ifdef HOT_HALO
+ All.Halocs = BOLTZMANN*All.HaloT/(16./26.*PROTONMASS)/(All.UnitVelocity_in_cm_per_s*All.UnitVelocity_in_cm_per_s);
+ All.HaloPartMass *= SOLAR_MASS/All.UnitMass_in_g;
+ All.HaloLast = All.TimeBegin;
+ All.HaloAccYBound = 0;
+#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;
#ifdef ART_CONDUCTIVITY
All.ArtCondConst = all.ArtCondConst;
All.ArtCondThreshold = all.ArtCondThreshold;
#endif
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 JEANS_PRESSURE_FLOOR
All.JeansMassFactor = all.JeansMassFactor;
#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 FOF
All.FoF_Density = all.FoF_Density;
All.FoF_ThresholdDensityFactor = all.FoF_ThresholdDensityFactor;
All.FoF_MinHeadDensityFactor = all.FoF_MinHeadDensityFactor;
All.FoF_MinGroupMembers = all.FoF_MinGroupMembers;
All.FoF_MinGroupMass = all.FoF_MinGroupMass;
All.FoF_TimeBetFoF = all.FoF_TimeBetFoF;
All.FoF_HsmlSearchRadiusFactor = all.FoF_HsmlSearchRadiusFactor;
All.FoF_HsmlMaxDistFactor = all.FoF_HsmlMaxDistFactor;
All.FoF_StarFormationType = all.FoF_StarFormationType;
#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.ChimieSNIaThermalTime = all.ChimieSNIaThermalTime;
All.ChimieSNIIThermalTime = all.ChimieSNIIThermalTime;
All.ChimieMaxSizeTimestep = all.ChimieMaxSizeTimestep;
#ifdef CHIMIE_ONE_SN_ONLY
All.ChimieOneSNMass = all.ChimieOneSNMass;
#endif
#if CHIMIE_EJECTA_RADIUS == 1
All.ChimieEjectaRadius = all.ChimieEjectaRadius;
#endif
#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
#if defined(ART_VISCO_MM)|| defined(ART_VISCO_RO) || defined(ART_VISCO_CD)
All.ArtBulkViscConstMin = all.ArtBulkViscConstMin;
All.ArtBulkViscConstMax = all.ArtBulkViscConstMax;
All.ArtBulkViscConstL = all.ArtBulkViscConstL;
#endif
#ifdef METAL_DIFFUSION
All.MetalDiffusionConst = all.MetalDiffusionConst;
#endif
#ifdef AB_TURB
All.StDecay = all.StDecay;
All.StEnergy = all.StEnergy;
All.StDtFreq = all.StDtFreq;
All.StKmin = all.StKmin;
All.StKmax = all.StKmax;
All.StSolWeight = all.StSolWeight;
All.StAmplFac = all.StAmplFac;
All.StSpectForm = all.StSpectForm;
All.StSeed = all.StSeed;
#endif
#ifdef SYNCHRONIZE_NGB_TIMESTEP
All.NgbFactorTimestep = all.NgbFactorTimestep;
#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);
#ifdef FOF
strcpy(All.FoF_SnapshotFileBase, all.FoF_SnapshotFileBase);
#endif
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");
}
if (ThisTask==0)
printf("Initialize full cosmic table\n");
init_full_cosmictime_table();
if (ThisTask==0)
printf("Initialize full 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 PERIODICOUTER
+ init_quat();
+#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 PNBODY
if(ThisTask == 0) printf("Initialize pnbody...\n");
init_pnbody();
if(ThisTask == 0) printf("Initialize pnbody 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
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.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);
// }
#ifdef COLDGAS_CYCLE
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.HubbleParam;
All.StarFormationDensity = All.StarFormationDensity/All.UnitDensity_in_cgs/(All.HubbleParam*All.HubbleParam);
#endif
#ifdef FOF
All.FoF_Density = All.FoF_Density/All.UnitDensity_in_cgs/(All.HubbleParam*All.HubbleParam);
All.FoF_ThresholdDensity = All.FoF_ThresholdDensityFactor*All.FoF_Density;
All.FoF_MinHeadDensity = All.FoF_MinHeadDensityFactor *All.FoF_Density;
All.FoF_MinGroupMass *=SOLAR_MASS/All.UnitMass_in_g*All.HubbleParam; /* to CMU */
#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 / All.HubbleParam; /* erg/s/g to code unit */
}
#endif
#ifdef FEEDBACK
All.SupernovaEgySpecPerMassUnit *= All.UnitMass_in_g / All.UnitEnergy_in_cgs;
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.HubbleParam;
All.ChimieWindSpeed = All.ChimieWindSpeed*1e5/All.UnitVelocity_in_cm_per_s;
All.ChimieWindTime = All.ChimieWindTime*3.1536e13/All.UnitTime_in_s*All.HubbleParam;
All.ChimieSNIaThermalTime = All.ChimieSNIaThermalTime*3.1536e13/All.UnitTime_in_s*All.HubbleParam;
All.ChimieSNIIThermalTime = All.ChimieSNIIThermalTime*3.1536e13/All.UnitTime_in_s*All.HubbleParam;
All.ChimieMaxSizeTimestep = All.ChimieMaxSizeTimestep*3.1536e13/All.UnitTime_in_s*All.HubbleParam;
#endif
#if defined(CHIMIE) || defined(FOF)
All.CMUtoMsol = All.UnitMass_in_g/SOLAR_MASS/All.HubbleParam; /* convertion factor from Code Mass Unit to Solar Mass */
All.MsoltoCMU = 1/All.CMUtoMsol; /* convertion factor from Solar Mass to Code Mass Unit */
#endif
#ifdef CHIMIE
#ifdef CHIMIE_ONE_SN_ONLY
All.ChimieOneSNMass = All.ChimieOneSNMass*All.MsoltoCMU;
#endif
#if CHIMIE_EJECTA_RADIUS == 1
All.ChimieEjectaRadius = All.ChimieEjectaRadius * KPC_IN_CM/All.UnitLength_in_cm * All.HubbleParam; /* kpc to code length units */
#endif
#endif
#ifdef JEANS_PRESSURE_FLOOR
All.JeansMassFactor = pow(All.JeansMassFactor,2/3.);
#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("ChimieSNIaThermalTime (internal units) = %g \n", All.ChimieSNIaThermalTime);
printf("ChimieSNIIThermalTime (internal units) = %g \n", All.ChimieSNIIThermalTime);
printf("ChimieMaxSizeTimestep (internal units) = %g \n", All.ChimieMaxSizeTimestep);
#endif
#ifdef FOF
printf("FoF_Density (internal units) = %g \n",All.FoF_Density);
printf("FoF_ThresholdDensity (internal units) = %g \n",All.FoF_ThresholdDensity);
printf("FoF_MinHeadDensity (internal units) = %g \n",All.FoF_MinHeadDensity);
printf("FoF_MinGroupMass (internal units) = %g \n",All.FoF_MinGroupMass);
printf("FoF_HsmlSearchRadiusFactor (internal units) = %g \n",All.FoF_HsmlSearchRadiusFactor);
#endif
#ifdef JEANS_PRESSURE_FLOOR
printf("JeansMassFactor^(2/3) = %g \n",All.JeansMassFactor);
#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
#ifdef INTEGRAL_CONSERVING_DISSIPATION
LocalSysState.EnergyICDissipation = 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(RestartFlag == 0)
strcpy(mode, "w");
else
strcpy(mode, "a");
/* for this kind of log, all tasks write its own file */
#ifdef CHIMIE
#ifdef CHIMIE_STATS
sprintf(buf, "%s%s_%s.%d", All.OutputDir, All.ChimieFile,"SNs",ThisTask);
if(!(FdChimieStatsSNs = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
sprintf(buf, "%s%s_%s.%d", All.OutputDir, All.ChimieFile,"Gas",ThisTask);
if(!(FdChimieStatsGas = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
#endif
#endif
if(ThisTask != 0) /* only the root processor writes to the log files */
return;
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 DISSIPATION_FORCES
fprintf(FdEnergy,"EnergyDissipationForces ");
#endif
#ifdef INTEGRAL_CONSERVING_DISSIPATION
fprintf(FdEnergy,"EnergyICDissipation ");
#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
#ifdef GAS_ACCRETION
sprintf(buf, "%s%s", All.OutputDir, All.GasAccretionFile);
if(!(FdGasAccretion = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
#endif
+
+#ifdef PERIODICOUTER
+ sprintf(buf, "%s%s", All.OutputDir, All.TraceFile);
+ if(!(FdTrace = 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)
{
/* for this kind of log, all tasks write its own file */
#ifdef CHIMIE
#ifdef CHIMIE_STATS
fclose(FdChimieStatsSNs);
fclose(FdChimieStatsGas);
#endif
#endif
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 CHIMIE
fclose(FdChimie);
#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
#ifdef GAS_ACCRETION
fclose(FdGasAccretion);
#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
#ifdef GAS_ACCRETION
strcpy(tag[nt], "GasAccretionFile");
addr[nt] = All.GasAccretionFile;
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;
#ifdef ART_CONDUCTIVITY
strcpy(tag[nt], "ArtCondConst");
addr[nt] = &All.ArtCondConst;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ArtCondThreshold");
addr[nt] = &All.ArtCondThreshold;
id[nt++] = DOUBLE;
#endif
#if defined(ART_VISCO_MM)|| defined(ART_VISCO_RO) || defined(ART_VISCO_CD)
strcpy(tag[nt], "ArtBulkViscConstMin");
addr[nt] = &All.ArtBulkViscConstMin;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ArtBulkViscConstMax");
addr[nt] = &All.ArtBulkViscConstMax;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ArtBulkViscConstL");
addr[nt] = &All.ArtBulkViscConstL;
id[nt++] = DOUBLE;
#endif
#if METAL_DIFFUSION
strcpy(tag[nt], "MetalDiffusionConst");
addr[nt] = &All.MetalDiffusionConst;
id[nt++] = DOUBLE;
#endif
#ifdef AB_TURB
strcpy(tag[nt], "ST_decay");
addr[nt] = &All.StDecay;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ST_energy");
addr[nt] = &All.StEnergy;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ST_DtFreq");
addr[nt] = &All.StDtFreq;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ST_Kmin");
addr[nt] = &All.StKmin;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ST_Kmax");
addr[nt] = &All.StKmax;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ST_SolWeight");
addr[nt] = &All.StSolWeight;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ST_AmplFac");
addr[nt] = &All.StAmplFac;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ST_SpectForm");
addr[nt] = &All.StSpectForm;
id[nt++] = INT;
strcpy(tag[nt], "ST_Seed");
addr[nt] = &All.StSeed;
id[nt++] = INT;
#endif
#ifdef SYNCHRONIZE_NGB_TIMESTEP
strcpy(tag[nt], "NgbFactorTimestep");
addr[nt] = &All.NgbFactorTimestep;
id[nt++] = INT;
#endif
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;
#ifdef SFR
strcpy(tag[nt], "StarsAllocFactor");
addr[nt] = &All.StarsAllocFactor;
id[nt++] = DOUBLE;
#endif
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;
#ifdef COOLING_WIERSMA
strcpy(tag[nt], "CoolingDirectory");
addr[nt] = All.CoolingDirectory;
id[nt++] = STRING;
#endif
#ifdef COOLING_GRACKLE
strcpy(tag[nt], "GrackleCloudyTable");
addr[nt] = All.GrackleCloudyTable;
id[nt++] = STRING;
strcpy(tag[nt], "GrackleUVbackground");
addr[nt] = &All.GrackleUVbackground;
id[nt++] = INT;
strcpy(tag[nt], "GrackleRedshift");
addr[nt] = &All.GrackleRedshift;
id[nt++] = DOUBLE;
#endif
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], "ChimieSNIaThermalTime");
addr[nt] = &All.ChimieSNIaThermalTime;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ChimieSNIIThermalTime");
addr[nt] = &All.ChimieSNIIThermalTime;
id[nt++] = DOUBLE;
strcpy(tag[nt], "ChimieMaxSizeTimestep");
addr[nt] = &All.ChimieMaxSizeTimestep;
id[nt++] = DOUBLE;
#ifdef CHIMIE_ONE_SN_ONLY
strcpy(tag[nt], "ChimieOneSNMass");
addr[nt] = &All.ChimieOneSNMass;
id[nt++] = DOUBLE;
#endif
#if CHIMIE_EJECTA_RADIUS == 1
strcpy(tag[nt], "ChimieEjectaRadius");
addr[nt] = &All.ChimieEjectaRadius;
id[nt++] = DOUBLE;
#endif
#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 JEANS_PRESSURE_FLOOR
strcpy(tag[nt], "JeansMassFactor");
addr[nt] = &All.JeansMassFactor;
id[nt++] = DOUBLE;
#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 FOF
strcpy(tag[nt], "FoF_Density");
addr[nt] = &All.FoF_Density;
id[nt++] = DOUBLE;
strcpy(tag[nt], "FoF_ThresholdDensityFactor");
addr[nt] = &All.FoF_ThresholdDensityFactor;
id[nt++] = DOUBLE;
strcpy(tag[nt], "FoF_MinHeadDensityFactor");
addr[nt] = &All.FoF_MinHeadDensityFactor;
id[nt++] = DOUBLE;
strcpy(tag[nt], "FoF_MinGroupMembers");
addr[nt] = &All.FoF_MinGroupMembers;
id[nt++] = INT;
strcpy(tag[nt], "FoF_MinGroupMass");
addr[nt] = &All.FoF_MinGroupMass;
id[nt++] = DOUBLE;
strcpy(tag[nt], "FoF_HsmlSearchRadiusFactor");
addr[nt] = &All.FoF_HsmlSearchRadiusFactor;
id[nt++] = DOUBLE;
strcpy(tag[nt], "FoF_HsmlMaxDistFactor");
addr[nt] = &All.FoF_HsmlMaxDistFactor;
id[nt++] = DOUBLE;
strcpy(tag[nt], "FoF_TimeBetFoF");
addr[nt] = &All.FoF_TimeBetFoF;
id[nt++] = DOUBLE;
strcpy(tag[nt], "FoF_SnapshotFileBase");
addr[nt] = All.FoF_SnapshotFileBase;
id[nt++] = STRING;
strcpy(tag[nt], "FoF_StarFormationType");
addr[nt] = &All.FoF_StarFormationType;
id[nt++] = INT;
#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
+
+#ifdef PERIODICOUTER
+ /*Trace Output file*/
+ strcpy(tag[nt], "TraceFile");
+ addr[nt] = All.TraceFile;
+ id[nt++] = STRING;
+
+ /*External position */
+ strcpy(tag[nt],"TracePosX");
+ addr[nt] = &All.TracePos[0];
+ id[nt++] = DOUBLE;
+
+ strcpy(tag[nt],"TracePosY");
+ addr[nt] = &All.TracePos[1];
+ id[nt++] = DOUBLE;
+
+ strcpy(tag[nt],"TracePosZ");
+ addr[nt] = &All.TracePos[2];
+ id[nt++] = DOUBLE;
+
+ /*Box Velocity*/
+ strcpy(tag[nt],"TraceVelX");
+ addr[nt] = &All.TraceVel[0];
+ id[nt++] = DOUBLE;
+
+ strcpy(tag[nt],"TraceVelY");
+ addr[nt] = &All.TraceVel[1];
+ id[nt++] = DOUBLE;
+
+ strcpy(tag[nt],"TraceVelZ");
+ addr[nt] = &All.TraceVel[2];
+ id[nt++] = DOUBLE;
+
+ /*Inertial Frame*/
+ strcpy(tag[nt],"InertialV");
+ addr[nt] = &All.InertialV;
+ id[nt++] = INT;
+#ifndef TRACE_ACC
+ /*Internal trace particle position*/
+ strcpy(tag[nt],"TracePeriodX");
+ addr[nt] = &All.TracePeriodPos[0];
+ id[nt++] = DOUBLE;
+
+ strcpy(tag[nt],"TracePeriodY");
+ addr[nt] = &All.TracePeriodPos[1];
+ id[nt++] = DOUBLE;
+
+ strcpy(tag[nt],"TracePeriodZ");
+ addr[nt] = &All.TracePeriodPos[2];
+ id[nt++] = DOUBLE;
+#endif
+
+#endif
+
+#ifdef HOT_HALO
+ strcpy(tag[nt],"HaloT");
+ addr[nt] = &All.HaloT;
+ id[nt++] = DOUBLE;
+
+ strcpy(tag[nt],"HaloPMass");
+ addr[nt] = &All.HaloPartMass;
+ id[nt++] = DOUBLE;
+
+ strcpy(tag[nt],"HaloScale");
+ addr[nt] = &All.HaloScaleFactor;
+ 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
#ifdef SYNCHRONIZE_NGB_TIMESTEP
int ti = 1;
while((ti != All.NgbFactorTimestep) && (ti!=TIMEBASE))
ti <<= 1;
if (ti==TIMEBASE)
{
if(ThisTask == 0)
{
printf("\nThe parameter NgbFactorTimestep must be a power of two\n");
printf("NgbFactorTimestep=%d is not valid\n\n",All.NgbFactorTimestep);
endrun(7);
}
}
#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/src/gravtree.c b/src/gravtree.c
index fb7de06..6d6d00c 100644
--- a/src/gravtree.c
+++ b/src/gravtree.c
@@ -1,681 +1,686 @@
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <float.h>
#include <mpi.h>
#include "allvars.h"
#include "proto.h"
/*! \file gravtree.c
* \brief main driver routines for gravitational (short-range) force computation
*
* This file contains the code for the gravitational force computation by
* means of the tree algorithm. To this end, a tree force is computed for
* all active local particles, and particles are exported to other
* processors if needed, where they can receive additional force
* contributions. If the TreePM algorithm is enabled, the force computed
* will only be the short-range part.
*/
/*! This function computes the gravitational forces for all active
* particles. If needed, a new tree is constructed, otherwise the
* dynamically updated tree is used. Particles are only exported to other
* processors when really needed, thereby allowing a good use of the
* communication buffer.
*/
void gravity_tree(void)
{
long long ntot;
int numnodes, nexportsum = 0;
int i, j, iter = 0;
int *numnodeslist, maxnumnodes, nexport, *numlist, *nrecv, *ndonelist;
double tstart, tend, timetree = 0, timecommsumm = 0, timeimbalance = 0, sumimbalance;
double ewaldcount;
double costtotal, ewaldtot, *costtreelist, *ewaldlist;
double maxt, sumt, *timetreelist, *timecommlist;
double fac, plb, plb_max, sumcomm;
#ifdef DETAILED_CPU_GRAVITY
double timetree1 = 0, timecommsumm1 = 0, timeimbalance1 = 0;
double timetree2 = 0, timecommsumm2 = 0, timeimbalance2 = 0;
double sumt1,sumt2;
double sumcomm1,sumcomm2;
double sumimbalance1,sumimbalance2;
#endif
#ifdef DETAILED_CPU_OUTPUT_IN_GRAVTREE
double *timetreelist1, *timecommlist1, *timeimbalancelist1;
double *timetreelist2, *timecommlist2, *timeimbalancelist2;
double *timeimbalancelist;
int *numpartlist;
#endif
#ifndef NOGRAVITY
int *noffset, *nbuffer, *nsend, *nsend_local;
long long ntotleft;
int ndone, maxfill, ngrp;
int k, place;
int level, sendTask, recvTask;
double ax, ay, az;
MPI_Status status;
#endif
/* set new softening lengths */
if(All.ComovingIntegrationOn)
set_softenings();
/* contruct tree if needed */
tstart = second();
if(TreeReconstructFlag)
{
if(ThisTask == 0)
printf("Tree construction.\n");
force_treebuild(NumPart);
TreeReconstructFlag = 0;
if(ThisTask == 0)
printf("Tree construction done.\n");
}
tend = second();
All.CPU_TreeConstruction += timediff(tstart, tend);
costtotal = ewaldcount = 0;
/* Note: 'NumForceUpdate' has already been determined in find_next_sync_point_and_drift() */
numlist = malloc(NTask * sizeof(int) * NTask);
MPI_Allgather(&NumForceUpdate, 1, MPI_INT, numlist, 1, MPI_INT, MPI_COMM_WORLD);
for(i = 0, ntot = 0; i < NTask; i++)
ntot += numlist[i];
free(numlist);
#ifndef NOGRAVITY
if(ThisTask == 0)
printf("Begin tree force.\n");
#ifdef SELECTIVE_NO_GRAVITY
for(i = 0; i < NumPart; i++)
if(((1 << P[i].Type) & (SELECTIVE_NO_GRAVITY)))
P[i].Ti_endstep = -P[i].Ti_endstep - 1;
#endif
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; /* beginn with this index */
ntotleft = ntot; /* particles left for all tasks together */
while(ntotleft > 0)
{
iter++;
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 < NumPart && nexport < All.BunchSizeForce - NTask; i++)
if(P[i].Ti_endstep == All.Ti_Current)
{
ndone++;
for(j = 0; j < NTask; j++)
Exportflag[j] = 0;
#ifndef PMGRID
costtotal += force_treeevaluate(i, 0, &ewaldcount);
#else
costtotal += force_treeevaluate_shortrange(i, 0);
#endif
for(j = 0; j < NTask; j++)
{
if(Exportflag[j])
{
for(k = 0; k < 3; k++)
GravDataGet[nexport].u.Pos[k] = P[i].Pos[k];
#if defined(UNEQUALSOFTENINGS) || defined(STELLAR_FLUX)
GravDataGet[nexport].Type = P[i].Type;
#ifdef ADAPTIVE_GRAVSOFT_FORGAS
if(P[i].Type == 0)
GravDataGet[nexport].Soft = SphP[i].Hsml;
#endif
#endif
GravDataGet[nexport].w.OldAcc = P[i].OldAcc;
GravDataIndexTable[nexport].Task = j;
GravDataIndexTable[nexport].Index = i;
GravDataIndexTable[nexport].SortIndex = nexport;
nexport++;
nexportsum++;
nsend_local[j]++;
}
}
}
tend = second();
timetree += timediff(tstart, tend);
#ifdef DETAILED_CPU_GRAVITY
timetree1 += timediff(tstart, tend);
#endif
qsort(GravDataIndexTable, nexport, sizeof(struct gravdata_index), grav_tree_compare_key);
for(j = 0; j < nexport; j++)
GravDataIn[j] = GravDataGet[GravDataIndexTable[j].SortIndex];
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);
#ifdef DETAILED_CPU_GRAVITY
timeimbalance1 += timediff(tstart, tend);
#endif
/* 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.BunchSizeForce)
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(&GravDataIn[noffset[recvTask]],
nsend_local[recvTask] * sizeof(struct gravdata_in), MPI_BYTE,
recvTask, TAG_GRAV_A,
&GravDataGet[nbuffer[ThisTask]],
nsend[recvTask * NTask + ThisTask] * sizeof(struct gravdata_in), MPI_BYTE,
recvTask, TAG_GRAV_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);
#ifdef DETAILED_CPU_GRAVITY
timecommsumm1 += timediff(tstart, tend);
#endif
tstart = second();
for(j = 0; j < nbuffer[ThisTask]; j++)
{
#ifndef PMGRID
costtotal += force_treeevaluate(j, 1, &ewaldcount);
#else
costtotal += force_treeevaluate_shortrange(j, 1);
#endif
}
tend = second();
timetree += timediff(tstart, tend);
#ifdef DETAILED_CPU_GRAVITY
timetree2 += timediff(tstart, tend);
#endif
tstart = second();
MPI_Barrier(MPI_COMM_WORLD);
tend = second();
timeimbalance += timediff(tstart, tend);
#ifdef DETAILED_CPU_GRAVITY
timeimbalance2 += timediff(tstart, tend);
#endif
/* 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.BunchSizeForce)
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(&GravDataResult[nbuffer[ThisTask]],
nsend[recvTask * NTask + ThisTask] * sizeof(struct gravdata_in),
MPI_BYTE, recvTask, TAG_GRAV_B,
&GravDataOut[noffset[recvTask]],
nsend_local[recvTask] * sizeof(struct gravdata_in),
MPI_BYTE, recvTask, TAG_GRAV_B, MPI_COMM_WORLD, &status);
/* add the result to the particles */
for(j = 0; j < nsend_local[recvTask]; j++)
{
place = GravDataIndexTable[noffset[recvTask] + j].Index;
for(k = 0; k < 3; k++)
P[place].GravAccel[k] += GravDataOut[j + noffset[recvTask]].u.Acc[k];
P[place].GravCost += GravDataOut[j + noffset[recvTask]].w.Ninteractions;
#ifdef STELLAR_FLUX
if (P[place].Type==0) /* only for gas */
SphP[place].EnergyFlux += GravDataOut[j + noffset[recvTask]].EnergyFlux;
#endif
}
}
}
for(j = 0; j < NTask; j++)
if((j ^ ngrp) < NTask)
nbuffer[j] += nsend[(j ^ ngrp) * NTask + j];
}
tend = second();
timecommsumm += timediff(tstart, tend);
#ifdef DETAILED_CPU_GRAVITY
timecommsumm2 += timediff(tstart, tend);
#endif
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);
/* now add things for comoving integration */
/* yr: with vacuum boundary conditions */
#ifndef PERIODIC
#ifndef PMGRID
if(All.ComovingIntegrationOn)
{
fac = 0.5 * All.Hubble * All.Hubble * All.Omega0 / All.G;
for(i = 0; i < NumPart; i++)
if(P[i].Ti_endstep == All.Ti_Current)
for(j = 0; j < 3; j++)
P[i].GravAccel[j] += fac * P[i].Pos[j];
}
#endif
#endif
for(i = 0; i < NumPart; i++)
if(P[i].Ti_endstep == All.Ti_Current)
{
#ifdef PMGRID
ax = P[i].GravAccel[0] + P[i].GravPM[0] / All.G;
ay = P[i].GravAccel[1] + P[i].GravPM[1] / All.G;
az = P[i].GravAccel[2] + P[i].GravPM[2] / All.G;
#else
ax = P[i].GravAccel[0];
ay = P[i].GravAccel[1];
az = P[i].GravAccel[2];
#endif
P[i].OldAcc = sqrt(ax * ax + ay * ay + az * az);
}
if(All.TypeOfOpeningCriterion == 1)
All.ErrTolTheta = 0; /* This will switch to the relative opening criterion for the following force computations */
/* muliply by G */
for(i = 0; i < NumPart; i++)
if(P[i].Ti_endstep == All.Ti_Current)
for(j = 0; j < 3; j++)
P[i].GravAccel[j] *= All.G;
/* Finally, the following factor allows a computation of a cosmological simulation
with vacuum energy in physical coordinates */
#ifndef PERIODIC
#ifndef PMGRID
if(All.ComovingIntegrationOn == 0)
{
fac = All.OmegaLambda * All.Hubble * All.Hubble;
for(i = 0; i < NumPart; i++)
if(P[i].Ti_endstep == All.Ti_Current)
for(j = 0; j < 3; j++)
P[i].GravAccel[j] += fac * P[i].Pos[j];
}
#endif
#endif
#ifdef SELECTIVE_NO_GRAVITY
for(i = 0; i < NumPart; i++)
if(P[i].Ti_endstep < 0)
P[i].Ti_endstep = -P[i].Ti_endstep - 1;
#endif
if(ThisTask == 0)
printf("tree is done.\n");
#else /* gravity is switched off */
for(i = 0; i < NumPart; i++)
if(P[i].Ti_endstep == All.Ti_Current)
for(j = 0; j < 3; j++)
P[i].GravAccel[j] = 0;
#endif
#ifdef OUTERPOTENTIAL
/* Add outer forces from an outer potential */
outer_forces();
#endif
+#ifdef PERIODICOUTER
+ update_traceacc();
+ update_rotang();
+ fictitious_forces();
+#endif
/* Now the force computation is finished */
/* gather some diagnostic information */
timetreelist = malloc(sizeof(double) * NTask);
timecommlist = malloc(sizeof(double) * NTask);
costtreelist = malloc(sizeof(double) * NTask);
numnodeslist = malloc(sizeof(int) * NTask);
ewaldlist = malloc(sizeof(double) * NTask);
nrecv = malloc(sizeof(int) * NTask);
#ifdef DETAILED_CPU_OUTPUT_IN_GRAVTREE
timeimbalancelist = malloc(sizeof(double) * NTask);
numpartlist = malloc(sizeof(int) * NTask);
timetreelist1 = malloc(sizeof(double) * NTask);
timecommlist1 = malloc(sizeof(double) * NTask);
timeimbalancelist1 = malloc(sizeof(double) * NTask);
timetreelist2 = malloc(sizeof(double) * NTask);
timecommlist2 = malloc(sizeof(double) * NTask);
timeimbalancelist2 = malloc(sizeof(double) * NTask);
#endif
numnodes = Numnodestree;
MPI_Gather(&costtotal, 1, MPI_DOUBLE, costtreelist, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Gather(&numnodes, 1, MPI_INT, numnodeslist, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Gather(&timetree, 1, MPI_DOUBLE, timetreelist, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Gather(&timecommsumm, 1, MPI_DOUBLE, timecommlist, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Gather(&NumPart, 1, MPI_INT, nrecv, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Gather(&ewaldcount, 1, MPI_DOUBLE, ewaldlist, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Reduce(&nexportsum, &nexport, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(&timeimbalance, &sumimbalance, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
#ifdef DETAILED_CPU_GRAVITY
MPI_Reduce(&timetree1, &sumt1, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(&timetree2, &sumt2, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(&timeimbalance1, &sumimbalance1, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(&timeimbalance2, &sumimbalance2, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(&timecommsumm1, &sumcomm1, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(&timecommsumm2, &sumcomm2, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
#endif
#ifdef DETAILED_CPU_OUTPUT_IN_GRAVTREE
MPI_Gather(&timeimbalance, 1, MPI_DOUBLE, timeimbalancelist, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Gather(&NumForceUpdate, 1, MPI_INT, numpartlist, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Gather(&timetree1, 1, MPI_DOUBLE, timetreelist1, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Gather(&timetree2, 1, MPI_DOUBLE, timetreelist2, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Gather(&timecommsumm1, 1, MPI_DOUBLE, timecommlist1, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Gather(&timecommsumm2, 1, MPI_DOUBLE, timecommlist2, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Gather(&timeimbalance1, 1, MPI_DOUBLE, timeimbalancelist1, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Gather(&timeimbalance2, 1, MPI_DOUBLE, timeimbalancelist2, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
#ifdef SPLIT_DOMAIN_USING_TIME
CPU_Gravity = timetree1;
#endif
#ifndef PY_INTERFACE
if(ThisTask == 0)
{
All.TotNumOfForces += ntot;
fprintf(FdTimings, "Step= %d t= %g dt= %g \n", All.NumCurrentTiStep, All.Time, All.TimeStep);
fprintf(FdTimings, "Nf= %d%09d total-Nf= %d%09d ex-frac= %g iter= %d\n",
(int) (ntot / 1000000000), (int) (ntot % 1000000000),
(int) (All.TotNumOfForces / 1000000000), (int) (All.TotNumOfForces % 1000000000),
nexport / ((double) ntot), iter);
/* note: on Linux, the 8-byte integer could be printed with the format identifier "%qd", but doesn't work on AIX */
fac = NTask / ((double) All.TotNumPart);
for(i = 0, maxt = timetreelist[0], sumt = 0, plb_max = 0,
maxnumnodes = 0, costtotal = 0, sumcomm = 0, ewaldtot = 0; i < NTask; i++)
{
costtotal += costtreelist[i];
sumcomm += timecommlist[i];
if(maxt < timetreelist[i])
maxt = timetreelist[i];
sumt += timetreelist[i];
plb = nrecv[i] * fac;
if(plb > plb_max)
plb_max = plb;
if(numnodeslist[i] > maxnumnodes)
maxnumnodes = numnodeslist[i];
ewaldtot += ewaldlist[i];
}
fprintf(FdTimings, "work-load balance: %g max=%g avg=%g PE0=%g\n",
maxt / (sumt / NTask), maxt, sumt / NTask, timetreelist[0]);
fprintf(FdTimings, "particle-load balance: %g\n", plb_max);
fprintf(FdTimings, "max. nodes: %d, filled: %g\n", maxnumnodes,
maxnumnodes / (All.TreeAllocFactor * All.MaxPart));
fprintf(FdTimings, "part/sec=%g | %g ia/part=%g (%g)\n", ntot / (sumt + 1.0e-20),
ntot / (maxt * NTask), ((double) (costtotal)) / ntot, ((double) ewaldtot) / ntot);
#ifdef DETAILED_CPU_OUTPUT_IN_GRAVTREE
fprintf(FdTimings, "\n gravtree\n\n");
fprintf(FdTimings, "Nupdate ");
for (i=0;i<NTask;i++)
fprintf(FdTimings, "%12d ",numpartlist[i]); /* nombre de part par proc */
fprintf(FdTimings, "\n");
fprintf(FdTimings, "costtree ");
for (i=0;i<NTask;i++)
fprintf(FdTimings, "%12g ",costtreelist[i]); /* nombre d'interactions */
fprintf(FdTimings, "\n");
fprintf(FdTimings, "timetree ");
for (i=0;i<NTask;i++)
fprintf(FdTimings, "%12g ",timetreelist[i]);
fprintf(FdTimings, "\n");
fprintf(FdTimings, "timeimbalance ");
for (i=0;i<NTask;i++)
fprintf(FdTimings, "%12g ",timeimbalancelist[i]);
fprintf(FdTimings, "\n");
fprintf(FdTimings, "timecomm ");
for (i=0;i<NTask;i++)
fprintf(FdTimings, "%12g ",timecommlist[i]);
fprintf(FdTimings, "\n");
fprintf(FdTimings, "timetree1 ");
for (i=0;i<NTask;i++)
fprintf(FdTimings, "%12g ",timetreelist1[i]);
fprintf(FdTimings, "\n");
fprintf(FdTimings, "timetree2 ");
for (i=0;i<NTask;i++)
fprintf(FdTimings, "%12g ",timetreelist2[i]);
fprintf(FdTimings, "\n");
fprintf(FdTimings, "timeimbalance1 ");
for (i=0;i<NTask;i++)
fprintf(FdTimings, "%12g ",timeimbalancelist1[i]);
fprintf(FdTimings, "\n");
fprintf(FdTimings, "timeimbalance2 ");
for (i=0;i<NTask;i++)
fprintf(FdTimings, "%12g ",timeimbalancelist2[i]);
fprintf(FdTimings, "\n");
fprintf(FdTimings, "timecomm1 ");
for (i=0;i<NTask;i++)
fprintf(FdTimings, "%12g ",timecommlist1[i]);
fprintf(FdTimings, "\n");
fprintf(FdTimings, "timecomm2 ");
for (i=0;i<NTask;i++)
fprintf(FdTimings, "%12g ",timecommlist2[i]);
fprintf(FdTimings, "\n");
fprintf(FdTimings, "\n");
#endif
fprintf(FdTimings, "\n");
fflush(FdTimings);
All.CPU_TreeWalk += sumt / NTask;
All.CPU_Imbalance += sumimbalance / NTask;
All.CPU_CommSum += sumcomm / NTask;
#ifdef DETAILED_CPU_GRAVITY
All.CPU_Gravity_TreeWalk1 += sumt1 / NTask;
All.CPU_Gravity_Imbalance1 += sumimbalance1 / NTask;
All.CPU_Gravity_CommSum1 += sumcomm1 / NTask;
All.CPU_Gravity_TreeWalk2 += sumt2 / NTask;
All.CPU_Gravity_Imbalance2 += sumimbalance2 / NTask;
All.CPU_Gravity_CommSum2 += sumcomm2 / NTask;
#endif
}
#endif /*ndef PY_INTERFACE*/
#ifdef DETAILED_CPU_OUTPUT_IN_GRAVTREE
free(timeimbalancelist2);
free(timecommlist2);
free(timetreelist2);
free(timeimbalancelist1);
free(timecommlist1);
free(timetreelist1);
free(numpartlist);
free(timeimbalancelist);
#endif
free(nrecv);
free(ewaldlist);
free(numnodeslist);
free(costtreelist);
free(timecommlist);
free(timetreelist);
}
/*! This function sets the (comoving) softening length of all particle
* types in the table All.SofteningTable[...]. We check that the physical
* softening length is bounded by the Softening-MaxPhys values.
*/
void set_softenings(void)
{
int i;
if(All.ComovingIntegrationOn)
{
if(All.SofteningGas * All.Time > All.SofteningGasMaxPhys)
All.SofteningTable[0] = All.SofteningGasMaxPhys / All.Time;
else
All.SofteningTable[0] = All.SofteningGas;
if(All.SofteningHalo * All.Time > All.SofteningHaloMaxPhys)
All.SofteningTable[1] = All.SofteningHaloMaxPhys / All.Time;
else
All.SofteningTable[1] = All.SofteningHalo;
if(All.SofteningDisk * All.Time > All.SofteningDiskMaxPhys)
All.SofteningTable[2] = All.SofteningDiskMaxPhys / All.Time;
else
All.SofteningTable[2] = All.SofteningDisk;
if(All.SofteningBulge * All.Time > All.SofteningBulgeMaxPhys)
All.SofteningTable[3] = All.SofteningBulgeMaxPhys / All.Time;
else
All.SofteningTable[3] = All.SofteningBulge;
if(All.SofteningStars * All.Time > All.SofteningStarsMaxPhys)
All.SofteningTable[4] = All.SofteningStarsMaxPhys / All.Time;
else
All.SofteningTable[4] = All.SofteningStars;
if(All.SofteningBndry * All.Time > All.SofteningBndryMaxPhys)
All.SofteningTable[5] = All.SofteningBndryMaxPhys / All.Time;
else
All.SofteningTable[5] = All.SofteningBndry;
}
else
{
All.SofteningTable[0] = All.SofteningGas;
All.SofteningTable[1] = All.SofteningHalo;
All.SofteningTable[2] = All.SofteningDisk;
All.SofteningTable[3] = All.SofteningBulge;
All.SofteningTable[4] = All.SofteningStars;
All.SofteningTable[5] = All.SofteningBndry;
}
for(i = 0; i < 6; i++)
All.ForceSoftening[i] = 2.8 * All.SofteningTable[i];
All.MinGasHsml = All.MinGasHsmlFractional * All.ForceSoftening[0];
}
/*! This function is used as a comparison kernel in a sort routine. It is
* used to group particles in the communication buffer that are going to
* be sent to the same CPU.
*/
int grav_tree_compare_key(const void *a, const void *b)
{
if(((struct gravdata_index *) a)->Task < (((struct gravdata_index *) b)->Task))
return -1;
if(((struct gravdata_index *) a)->Task > (((struct gravdata_index *) b)->Task))
return +1;
return 0;
}
diff --git a/src/init.c b/src/init.c
index 88ae0d6..03e1ae1 100644
--- a/src/init.c
+++ b/src/init.c
@@ -1,785 +1,789 @@
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <mpi.h>
#include "allvars.h"
#include "proto.h"
/*! \file init.c
* \brief Code for initialisation of a simulation from initial conditions
*/
/*! This function reads the initial conditions, and allocates storage for the
* tree. Various variables of the particle data are initialised and An intial
* domain decomposition is performed. If SPH particles are present, the inial
* SPH smoothing lengths are determined.
*/
void init(void)
{
int i, j;
double a3;
#ifdef SFR
double Mgas=0,sum_Mgas=0;
int nstars=0;
int *numlist;
#ifndef LONGIDS
unsigned int MaxID=0;
#else
unsigned long long MaxID=0;
#endif
#endif
All.Time = All.TimeBegin;
switch (All.ICFormat)
{
case 1:
#if (MAKEGLASS > 1)
seed_glass();
#else
read_ic(All.InitCondFile);
#endif
break;
case 2:
case 3:
read_ic(All.InitCondFile);
break;
default:
if(ThisTask == 0)
printf("ICFormat=%d not supported.\n", All.ICFormat);
endrun(0);
}
All.Time = All.TimeBegin;
All.Ti_Current = 0;
if(All.ComovingIntegrationOn)
{
All.Timebase_interval = (log(All.TimeMax) - log(All.TimeBegin)) / TIMEBASE;
a3 = All.Time * All.Time * All.Time;
}
else
{
All.Timebase_interval = (All.TimeMax - All.TimeBegin) / TIMEBASE;
a3 = 1;
}
if (ThisTask==0)
printf("\nMinimum Time Step (Timebase_interval) = %g \n\n", All.Timebase_interval);
set_softenings();
All.NumCurrentTiStep = 0; /* setup some counters */
All.SnapshotFileCount = 0;
if(RestartFlag == 2)
All.SnapshotFileCount = atoi(All.InitCondFile + strlen(All.InitCondFile) - 3) + 1;
#ifdef FOF
All.FoF_SnapshotFileCount = 0;
#endif
All.TotNumOfForces = 0;
All.NumForcesSinceLastDomainDecomp = 0;
if(All.ComovingIntegrationOn)
if(All.PeriodicBoundariesOn == 1)
check_omega();
All.TimeLastStatistics = All.TimeBegin - All.TimeBetStatistics;
#ifdef AGN_ACCRETION
All.TimeLastAccretion = All.TimeBegin - All.TimeBetAccretion;
All.LastMTotInRa = 0;
#endif
#ifdef BONDI_ACCRETION
All.BondiTimeLast = All.TimeBegin - All.BondiTimeBet;
#endif
#ifdef FOF
All.FoF_TimeLastFoF = All.TimeBegin - All.FoF_TimeBetFoF;
#endif
#ifdef BUBBLES
All.EnergyBubbles=0;
#endif
if(All.ComovingIntegrationOn) /* change to new velocity variable */
{
for(i = 0; i < NumPart; i++)
for(j = 0; j < 3; j++)
P[i].Vel[j] *= sqrt(All.Time) * All.Time;
}
for(i = 0; i < NumPart; i++) /* start-up initialization */
{
for(j = 0; j < 3; j++)
P[i].GravAccel[j] = 0;
#ifdef PMGRID
for(j = 0; j < 3; j++)
P[i].GravPM[j] = 0;
#endif
P[i].Ti_endstep = 0;
P[i].Ti_begstep = 0;
P[i].OldAcc = 0;
P[i].GravCost = 1;
P[i].Potential = 0;
#ifdef PARTICLE_FLAG
P[i].Flag = 0;
#endif
#ifdef TESSEL
P[i].iPref = -1; /* index of the reference particle : -1 for normal particles */
#endif
#ifdef VANISHING_PARTICLES
P[i].VanishingFlag=0;
#endif
#ifdef SFR
if (P[i].ID>MaxID)
MaxID=P[i].ID;
#endif
}
#ifdef PMGRID
All.PM_Ti_endstep = All.PM_Ti_begstep = 0;
#endif
#ifdef FLEXSTEPS
All.PresentMinStep = TIMEBASE;
for(i = 0; i < NumPart; i++) /* start-up initialization */
{
P[i].FlexStepGrp = (int) (TIMEBASE * get_random_number(P[i].ID));
}
#endif
for(i = 0; i < N_gas; i++) /* initialize sph_properties */
{
for(j = 0; j < 3; j++)
{
SphP[i].VelPred[j] = P[i].Vel[j];
SphP[i].HydroAccel[j] = 0;
#ifdef DISSIPATION_FORCES
SphP[i].DissipationForcesAccel[j] = 0;
#endif
}
SphP[i].DtEntropy = 0;
#ifdef COOLING
//SphP[i].EntropyRad = 0;
SphP[i].DtEntropyRad = 0;
SphP[i].DtEnergyRad = 0;
#endif
#ifdef DISSIPATION_FORCES
SphP[i].EnergyDissipationForces = 0;
SphP[i].DtEnergyDissipationForces = 0;
#endif
#ifdef STELLAR_FLUX
SphP[i].EnergyFlux = 0.;
#endif
#ifdef AGN_HEATING
SphP[i].EgySpecAGNHeat = 0.;
SphP[i].DtEgySpecAGNHeat = 0.;
#endif
#ifdef MULTIPHASE
#ifdef COUNT_COLLISIONS
SphP[i].StickyCollisionNumber = 0;
#endif
#endif
#ifdef FEEDBACK
SphP[i].EgySpecFeedback = 0.;
SphP[i].DtEgySpecFeedback = 0.;
SphP[i].EnergySN = 0.;
SphP[i].EnergySNrem = 0.;
SphP[i].TimeSN = 0.;
for(j = 0; j < 3; j++)
{
SphP[i].FeedbackVel[j] = 0;
}
#endif
#ifdef FEEDBACK_WIND
for(j = 0; j < 3; j++)
{
SphP[i].FeedbackWindVel[j] = 0;
}
#endif
#if defined(ART_VISCO_MM)|| defined(ART_VISCO_RO) || defined(ART_VISCO_CD)
SphP[i].ArtBulkViscConst = All.ArtBulkViscConstMin;
#ifdef ART_VISCO_CD
SphP[i].ArtBulkViscConst = 0.;
SphP[i].DiVelAccurate = 0.;
SphP[i].DiVelTemp = 0.;
#endif
#endif
#ifdef OUTPUTOPTVAR1
SphP[i].OptVar1 = 0.;
#endif
#ifdef OUTPUTOPTVAR2
SphP[i].OptVar2 = 0.;
#endif
#ifdef COMPUTE_VELOCITY_DISPERSION
for(j = 0; j < VELOCITY_DISPERSION_SIZE; j++)
SphP[i].VelocityDispersion[j] = 0.;
#endif
if(RestartFlag == 0)
{
SphP[i].Hsml = 0;
SphP[i].Density = -1;
}
#ifdef MULTIPHASE
/* here, we set the Phase, according to the SpecificEnergy and not Entropy */
if (SphP[i].Entropy > All.CriticalEgySpec)
SphP[i].Phase = GAS_SPH; /* warmer phase */
else
{
if (SphP[i].Entropy >= All.CriticalNonCollisionalEgySpec)
SphP[i].Phase = GAS_STICKY;
else
SphP[i].Phase = GAS_DARK;
}
SphP[i].StickyFlag = 0;
SphP[i].StickyTime = All.Time;
//SphP[i].StickyTime = All.Time + All.StickyIdleTime*get_random_number(P[i].ID);
#endif
#ifdef SFR
Mgas += P[i].Mass;
#endif
}
#ifdef SFR
#ifndef LONGIDS
MPI_Allreduce(&MaxID, &All.MaxID, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD);
#else
printf("MPI_Allreduce must be adapted...\n");
endrun(-77);
#endif
All.MaxID++;
RearrangeParticlesFlag=0;
if (All.StarFormationStarMass==0)
{
/* compute the mean gas mass */
MPI_Allreduce(&Mgas, &sum_Mgas, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
All.StarFormationStarMass = (sum_Mgas/All.TotN_gas) / All.StarFormationNStarsFromGas;
}
for(i = 0; i < NumPart; i++) /* initialize st_properties */
{
if (P[i].Type==ST)
nstars++;
#ifdef STELLAR_PROP
if (P[i].Type==ST)
{
if (RestartFlag==0) /* only if starting from scratch */
{
#ifndef CHIMIE_INPUT_ALL
P[i].StPIdx = i-N_gas;
StP[P[i].StPIdx].FormationTime = 0; /* bad */
StP[P[i].StPIdx].InitialMass = P[i].Mass; /* bad */
StP[P[i].StPIdx].IDProj = P[i].ID;
StP[P[i].StPIdx].Hsml = 0;
StP[P[i].StPIdx].Density = -1;
for(j = 0; j < NELEMENTS; j++)
StP[P[i].StPIdx].Metal[j] = 0.;
StP[P[i].StPIdx].Flag = 0; /*obsolete*/
#else /* here, we restart for a file already processed by gadget */
P[i].StPIdx = i-N_gas;
StP[P[i].StPIdx].Flag = 0; /*obsolete*/
#endif /* CHIMIE_INPUT_ALL */
}
if (RestartFlag==2) /* start from snapshot */
{
P[i].StPIdx = i-N_gas;
StP[P[i].StPIdx].Flag = 0; /*obsolete*/
}
StP[P[i].StPIdx].PIdx = i;
#ifdef CHECK_ID_CORRESPONDENCE
StP[P[i].StPIdx].ID = P[i].ID;
#endif
}
//else
// P[i].StPIdx = -1; /* shoud be set, however, may be a problem in domain.c --> must be corrected */
#endif // STELLAR_PROP
#ifdef CHIMIE
if (P[i].Type==0)
{
if (RestartFlag==0 && header.flag_metals==0) /* only if starting from scratch and metal block not present */
{
for(j = 0; j < NELEMENTS; j++)
{
#ifdef CHIMIE_SMOOTH_METALS
SphP[i].MassMetal[j] = (pow(10,All.InitGasMetallicity)-1e-10)*get_SolarMassAbundance(j);
#else
SphP[i].Metal[j] = (pow(10,All.InitGasMetallicity)-1e-10)*get_SolarMassAbundance(j);
#endif
//if (j==FE)
// SphP[i].Metal[j] = (pow(10,All.InitGasMetallicity)-1e-10)*All.CoolingParameters_FeHSolar;
//else
// SphP[i].Metal[j] = 0;
}
}
#ifdef CHIMIE_SMOOTH_METALS
if (RestartFlag==0 && header.flag_metals>0)
for(j = 0; j < NELEMENTS; j++)
SphP[i].MassMetal[j] = SphP[i].Metal[j];
#endif
#ifdef CHIMIE_THERMAL_FEEDBACK
SphP[i].DeltaEgySpec = 0;
SphP[i].NumberOfSNIa = 0;
SphP[i].NumberOfSNII = 0;
SphP[i].SNIaThermalTime = -1;
SphP[i].SNIIThermalTime = -1;
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
SphP[i].WindTime = All.TimeBegin-2*All.ChimieWindTime;
SphP[i].WindFlag = 0;
#endif
}
#endif /* CHIMIE */
#ifdef COOLING
#ifndef CHIMIE
All.GasMetal = (pow(10,All.InitGasMetallicity)-1e-10)*All.CoolingParameters_FeHSolar;
#endif /* CHIMIE*/
#endif /* COOLING */
#ifdef TIMESTEP_UPDATE_FOR_FEEDBACK
if (P[i].Type==0)
{
for (j=0;j<3;j++)
SphP[i].FeedbackUpdatedAccel[j] = 0;
}
#endif
}
#ifdef CHECK_ID_CORRESPONDENCE
#ifdef CHIMIE
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(333001);
}
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(333002);
}
}
if (ThisTask==0)
printf("Check id correspondence before decomposition done...\n");
#endif // CHIMIE
#endif // CHECK_ID_CORRESPONDENCE
/* here, we would like to reduce N_stars to TotN_stars */
/* MPI_Allreduce(&N_stars, &All.TotN_stars, 1, MPI_LONG_LONG, MPI_SUM, MPI_COMM_WORLD); does not works */
numlist = malloc(NTask * sizeof(int) * NTask);
MPI_Allgather(&N_stars, 1, MPI_INT, numlist, 1, MPI_INT, MPI_COMM_WORLD);
for(i = 0, All.TotN_stars = 0; i < NTask; i++)
All.TotN_stars += numlist[i];
free(numlist);
if(ThisTask == 0)
{
printf("Total number of star particles : %d%09d\n\n",(int) (All.TotN_stars / 1000000000), (int) (All.TotN_stars % 1000000000));
fflush(stdout);
}
#endif /*SFR*/
ngb_treeallocate(MAX_NGB);
force_treeallocate(All.TreeAllocFactor * All.MaxPart, All.MaxPart);
All.NumForcesSinceLastDomainDecomp = 1 + All.TotNumPart * All.TreeDomainUpdateFrequency;
Flag_FullStep = 1; /* to ensure that Peano-Hilber order is done */
domain_Decomposition(); /* do initial domain decomposition (gives equal numbers of particles) */
ngb_treebuild(); /* will build tree */
setup_smoothinglengths();
#ifdef CHIMIE
#ifndef CHIMIE_INPUT_ALL
stars_setup_smoothinglengths();
#endif
#endif
#ifdef TESSEL
setup_searching_radius();
#endif
TreeReconstructFlag = 1;
/* at this point, the entropy variable normally contains the
* internal energy, read in from the initial conditions file, unless the file
* explicitly signals that the initial conditions contain the entropy directly.
* Once the density has been computed, we can convert thermal energy to entropy.
*/
#ifndef DENSITY_INDEPENDENT_SPH /* in this case, entropy is correctely defined in setup_smoothinglengths */
#ifndef ISOTHERM_EQS
if(header.flag_entropy_instead_u == 0)
{
for(i = 0; i < N_gas; i++)
{
#ifdef MULTIPHASE
{
switch(SphP[i].Phase)
{
case GAS_SPH:
SphP[i].Entropy = GAMMA_MINUS1 * SphP[i].Entropy / pow(SphP[i].Density / a3, GAMMA_MINUS1);
break;
case GAS_STICKY:
break;
case GAS_DARK:
SphP[i].Entropy = -SphP[i].Entropy;
break;
}
}
#else
SphP[i].Entropy = GAMMA_MINUS1 * SphP[i].Entropy / pow(SphP[i].Density / a3, GAMMA_MINUS1);
#endif
}
}
#endif
#endif /* DENSITY_INDEPENDENT_SPH */
#ifdef ENTROPYPRED
for(i = 0; i < N_gas; i++)
SphP[i].EntropyPred = SphP[i].Entropy;
#endif
+#ifdef TRACE_ACC
+ trace_pos();
+#endif
+
}
/*! This routine computes the mass content of the box and compares it to the
* specified value of Omega-matter. If discrepant, the run is terminated.
*/
void check_omega(void)
{
double mass = 0, masstot, omega;
int i;
for(i = 0; i < NumPart; i++)
mass += P[i].Mass;
MPI_Allreduce(&mass, &masstot, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
omega =
masstot / (All.BoxSize * All.BoxSize * All.BoxSize) / (3 * All.Hubble * All.Hubble / (8 * M_PI * All.G));
if(fabs(omega - All.Omega0) > 1.0e-3)
{
if(ThisTask == 0)
{
printf("\n\nI've found something odd!\n");
printf
("The mass content accounts only for Omega=%g,\nbut you specified Omega=%g in the parameterfile.\n",
omega, All.Omega0);
printf("\nI better stop.\n");
fflush(stdout);
}
endrun(1);
}
}
/*! This function is used to find an initial smoothing length for each SPH
* particle. It guarantees that the number of neighbours will be between
* desired_ngb-MAXDEV and desired_ngb+MAXDEV. For simplicity, a first guess
* of the smoothing length is provided to the function density(), which will
* then iterate if needed to find the right smoothing length.
*/
void setup_smoothinglengths(void)
{
int i, j, no, p;
double a3;
if(All.ComovingIntegrationOn)
{
a3 = All.Time * All.Time * All.Time;
}
else
{
a3 = 1;
}
if(RestartFlag == 0)
{
for(i = 0; i < N_gas; i++)
{
no = Father[i];
while(10 * All.DesNumNgb * P[i].Mass > Nodes[no].u.d.mass)
{
p = Nodes[no].u.d.father;
if(p < 0)
break;
no = p;
}
#ifndef TWODIMS
SphP[i].Hsml =
pow(3.0 / (4 * M_PI) * All.DesNumNgb * P[i].Mass / Nodes[no].u.d.mass, 1.0 / 3) * Nodes[no].len;
#else
SphP[i].Hsml =
pow(1.0 / (M_PI) * All.DesNumNgb * P[i].Mass / Nodes[no].u.d.mass, 1.0 / 2) * Nodes[no].len;
#endif
}
}
#ifdef DENSITY_INDEPENDENT_SPH
/* initialization of the entropy variable is a little trickier in this version of SPH,
since we need to make sure it 'talks to' the density appropriately */
for(i = 0; i < N_gas; i++)
SphP[i].EntVarPred = pow(SphP[i].Entropy,1/GAMMA);
#endif
density(0);
#ifdef DENSITY_INDEPENDENT_SPH
if(header.flag_entropy_instead_u == 0)
{
for(j=0;j<5;j++)
{ /* since ICs give energies, not entropies, need to iterate get this initialized correctly */
for(i = 0; i < N_gas; i++)
SphP[i].EntVarPred = pow( GAMMA_MINUS1 * SphP[i].Entropy / pow(SphP[i].EgyWtDensity/a3 , GAMMA_MINUS1) ,1/GAMMA);
density(0);
}
/* convert energy into entropy */
for(i = 0; i < N_gas; i++)
SphP[i].Entropy = GAMMA_MINUS1 * SphP[i].Entropy / pow(SphP[i].EgyWtDensity/a3 , GAMMA_MINUS1);
}
#endif
}
#ifdef CHIMIE
/*! This function is used to find an initial smoothing length for each SPH
* particle. It guarantees that the number of neighbours will be between
* desired_ngb-MAXDEV and desired_ngb+MAXDEV. For simplicity, a first guess
* of the smoothing length is provided to the function density(), which will
* then iterate if needed to find the right smoothing length.
*/
void stars_setup_smoothinglengths(void)
{
int i, no, p;
if(RestartFlag == 0)
{
for(i = 0; i < NumPart; i++)
{
if(P[i].Type == ST)
{
no = Father[i];
while(10 * All.DesNumNgb * P[i].Mass > Nodes[no].u.d.mass)
{
p = Nodes[no].u.d.father;
if(p < 0)
break;
no = p;
}
#ifndef TWODIMS
StP[P[i].StPIdx].Hsml =
pow(3.0 / (4 * M_PI) * All.DesNumNgb * P[i].Mass / Nodes[no].u.d.mass, 1.0 / 3) * Nodes[no].len;
#else
StP[P[i].StPIdx].Hsml =
pow(1.0 / (M_PI) * All.DesNumNgb * P[i].Mass / Nodes[no].u.d.mass, 1.0 / 2) * Nodes[no].len;
#endif
}
}
}
stars_density();
}
#endif
/*! If the code is run in glass-making mode, this function populates the
* simulation box with a Poisson sample of particles.
*/
#if (MAKEGLASS > 1)
void seed_glass(void)
{
int i, k, n_for_this_task;
double Range[3], LowerBound[3];
double drandom, partmass;
long long IDstart;
All.TotNumPart = MAKEGLASS;
partmass = All.Omega0 * (3 * All.Hubble * All.Hubble / (8 * M_PI * All.G))
* (All.BoxSize * All.BoxSize * All.BoxSize) / All.TotNumPart;
All.MaxPart = All.PartAllocFactor * (All.TotNumPart / NTask); /* sets the maximum number of particles that may */
allocate_memory();
header.npartTotal[1] = All.TotNumPart;
header.mass[1] = partmass;
if(ThisTask == 0)
{
printf("\nGlass initialising\nPartMass= %g\n", partmass);
printf("TotNumPart= %d%09d\n\n",
(int) (All.TotNumPart / 1000000000), (int) (All.TotNumPart % 1000000000));
}
/* set the number of particles assigned locally to this task */
n_for_this_task = All.TotNumPart / NTask;
if(ThisTask == NTask - 1)
n_for_this_task = All.TotNumPart - (NTask - 1) * n_for_this_task;
NumPart = 0;
IDstart = 1 + (All.TotNumPart / NTask) * ThisTask;
/* split the temporal domain into Ntask slabs in z-direction */
Range[0] = Range[1] = All.BoxSize;
Range[2] = All.BoxSize / NTask;
LowerBound[0] = LowerBound[1] = 0;
LowerBound[2] = ThisTask * Range[2];
srand48(ThisTask);
for(i = 0; i < n_for_this_task; i++)
{
for(k = 0; k < 3; k++)
{
drandom = drand48();
P[i].Pos[k] = LowerBound[k] + Range[k] * drandom;
P[i].Vel[k] = 0;
}
P[i].Mass = partmass;
P[i].Type = 1;
P[i].ID = IDstart + i;
NumPart++;
}
}
#endif
diff --git a/src/outerpotential.c b/src/outerpotential.c
index 099a8a3..0d6a73b 100644
--- a/src/outerpotential.c
+++ b/src/outerpotential.c
@@ -1,570 +1,779 @@
+#include <dirent.h>
#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_integration.h>
+
#include "allvars.h"
#include "proto.h"
-#ifdef OUTERPOTENTIAL
-
/**************************************
*
* * * * driving functions * * *
*
***************************************/
-
+#ifdef OUTERPOTENTIAL
void init_outer_potential()
{
#ifdef NFW
init_outer_potential_nfw();
#endif
#ifdef PLUMMER
init_outer_potential_plummer();
#endif
#ifdef MIYAMOTONAGAI
init_outer_potential_miyamotonagai();
#endif
#ifdef PISOTHERM
init_outer_potential_pisotherm();
#endif
#ifdef CORIOLIS
init_outer_potential_coriolis();
#endif
+
+#ifdef EVOLVE_POT
+ init_outer_potential_evolve();
+#endif
}
void outer_forces()
+{
+
+ int i,j;
+#ifdef EVOLVE_POT
+ interp_evolve_vals();
+#endif
+ for(i = 0; i < NumPart; i++)
+ {
+ if(P[i].Ti_endstep == All.Ti_Current)
+ {
+
+ FLOAT pos[3] = {}, vel[3] = {}, acc[3] = {};
+
+#ifdef PERIODICOUTER //The position is (the internal position - the origin of the tracer particle)*rotated to the galactic axis + tracer particle
+ double posquat[4] = {P[i].Pos[0] - All.TracePeriodPos[0],P[i].Pos[1] - All.TracePeriodPos[1],P[i].Pos[2] - All.TracePeriodPos[2],0};
+ double velquat[4] = {P[i].Vel[0],P[i].Vel[1],P[i].Vel[2],0};
+
+ quatrot(posquat,posquat,All.TraceQuat);
+ quatrot(velquat,velquat,All.TraceQuat);
+
+
+ for(j = 0; j<3; j++) //Last entry of posbase should be 0, so can ignore
+ {
+ pos[j] = posquat[j] + All.TracePos[j] ; //Having it have a position makes it easier to calculate initial velocity
+
+ vel[j] = velquat[j] + All.TraceVel[j];
+ }
+#else //Position is just the position
+ for( j = 0; j<3; j++)
+ {
+ pos[j] = P[i].Pos[j];
+ vel[j] = P[i].Vel[j];
+ }
+#endif
+
+
+ forces_potentials(pos,vel,acc); //Calculate acceleration
+
+#ifdef PERIODICOUTER //Remove acceleration of the tracer
+ FLOAT rotpos[3];
+ double accquat[4] = {};
+ for( j = 0; j<3; j++)
+ {
+ acc[j] -= All.TraceAcc[j];
+ accquat[j] = acc[j];
+ }
+
+ quatrot(accquat,accquat,All.TraceQuatConj); //Rotate back
+
+for( j=0;j<3;j++)
+ {
+ acc[j] = accquat[j];
+ }
+
+#endif
+
+ for( j = 0; j<3; j++)
+ {
+ P[i].GravAccel[j] += acc[j]; //Add final acceleration to the gravaccel
+ }
+
+ }
+
+ }
+}
+
+
+void forces_potentials(FLOAT pos[3],FLOAT vel[3],FLOAT acc[3])
{
#ifdef NFW
- outer_forces_nfw();
+ outer_forces_nfw(pos,acc);
#endif
#ifdef PLUMMER
- outer_forces_plummer();
+ outer_forces_plummer(pos,acc);
#endif
#ifdef PISOTHERM
- outer_forces_pisotherm();
+ outer_forces_pisotherm(pos,acc);
#endif
-
+
#ifdef MIYAMOTONAGAI
- outer_forces_miyamotonagai();
+ outer_forces_miyamotonagai(pos,acc);
#endif
-
+
#ifdef CORIOLIS
- outer_forces_coriolis();
+ outer_forces_coriolis(pos,vel,acc);
#endif
+#ifdef EVOLVE_POT
+ outer_forces_evolve(pos,acc);
+#endif
}
-void outer_potential()
+
+void outer_potential()
{
+ int i,j;
+#ifdef EVOLVE_POT
+ interp_evolve_vals();
+#endif
+
+ for (i= 0; i < NumPart; i++)
+ {
+ FLOAT pos[3];
+ FLOAT Phi[1] = {};
+#ifdef PERIODICOUTER //Add the tracer particle position to get the real radius
+ double posquat[4] = {P[i].Pos[0] - All.TracePeriodPos[0],P[i].Pos[1] - All.TracePeriodPos[1],P[i].Pos[2] - All.TracePeriodPos[2],0};
+
+ quatrot(posquat,posquat,All.TraceQuat);
+ for(j=0 ; j<3; j++)
+ {
+ pos[j] = posquat[j] + All.TracePos[j];
+ }
+#else
+ for(j=0 ; j<3; j++)
+ {
+ pos[j] = P[i].Pos[j];
+ }
+#endif
+
+ potential_components(pos,Phi);
+ /* !!! do not forget do multiply by 2 (Springel choice ?) !!! */
+
+ P[i].Potential = P[i].Potential + 2*Phi[0];
+ }
+
+}
+
+void potential_components(FLOAT pos[3], FLOAT Phi[1])
+{
#ifdef NFW
- outer_potential_nfw();
+ outer_potential_nfw(pos,Phi);
#endif
#ifdef PLUMMER
- outer_potential_plummer();
+ outer_potential_plummer(pos,Phi);
#endif
#ifdef MIYAMOTONAGAI
- outer_potential_miyamotonagai();
+ outer_potential_miyamotonagai(pos,Phi);
#endif
#ifdef PISOTHERM
- outer_potential_pisotherm();
+ outer_potential_pisotherm(pos,Phi);
#endif
#ifdef CORIOLIS
- outer_potential_coriolis();
+ outer_potential_coriolis(pos,Phi);
#endif
+#ifdef EVOLVE_POT
+ outer_potential_evolve(pos,Phi);
+#endif
}
-
#ifdef NFW
/****************************
*
* * * * NFW * * *
*
*****************************/
/*! \file phase.c
* \brief Compute forces and potential from the outer potential
*
*/
/*! init outer potential constantes
*
*/
void init_outer_potential_nfw()
{
double rhoc;
-
All.HaloMass = All.HaloMass / All.UnitMass_in_g;
All.HaloMass = All.HaloMass*SOLAR_MASS; /* from Msolar in user units */
All.NFWPotentialCte = (1.-All.GasMassFraction) * All.G*All.HaloMass/(log(1+All.HaloConcentration) - All.HaloConcentration/(1+All.HaloConcentration));
/* here, convert HubbleParam in 1/(unit_time) */
rhoc = pow(All.HubbleParam*HUBBLE*All.UnitTime_in_s,2)*3/(8*PI*All.G);
All.Rs = pow(( All.HaloMass/(4/3.*PI*200*rhoc) ),(1./3.)) / All.HaloConcentration;
- printf("\nRs (internal units) = %g\n", All.Rs);
-
}
/*! compute forces du to the outer potential
*
*/
-void outer_forces_nfw()
+void outer_forces_nfw(FLOAT pos[3], FLOAT acc[3])
{
- int i;
- FLOAT accx, accy, accz;
- FLOAT r,dPhi;
-
- for(i = 0; i < NumPart; i++)
- {
- if(P[i].Ti_endstep == All.Ti_Current)
- {
-
- r = sqrt(P[i].Pos[0]*P[i].Pos[0] + P[i].Pos[1]*P[i].Pos[1] + P[i].Pos[2]*P[i].Pos[2]);
- dPhi = - All.NFWPotentialCte * ( log(1+r/All.Rs) - r/(All.Rs+r) ) / (r*r);
+ FLOAT dPhi, r;
+ int j;
+ r = sqrt(pos[0]*pos[0]+pos[1]*pos[1]+pos[2]*pos[2]);
+ dPhi = -All.NFWPotentialCte * ( log(1+r/All.Rs) - r/(All.Rs+r) ) / (r*r);
- accx = dPhi * P[i].Pos[0]/r;
- accy = dPhi * P[i].Pos[1]/r;
- accz = dPhi * P[i].Pos[2]/r;
-
- /*
- if (P[i].ID==8)
- {
- printf("------> x=%g y=%g z=%g ax=%g ay=%g az=%g r=%g\n",P[i].Pos[0],P[i].Pos[1],P[i].Pos[2],accx,accy,accz,r);
- printf("------> x=%g y=%g z=%g ax=%g ay=%g az=%g\n",P[i].Pos[0],P[i].Pos[1],P[i].Pos[2],P[i].GravAccel[0],P[i].GravAccel[1],P[i].GravAccel[2]);
- }
- */
-
-
- P[i].GravAccel[0] = P[i].GravAccel[0] + accx;
- P[i].GravAccel[1] = P[i].GravAccel[1] + accy;
- P[i].GravAccel[2] = P[i].GravAccel[2] + accz;
- }
- }
+ for(j = 0; j < 3; j++)
+ {
+ acc[j] += dPhi * pos[j]/r;
+ }
+
}
+
+
/*! compute outer potential
*
*/
-void outer_potential_nfw()
+void outer_potential_nfw(FLOAT pos[3], FLOAT Phi[1])
{
- int i;
- FLOAT r,Phi;
-
- for(i = 0; i < NumPart; i++)
- {
- r = sqrt(P[i].Pos[0]*P[i].Pos[0] + P[i].Pos[1]*P[i].Pos[1] + P[i].Pos[2]*P[i].Pos[2]);
- Phi = - All.NFWPotentialCte * (log(1+r/All.Rs) / r);
-
- /*
- if (P[i].ID==8)
- {
- printf("------> x=%g y=%g z=%g Phi=%g\n",P[i].Pos[0],P[i].Pos[1],P[i].Pos[2],Phi);
- printf("------> x=%g y=%g z=%g Phi=%g\n",P[i].Pos[0],P[i].Pos[1],P[i].Pos[2],P[i].Potential);
- }
- */
-
-
- /* !!! do not forget do multiply by 2 (Springel choice ?) !!! */
- P[i].Potential = P[i].Potential + 2*Phi;
- }
+ FLOAT r;
+ r = sqrt(pos[0]*pos[0] + pos[1]*pos[1] + pos[2]*pos[2]);
+ Phi[0] += - All.NFWPotentialCte * (log(1+r/All.Rs) / r);
}
-
+
#endif
-
+
#ifdef PLUMMER
/****************************
*
* * * * PLUMMER * * *
*
*****************************/
/*! \file phase.c
* \brief Compute forces and potential from the outer potential
*
*/
/*! init outer potential constantes
*
*/
void init_outer_potential_plummer()
{
All.PlummerPotentialCte = All.G*All.PlummerMass /All.UnitMass_in_g *SOLAR_MASS; /* from Msolar in user units */
}
/*! compute forces due to the outer potential
*
*/
-void outer_forces_plummer()
+void outer_forces_plummer(FLOAT pos[3], FLOAT acc[3])
{
- int i;
- FLOAT accx, accy, accz;
FLOAT r,dPhi;
-
- for(i = 0; i < NumPart; i++)
+ int j;
+ r = sqrt(pos[0]*pos[0] + pos[1]*pos[1] + pos[2]*pos[2]);
+ dPhi = - All.PlummerPotentialCte / pow(r*r+All.PlummerSoftenning*All.PlummerSoftenning,1.5)*r;
+
+ for(j = 0; j<3; j++)
{
- if(P[i].Ti_endstep == All.Ti_Current)
- {
-
- r = sqrt(P[i].Pos[0]*P[i].Pos[0] + P[i].Pos[1]*P[i].Pos[1] + P[i].Pos[2]*P[i].Pos[2]);
- dPhi = - All.PlummerPotentialCte / pow(r*r+All.PlummerSoftenning*All.PlummerSoftenning,1.5)*r;
-
- accx = dPhi * P[i].Pos[0]/r;
- accy = dPhi * P[i].Pos[1]/r;
- accz = dPhi * P[i].Pos[2]/r;
-
-
- P[i].GravAccel[0] = P[i].GravAccel[0] + accx;
- P[i].GravAccel[1] = P[i].GravAccel[1] + accy;
- P[i].GravAccel[2] = P[i].GravAccel[2] + accz;
- }
+ acc[j] += dPhi * pos[j]/r;
}
+
}
/*! compute outer potential
*
*/
-void outer_potential_plummer()
+void outer_potential_plummer(FLOAT pos[3], FLOAT Phi[1])
{
- int i;
- FLOAT r,Phi;
+ FLOAT r;
+
+ r = sqrt(pos[0]*pos[0] + pos[1]*pos[1] + pos[2]*pos[2]);
+ Phi[0] += - All.PlummerPotentialCte / pow(r*r+All.PlummerSoftenning*All.PlummerSoftenning,0.5);
+
- for(i = 0; i < NumPart; i++)
- {
- r = sqrt(P[i].Pos[0]*P[i].Pos[0] + P[i].Pos[1]*P[i].Pos[1] + P[i].Pos[2]*P[i].Pos[2]);
- Phi = - All.PlummerPotentialCte / pow(r*r+All.PlummerSoftenning*All.PlummerSoftenning,0.5);
-
-
-
- /* !!! do not forget do multiply by 2 (Springel choice ?) !!! */
- P[i].Potential = P[i].Potential + 2*Phi;
- }
}
#endif
#ifdef MIYAMOTONAGAI
/****************************
*
* * * * MIYAMOTONAGAI * * *
*
*****************************/
/*! \file phase.c
* \brief Compute forces and potential from the outer potential
*
*/
/*! init outer potential constantes
*
*/
void init_outer_potential_miyamotonagai()
{
All.MiyamotoNagaiPotentialCte = All.G*All.MiyamotoNagaiMass /All.UnitMass_in_g *SOLAR_MASS; /* from Msolar in user units */
}
/*! compute forces due to the outer potential
*
*/
-void outer_forces_miyamotonagai()
+void outer_forces_miyamotonagai(FLOAT pos[3], FLOAT acc[3])
{
- int i;
- FLOAT accx, accy, accz;
FLOAT r,dPhi;
-
- for(i = 0; i < NumPart; i++)
- {
- if(P[i].Ti_endstep == All.Ti_Current)
- {
-
- r = sqrt(P[i].Pos[0]*P[i].Pos[0] + P[i].Pos[1]*P[i].Pos[1] + P[i].Pos[2]*P[i].Pos[2]);
- dPhi = - All.MiyamotoNagaiPotentialCte / pow(r*r+All.MiyamotoNagaiHr*All.MiyamotoNagaiHr,1.5)*r;
+ int j;
+ r = sqrt(pos[0]*pos[0] + pos[1]*pos[1] + pos[2]*pos[2]);
+ dPhi = - All.MiyamotoNagaiPotentialCte / pow(r*r+All.MiyamotoNagaiHr*All.MiyamotoNagaiHr,1.5)*r;
- accx = dPhi * P[i].Pos[0]/r;
- accy = dPhi * P[i].Pos[1]/r;
- accz = dPhi * P[i].Pos[2]/r;
- P[i].GravAccel[0] = P[i].GravAccel[0] + accx;
- P[i].GravAccel[1] = P[i].GravAccel[1] + accy;
- P[i].GravAccel[2] = P[i].GravAccel[2] + accz;
- }
+ for(j = 0; j<3; j++)
+ {
+ acc[j] += dPhi * pos[j]/r;
}
+
}
/*! compute outer potential
*
*/
-void outer_potential_miyamotonagai()
+void outer_potential_miyamotonagai(FLOAT pos[3], FLOAT Phi[1])
{
- int i;
- FLOAT r,Phi;
- for(i = 0; i < NumPart; i++)
- {
- r = sqrt(P[i].Pos[0]*P[i].Pos[0] + P[i].Pos[1]*P[i].Pos[1] + P[i].Pos[2]*P[i].Pos[2]);
- Phi = - All.MiyamotoNagaiPotentialCte / pow(r*r+All.MiyamotoNagaiHr*All.MiyamotoNagaiHr,0.5);
+ FLOAT r;
+
+ r = sqrt(pos[0]*pos[0] + pos[1]*pos[1] + pos[2]*pos[2]);
+ Phi[0] += - All.MiyamotoNagaiPotentialCte / pow(r*r+All.MiyamotoNagaiHr*All.MiyamotoNagaiHr,0.5);
-
-
- /* !!! do not forget do multiply by 2 (Springel choice ?) !!! */
- P[i].Potential = P[i].Potential + 2*Phi;
- }
+
}
#endif
#ifdef PISOTHERM
/**********************************************
*
* * * * PSEUDO ISOTHERM POTENTIAL * * *
*
***********************************************/
/*! \file phase.c
* \brief Compute forces and potential from the outer potential
*
*/
/*! init outer potential constantes
*
*/
void init_outer_potential_pisotherm()
{
All.PisothermPotentialCte = 4*PI*All.Rho0*pow(All.Rc,3) *All.G *(1.-All.GasMassFraction);
All.Potentialw = gsl_integration_workspace_alloc (1000);
All.PotentialF.function = &potential_f;
/* potential normalisation */
/*All.PotentialInf = All.PisothermPotentialCte/All.Rc; viriel Pfen. */
All.PotentialInf = 3.3263051716357208; /* in order to have 2Uint = Epot */
}
/*! potential function
*
*/
double potential_f (double r, void * params)
{
double f = All.PisothermPotentialCte*(r/All.Rc-atan(r/All.Rc))/(r*r);
return f;
}
/*! potential function
*
*/
double get_potential(double r)
{
double result, error;
gsl_integration_qags (&All.PotentialF, 0, r, 0, 1e-5, 1000, All.Potentialw, &result, &error);
return result;
}
/*! compute forces du to the outer potential
*
*/
-void outer_forces_pisotherm()
+void outer_forces_pisotherm(FLOAT pos[3], FLOAT acc[3])
{
- int i;
- FLOAT accx, accy, accz;
+
FLOAT r,dPhi;
-
- for(i = 0; i < NumPart; i++)
+ int j;
+ r = sqrt(pos[0]*pos[0] + pos[1]*pos[1] + pos[2]*pos[2]);
+ dPhi = - All.PisothermPotentialCte * ( r/All.Rc - atan(r/All.Rc) ) / (r*r);
+
+ for(j = 0; j < 3; j++)
{
- if(P[i].Ti_endstep == All.Ti_Current)
- {
-
- r = sqrt(P[i].Pos[0]*P[i].Pos[0] + P[i].Pos[1]*P[i].Pos[1] + P[i].Pos[2]*P[i].Pos[2]);
- dPhi = - All.PisothermPotentialCte * ( r/All.Rc - atan(r/All.Rc) ) / (r*r);
-
- accx = dPhi * P[i].Pos[0]/r;
- accy = dPhi * P[i].Pos[1]/r;
- accz = dPhi * P[i].Pos[2]/r;
-
-
- P[i].GravAccel[0] = P[i].GravAccel[0] + accx;
- P[i].GravAccel[1] = P[i].GravAccel[1] + accy;
- P[i].GravAccel[2] = P[i].GravAccel[2] + accz;
- }
- }
+ acc[j] += dPhi * pos[j]/r;
+ }
+
}
/*! compute outer potential
*
*/
-void outer_potential_pisotherm()
+void outer_potential_pisotherm(FLOAT pos[3], FLOAT Phi[1])
{
- int i;
- FLOAT Phi;
FLOAT r;
- for(i = 0; i < NumPart; i++)
- {
- r = sqrt(P[i].Pos[0]*P[i].Pos[0] + P[i].Pos[1]*P[i].Pos[1] + P[i].Pos[2]*P[i].Pos[2]);
- Phi = get_potential(r)-All.PotentialInf;
-
- /* !!! do not forget do multiply by 2 (Springel choice ?) !!! */
- P[i].Potential = P[i].Potential + 2*Phi;
- }
+ r = sqrt(pos[0]*pos[0] + pos[1]*pos[1] + pos[2]*pos[2]);
+ Phi[0] += get_potential(r)-All.PotentialInf;
+
}
-
+
#endif
-
+
#ifdef CORIOLIS
/****************************
*
* * * * CORIOLIS * * *
*
*****************************/
/*! \file phase.c
* \brief Compute forces and potential from the outer potential
*
*/
/*! init outer potential constantes
*
*/
void init_outer_potential_coriolis()
{
set_outer_potential_coriolis();
}
void set_outer_potential_coriolis()
{
double amp;
double CoriolisTime = 1000;
amp = All.Time/CoriolisTime;
if (amp>1)
amp = 1;
All.CoriolisOmegaX = All.CoriolisOmegaX0*amp;
All.CoriolisOmegaY = All.CoriolisOmegaY0*amp;
All.CoriolisOmegaZ = All.CoriolisOmegaZ0*amp;
printf("coriolis CoriolisOmegaZ = %g\n",All.CoriolisOmegaZ);
}
-
+
/*! compute forces due to the outer potential
*
*/
-void outer_forces_coriolis()
+void outer_forces_coriolis(FLOAT pos[3], FLOAT acc[3])
{
- int i;
- FLOAT accx, accy, accz;
-
- for(i = 0; i < NumPart; i++)
- {
- if(P[i].Ti_endstep == All.Ti_Current)
- {
-
- accx = pow(All.CoriolisOmegaZ,2)*P[i].Pos[0] - All.CoriolisOmegaZ*P[i].Vel[1];
- accy = pow(All.CoriolisOmegaZ,2)*P[i].Pos[1] + All.CoriolisOmegaZ*P[i].Vel[0];
- accz = 0;
-
-
- P[i].GravAccel[0] = P[i].GravAccel[0] + accx;
- P[i].GravAccel[1] = P[i].GravAccel[1] + accy;
- P[i].GravAccel[2] = P[i].GravAccel[2] + accz;
- }
- }
+ acc[0] += pow(All.CoriolisOmegaZ,2)*pos[0] - All.CoriolisOmegaZ*P[i].Vel[1];
+ acc[1] += pow(All.CoriolisOmegaZ,2)*pos[1] + All.CoriolisOmegaZ*P[i].Vel[0];
}
-
+
/*! compute outer potential
*
*/
-void outer_potential_coriolis()
+
+void outer_potential_coriolis(FLOAT pos[3], FLOAT Phi[1])
{
- int i;
- FLOAT r,Phi;
+ FLOAT r;
- for(i = 0; i < NumPart; i++)
- {
- r = sqrt(P[i].Pos[0]*P[i].Pos[0] + P[i].Pos[1]*P[i].Pos[1] + P[i].Pos[2]*P[i].Pos[2]);
- Phi = -0.5*pow(All.CoriolisOmegaZ*r,2);
+ r = sqrt(pos[0]*pos[0] + pos[1]*pos[1] + pos[2]*pos[2]);
+ Phi[0] += -0.5*pow(All.CoriolisOmegaZ*r,2);
+}
- /* !!! do not forget do multiply by 2 (Springel choice ?) !!! */
- P[i].Potential = P[i].Potential + 2*Phi;
+
+#endif
+
+
+#ifdef EVOLVE_POT
+/*NOTE THE FOLLOWING ASSUMES A LINUX FILE STRUCTURE*/
+/*Since we can't broadcast splines we have two choices. 1) Make every CPU calculate the spline 2) At every timestep, broadcast information evaluated from the spline. We follow option 1 here.*/
+/*Error checking is pretty terrible, i.e. nearly non-existent*/
+void init_outer_potential_evolve()
+{
+ struct dirent **potnames;
+ int npots, i, j,k,nlines,nheader;
+ int LINELENGTH = 8192;
+ char pfilename[MAXLEN_FILENAME];
+ char line[LINELENGTH];
+ char pottype[POTNAMELENGTH]; //pottype decides on the type of profile. 0 = NFW, 1 = Plummer.
+ FILE *potential;
+ FILE *potentialline;
+ double entry;
+ int nvars;
+ int coeffs = 12;
+ int order = 4;
+
+
+ /*Read folder. Count total number of entries. Create array with that many.*/
+ npots = scandir(All.PotDirect, &potnames,0,0);
+
+ /* ./ and ../ aren't potential files, so can free them automatically and remove them from the count, also if the files are hidden well its their own fdamn fault*/
+ free(potnames[0]);
+ free(potnames[1]);
+ npots -= 2;
+
+ if(npots > MAXPOTFILE)
+ {
+ if(ThisTask == 0)
+ printf("\nNumber of potentials %d > MAXPOTFILE %d\n",npots,MAXPOTFILE);\
+ endrun(5000);
+ }
+
+ /*For each potential file, need to interpolate all the variables used throughout, e.g. Mvir, Rvir, Rs for NFW.*/
+ for(i=0;i<npots;i++)
+ {
+ sprintf(pfilename,"%s/%s",All.PotDirect,potnames[i+2]->d_name);
+ /*Open the potential file*/
+ potential = fopen(pfilename,"r");
+ free(potnames[i+2]);
+
+ nlines = 0;
+ nheader = 0;
+ while(fgets(line,LINELENGTH,potential) != NULL)
+ {
+ /*Allow headers to exist but only at the start*/
+ if(nlines == 0 && &line[0] == "#")
+ nheader++;
+ else
+ nlines++;
+ }
+ rewind(potential); /*Have the number of lines, so move back to start of file*/
+ nlines--; /*First non header line is the type so don't want to count it */
+ for(j=0;j<nheader;j++)
+ fgets(line,LINELENGTH,potential); /*Grab each header line so we can skip it...*/
+ fgets(line,LINELENGTH,potential); /*First line*/
+ sscanf(line,"%s",pottype);
+ if(ThisTask == 0)
+ printf("%s\n",pottype);
+ All.PotType[i] = pottype;
+ ///*How many variables are we expecting and setting potential type, don't change these just add more*/
+ //if(!strcasecmp(pottype,"NFW")) All.PotType[i] = 0;
+ //else if(!strcasecmp(pottype,"Plummer")) All.PotType[i] = 1;
+
+ nvars = NumVars(All.PotType[i]);
+ double vars[nvars+1][nlines];
+ /*Grab each lines variables and throw them into the vars array*/
+ /*Move to a file to use fscanf, since various files might have different lines*/
+ for(j=0;j<nlines;j++)
+ {
+ fgets(line,LINELENGTH,potential);
+ potentialline = fmemopen(line,strlen(line),"r");
+ for(k=0;k<nvars+1;k++)
+ fscanf(potentialline,"%lg",&vars[k][j]);
+ fclose(potentialline);
+ }
+ fclose(potential);
+
+ adapt_evolve_variables(All.PotType[i],*vars,nlines);
+ /*Interpolate each of these with respect to time which is the first column*/
+ for(j=0;j<nvars;j++)
+ {
+ All.PotSplines[i][j] = gsl_spline_alloc (gsl_interp_cspline, nlines);
+
+ gsl_spline_init(All.PotSplines[i][j],vars[0],vars[j+1],nlines);
+ }
}
+ free(potnames);
+ for(i=npots;i<MAXPOTFILE;i++)
+ {
+ All.PotType[i] = -1; //Casting int to char but it's fine...
+ }
+
+ interp_evolve_vals();
+}
+
+int NumVars(char pottype[POTNAMELENGTH])
+{
+ if(pottype == "NFW") //NFW
+ return 3;
+ else if (pottype=="Plummer") //Plummer
+ return 2;
}
-#endif
+void adapt_evolve_variables(char pottype[POTNAMELENGTH], double *vars, int nlines)
+{
+ int i,nvars;
+ if(pottype == "NFW")
+ for(i=0;i<nlines;i++)
+ {
+ nvars = 4;
+ *((vars+i)) *= SEC_PER_MEGAYEAR*1e3/All.UnitTime_in_s*All.HubbleParam; //Time in Gyr
+ *((vars+nlines+i)) *= SOLAR_MASS/All.UnitMass_in_g*All.HubbleParam; //Mvir in Msun
+ *((vars+2*nlines+i)) *= CM_PER_MPC/1e3/All.UnitLength_in_cm*All.HubbleParam; //Rvir in kpc
+ *((vars+3*nlines+i)) *= CM_PER_MPC/1e3/All.UnitLength_in_cm*All.HubbleParam; //Rs in kpc
+ }
+ else if(pottype == "Plummer")
+ for(i=0;i<nlines;i++)
+ {
+ nvars = 3;
+ *((vars+i)) *= 1000./All.UnitTime_in_Megayears*All.HubbleParam; //Time in Gyr
+ *((vars+nlines+i)) *= SOLAR_MASS/All.UnitMass_in_g*All.HubbleParam; //Mass in Msun
+ *((vars+2*nlines+i)) *= 30.857e20/All.UnitLength_in_cm*All.HubbleParam; //Softening in kpc
+ }
+}
+void interp_evolve_vals()
+{
+ gsl_interp_accel *spline_acc = gsl_interp_accel_alloc();
+ int i,j,nvars;
+ double val[MAXNVARS];
+ double work[5]; //Values to use for temp calculations need to be commented what they do
-#endif
+ for(i=0;i<MAXPOTFILE;i++)
+ {
+ if(All.PotType[i] == -1)
+ break;
+ gsl_interp_accel_reset(spline_acc);
+ nvars = NumVars(All.PotType[i]);
+ for(j=0;j<nvars;j++)
+ val[j] = gsl_spline_eval(All.PotSplines[i][j],All.Time,spline_acc);
+
+ if(All.PotType[i] == "NFW")
+ {
+ work[0] = val[1]/val[2]; //Concentration
+ All.PotVals[i][0] = All.G*val[0]/(log(1+work[0]) - work[0]/(1+work[0]));//All.NFWPotentialCte Equivalent
+ All.PotVals[i][1] = val[2];
+ }
+ else if(All.PotType[i] == "Plummer")
+ {
+ All.PotVals[i][0] = All.G*val[0];
+ All.PotVals[i][1] = val[1];
+ }
+ }
+
+ gsl_interp_accel_free(spline_acc);
+}
+void outer_potential_evolve(FLOAT pos[3], FLOAT Phi[1])
+{
+ FLOAT r;
+ int i;
+ r = sqrt(pos[0]*pos[0] + pos[1]*pos[1] + pos[2]*pos[2]);
+
+ for(i=0;i<MAXPOTFILE;i++)
+ {
+ if(All.PotType[i] == -1)
+ break;
+ if(All.PotType[i] == "NFW")
+ {
+ Phi[0] += -All.PotVals[i][0] * (log(1+r/All.PotVals[i][1])/r);
+ }
+ else if(All.PotType[i] == "Plummer")
+ {
+ Phi[0] += -All.PotVals[i][0] / pow(r*r + All.PotVals[i][1]*All.PotVals[i][1],0.5);
+ }
+ }
+}
+void outer_forces_evolve(FLOAT pos[3], FLOAT acc[3])
+{
+
+ FLOAT r,dPhi;
+ int i,j;
+ r = sqrt(pos[0]*pos[0] + pos[1]*pos[1] + pos[2]*pos[2]);
+
+ for(i=0;i<MAXPOTFILE;i++)
+ {
+ if(All.PotType[i] == -1)
+ break;
+ if(All.PotType[i] == "NFW")
+ {
+ dPhi = - All.PotVals[i][0] * ( log(1+r/All.PotVals[i][1]) - r/(All.PotVals[i][1]+r) ) / (r*r);
+ }
+ else if(All.PotType[i] == "Plummer")
+ {
+ dPhi = - All.PotVals[i][0] * ( r/All.PotVals[i][1] - atan(r/All.PotVals[i][1]) ) / (r*r);
+ }
+ for(j = 0; j < 3; j++)
+ {
+ acc[j] += dPhi * pos[j]/r;
+ }
+ }
+}
+
+
+#endif
+
+
+#endif
diff --git a/src/potential.c b/src/potential.c
index 976c3dd..8137d93 100644
--- a/src/potential.c
+++ b/src/potential.c
@@ -1,331 +1,333 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <float.h>
#include <mpi.h>
#include "allvars.h"
#include "proto.h"
/*! \file potential.c
* \brief Computation of the gravitational potential of particles
*/
/*! This function computes the gravitational potential for ALL the particles.
* First, the (short-range) tree potential is computed, and then, if needed,
* the long range PM potential is added.
*/
void compute_potential(void)
{
int i;
#ifndef NOGRAVITY
long long ntot, ntotleft;
int j, k, level, sendTask, recvTask;
int ndone;
int maxfill, ngrp, place, nexport;
int *nsend, *noffset, *nsend_local, *nbuffer, *ndonelist, *numlist;
double fac;
double t0, t1, tstart, tend;
MPI_Status status;
double r2;
t0 = second();
if(All.ComovingIntegrationOn)
set_softenings();
if(ThisTask == 0)
{
printf("Start computation of potential for all particles...\n");
fflush(stdout);
}
tstart = second();
if(TreeReconstructFlag)
{
if(ThisTask == 0)
printf("Tree construction.\n");
force_treebuild(NumPart);
TreeReconstructFlag = 0;
if(ThisTask == 0)
printf("Tree construction done.\n");
}
tend = second();
All.CPU_TreeConstruction += timediff(tstart, tend);
numlist = malloc(NTask * sizeof(int) * NTask);
MPI_Allgather(&NumPart, 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; /* beginn with this index */
ntotleft = ntot; /* particles left for all tasks together */
while(ntotleft > 0)
{
for(j = 0; j < NTask; j++)
nsend_local[j] = 0;
/* do local particles and prepare export list */
for(nexport = 0, ndone = 0; i < NumPart && nexport < All.BunchSizeForce - NTask; i++)
{
ndone++;
for(j = 0; j < NTask; j++)
Exportflag[j] = 0;
#ifndef PMGRID
force_treeevaluate_potential(i, 0);
#else
force_treeevaluate_potential_shortrange(i, 0);
#endif
for(j = 0; j < NTask; j++)
{
if(Exportflag[j])
{
for(k = 0; k < 3; k++)
GravDataGet[nexport].u.Pos[k] = P[i].Pos[k];
#ifdef UNEQUALSOFTENINGS
GravDataGet[nexport].Type = P[i].Type;
#ifdef ADAPTIVE_GRAVSOFT_FORGAS
if(P[i].Type == 0)
GravDataGet[nexport].Soft = SphP[i].Hsml;
#endif
#endif
GravDataGet[nexport].w.OldAcc = P[i].OldAcc;
GravDataIndexTable[nexport].Task = j;
GravDataIndexTable[nexport].Index = i;
GravDataIndexTable[nexport].SortIndex = nexport;
nexport++;
nsend_local[j]++;
}
}
}
qsort(GravDataIndexTable, nexport, sizeof(struct gravdata_index), grav_tree_compare_key);
for(j = 0; j < nexport; j++)
GravDataIn[j] = GravDataGet[GravDataIndexTable[j].SortIndex];
for(j = 1, noffset[0] = 0; j < NTask; j++)
noffset[j] = noffset[j - 1] + nsend_local[j - 1];
MPI_Allgather(nsend_local, NTask, MPI_INT, nsend, NTask, MPI_INT, MPI_COMM_WORLD);
/* now do the particles that need to be exported */
for(level = 1; level < (1 << PTask); level++)
{
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.BunchSizeForce)
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(&GravDataIn[noffset[recvTask]],
nsend_local[recvTask] * sizeof(struct gravdata_in), MPI_BYTE,
recvTask, TAG_POTENTIAL_A,
&GravDataGet[nbuffer[ThisTask]],
nsend[recvTask * NTask + ThisTask] * sizeof(struct gravdata_in), MPI_BYTE,
recvTask, TAG_POTENTIAL_A, MPI_COMM_WORLD, &status);
}
}
for(j = 0; j < NTask; j++)
if((j ^ ngrp) < NTask)
nbuffer[j] += nsend[(j ^ ngrp) * NTask + j];
}
for(j = 0; j < nbuffer[ThisTask]; j++)
{
#ifndef PMGRID
force_treeevaluate_potential(j, 1);
#else
force_treeevaluate_potential_shortrange(j, 1);
#endif
}
/* get the result */
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.BunchSizeForce)
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(&GravDataResult[nbuffer[ThisTask]],
nsend[recvTask * NTask + ThisTask] * sizeof(struct gravdata_in),
MPI_BYTE, recvTask, TAG_POTENTIAL_B,
&GravDataOut[noffset[recvTask]],
nsend_local[recvTask] * sizeof(struct gravdata_in),
MPI_BYTE, recvTask, TAG_POTENTIAL_B, MPI_COMM_WORLD, &status);
/* add the result to the particles */
for(j = 0; j < nsend_local[recvTask]; j++)
{
place = GravDataIndexTable[noffset[recvTask] + j].Index;
P[place].Potential += GravDataOut[j + noffset[recvTask]].u.Potential;
}
}
}
for(j = 0; j < NTask; j++)
if((j ^ ngrp) < NTask)
nbuffer[j] += nsend[(j ^ ngrp) * NTask + j];
}
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);
/* add correction to exclude self-potential */
for(i = 0; i < NumPart; i++)
{
/* remove self-potential */
P[i].Potential += P[i].Mass / All.SofteningTable[P[i].Type];
if(All.ComovingIntegrationOn)
if(All.PeriodicBoundariesOn)
P[i].Potential -= 2.8372975 * pow(P[i].Mass, 2.0 / 3) *
pow(All.Omega0 * 3 * All.Hubble * All.Hubble / (8 * M_PI * All.G), 1.0 / 3);
}
/* multiply with the gravitational constant */
for(i = 0; i < NumPart; i++)
P[i].Potential *= All.G;
#ifdef PMGRID
#ifdef PERIODIC
pmpotential_periodic();
#ifdef PLACEHIGHRESREGION
pmpotential_nonperiodic(1);
#endif
#else
pmpotential_nonperiodic(0);
#ifdef PLACEHIGHRESREGION
pmpotential_nonperiodic(1);
#endif
#endif
#endif
if(All.ComovingIntegrationOn)
{
#ifndef PERIODIC
fac = -0.5 * All.Omega0 * All.Hubble * All.Hubble;
for(i = 0; i < NumPart; i++)
{
for(k = 0, r2 = 0; k < 3; k++)
r2 += P[i].Pos[k] * P[i].Pos[k];
P[i].Potential += fac * r2;
}
#endif
}
else
{
fac = -0.5 * All.OmegaLambda * All.Hubble * All.Hubble;
if(fac != 0)
{
for(i = 0; i < NumPart; i++)
{
for(k = 0, r2 = 0; k < 3; k++)
r2 += P[i].Pos[k] * P[i].Pos[k];
P[i].Potential += fac * r2;
}
}
}
if(ThisTask == 0)
{
printf("potential done.\n");
fflush(stdout);
}
t1 = second();
All.CPU_Potential += timediff(t0, t1);
#else
for(i = 0; i < NumPart; i++)
P[i].Potential = 0;
#endif
#ifdef OUTERPOTENTIAL
/* Add contribution from an outer potential */
+#ifndef TRACE_ACC
outer_potential();
#endif
+#endif
}
diff --git a/src/predict.c b/src/predict.c
index 693dd3a..a8cae58 100644
--- a/src/predict.c
+++ b/src/predict.c
@@ -1,213 +1,235 @@
#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"
/*! \file predict.c
* \brief drift particles by a small time interval
*
* This function contains code to implement a drift operation on all the
* particles, which represents one part of the leapfrog integration scheme.
*/
/*! This function drifts all particles from the current time to the future:
* time0 - > time1
*
* If there is no explicit tree construction in the following timestep, the
* tree nodes are also drifted and updated accordingly. Note: For periodic
* boundary conditions, the mapping of coordinates onto the interval
* [0,All.BoxSize] is only done before the domain decomposition, or for
* outputs to snapshot files. This simplifies dynamic tree updates, and
* allows the domain decomposition to be carried out only every once in a
* while.
*/
void move_particles(int time0, int time1)
{
int i, j;
double dt_drift, dt_gravkick, dt_hydrokick, dt_entr;
double t0, t1;
#ifdef METAL_DIFFUSION
double eAdt;
#endif
t0 = second();
if(All.ComovingIntegrationOn)
{
dt_drift = get_drift_factor(time0, time1);
dt_gravkick = get_gravkick_factor(time0, time1);
dt_hydrokick = get_hydrokick_factor(time0, time1);
}
else
{
dt_drift = dt_gravkick = dt_hydrokick = (time1 - time0) * All.Timebase_interval;
}
for(i = 0; i < NumPart; i++)
{
for(j = 0; j < 3; j++)
P[i].Pos[j] += P[i].Vel[j] * dt_drift;
if(P[i].Type == 0)
{
#ifdef PMGRID
for(j = 0; j < 3; j++)
{
SphP[i].VelPred[j] += (P[i].GravAccel[j] + P[i].GravPM[j]) * dt_gravkick + SphP[i].HydroAccel[j] * dt_hydrokick;
}
#else
for(j = 0; j < 3; j++)
{
SphP[i].VelPred[j] += P[i].GravAccel[j] * dt_gravkick + SphP[i].HydroAccel[j] * dt_hydrokick;
}
#endif
#ifdef DISSIPATION_FORCES
for(j = 0; j < 3; j++)
{
SphP[i].VelPred[j] += SphP[i].DissipationForcesAccel[j] * dt_hydrokick;
}
#endif
SphP[i].Density *= exp(-SphP[i].DivVel * dt_drift);
SphP[i].Hsml *= exp(0.333333333333 * SphP[i].DivVel * dt_drift);
if(SphP[i].Hsml < All.MinGasHsml)
SphP[i].Hsml = All.MinGasHsml;
dt_entr = (time1 - (P[i].Ti_begstep + P[i].Ti_endstep) / 2) * All.Timebase_interval;
#ifdef DENSITY_INDEPENDENT_SPH
SphP[i].EgyWtDensity *= exp(-SphP[i].DivVel * dt_drift);
SphP[i].EntVarPred = pow(SphP[i].Entropy + SphP[i].DtEntropy * dt_entr, 1/GAMMA);
SphP[i].Pressure = (SphP[i].Entropy + SphP[i].DtEntropy * dt_entr) * pow(SphP[i].EgyWtDensity, GAMMA);
#else
SphP[i].Pressure = (SphP[i].Entropy + SphP[i].DtEntropy * dt_entr) * pow(SphP[i].Density, GAMMA);
#endif
#ifdef JEANS_PRESSURE_FLOOR
SphP[i].Pressure = dmax(SphP[i].Pressure,JeansPressureFloor(i));
#endif
#ifdef ENTROPYPRED
SphP[i].EntropyPred = (SphP[i].Entropy + SphP[i].DtEntropy * dt_entr);
#endif
#ifdef CHECK_ENTROPY_SIGN
if ((SphP[i].EntropyPred < 0)||(SphP[i].Entropy < 0))
{
printf("\ntask=%d: EntropyPred less than zero in move_particles !\n", ThisTask);
printf("ID=%d Entropy=%g EntropyPred=%g DtEntropy=%g dt_entr=%g\n",P[i].ID,SphP[i].Entropy,SphP[i].EntropyPred,SphP[i].DtEntropy,dt_entr);
fflush(stdout);
endrun(333021);
}
#endif
#ifdef NO_NEGATIVE_PRESSURE
if (SphP[i].Pressure<0)
{
printf("\ntask=%d: pressure less than zero in move_particles !\n", ThisTask);
printf("ID=%d Entropy=%g DtEntropy*dt=%g Density=%g DtEntropy=%g dt=%g\n",P[i].ID,SphP[i].Entropy,SphP[i].DtEntropy*dt_entr,SphP[i].Density,SphP[i].DtEntropy,dt_entr);
fflush(stdout);
endrun(333022);
}
#endif
/***********************************************************/
/* compute art visc coeff */
/***********************************************************/
#if defined(ART_VISCO_MM)|| defined(ART_VISCO_RO) || defined(ART_VISCO_CD)
move_art_visc(i,dt_drift);
#endif
/***********************************************************/
/* compute diffusion */
/***********************************************************/
#ifdef METAL_DIFFUSION
if(SphP[i].MetalDiffusionA!=0)
for(j = 0; j < NELEMENTS; j++)
if(SphP[i].MetalDiffusionA!=0)
{
eAdt = exp( SphP[i].MetalDiffusionA * dt_drift );
SphP[i].Metal[j] = SphP[i].Metal[j] * eAdt + SphP[i].MetalDiffusionB[j] / SphP[i].MetalDiffusionA * (1.0 - eAdt) ;
}
#endif
}
}
+#ifdef VANISHING_PARTICLES
+ vanishing_particles(time0,time1);
+#endif
+ MPI_Barrier(MPI_COMM_WORLD);
/* if domain-decomp and tree are not going to be reconstructed, update dynamically. */
if(All.NumForcesSinceLastDomainDecomp < All.TotNumPart * All.TreeDomainUpdateFrequency)
{
for(i = 0; i < Numnodestree; i++)
for(j = 0; j < 3; j++)
Nodes[All.MaxPart + i].u.d.s[j] += Extnodes[All.MaxPart + i].vs[j] * dt_drift;
force_update_len();
force_update_pseudoparticles();
}
t1 = second();
All.CPU_Predict += timediff(t0, t1);
}
/*! This function makes sure that all particle coordinates (Pos) are
* periodically mapped onto the interval [0, BoxSize]. After this function
* has been called, a new domain decomposition should be done, which will
* also force a new tree construction.
*/
#ifdef PERIODIC
void do_box_wrapping(void)
{
int i, j;
double boxsize[3];
for(j = 0; j < 3; j++)
boxsize[j] = All.BoxSize;
#ifdef LONG_X
boxsize[0] *= LONG_X;
#endif
#ifdef LONG_Y
boxsize[1] *= LONG_Y;
#endif
#ifdef LONG_Z
boxsize[2] *= LONG_Z;
#endif
-
+#ifdef PERIODICOUTER
+ FLOAT opos[3];
+ FLOAT npos[3];
+ FLOAT ovel[3];
+ double rotang[4] = {All.TraceAngular[0],All.TraceAngular[1],All.TraceAngular[2],0};
+ quatrot(rotang,rotang,All.TraceQuatConj);
+#endif
for(i = 0; i < NumPart; i++)
for(j = 0; j < 3; j++)
{
+#ifdef PERIODICOUTER
+ opos[j] = P[i].Pos[j]-All.TracePeriodPos[j];
+ ovel[j] = P[i].Vel[j];
+#endif
while(P[i].Pos[j] < 0)
P[i].Pos[j] += boxsize[j];
while(P[i].Pos[j] >= boxsize[j])
P[i].Pos[j] -= boxsize[j];
+#ifdef PERIODICOUTER
+ npos[j] = P[i].Pos[j] - All.TracePeriodPos[j];
+#endif
}
+#ifdef PERIODICOUTER
+ P[i].Vel[0] += (rotang[1]*(opos[2]-npos[2]) - rotang[2]*(opos[1]-npos[1]));
+ P[i].Vel[1] += -(rotang[0]*(opos[2]-npos[2]) - rotang[2]*(opos[0]-npos[0]));
+ P[i].Vel[2] += (rotang[0]*(opos[1]-npos[1]) - rotang[1]*(opos[0]-npos[0]));
+#endif
}
#endif
diff --git a/src/proto.h b/src/proto.h
index 3bb2570..f802e3b 100644
--- a/src/proto.h
+++ b/src/proto.h
@@ -1,718 +1,776 @@
/*! \file proto.h
* \brief this file contains all function prototypes of the code
*/
#ifndef ALLVARS_H
#include "allvars.h"
#endif
#ifdef HAVE_HDF5
#include <hdf5.h>
#endif
#ifdef COOLING_FCT_FROM_HDF5
#include <hdf5.h>
#endif
void advance_and_find_timesteps(void);
void allocate_commbuffers(void);
void allocate_memory(void);
void begrun(void);
int blockpresent(enum iofields blocknr);
#ifdef BLOCK_SKIPPING
int blockabsent(enum iofields blocknr);
#endif
void catch_abort(int sig);
void catch_fatal(int sig);
void check_omega(void);
void close_outputfiles(void);
int compare_key(const void *a, const void *b);
void compute_accelerations(int mode);
void compute_global_quantities_of_system(void);
void compute_potential(void);
int dens_compare_key(const void *a, const void *b);
void density(int mode);
void density_decouple(void);
void density_evaluate(int i, int mode);
#ifdef CHIMIE
int stars_dens_compare_key(const void *a, const void *b);
void stars_density(void);
void stars_density_evaluate(int i, int mode);
#endif
void distribute_file(int nfiles, int firstfile, int firsttask, int lasttask, int *filenr, int *master, int *last);
double dmax(double, double);
double dmin(double, double);
void do_box_wrapping(void);
void domain_Decomposition(void);
int domain_compare_key(const void *a, const void *b);
int domain_compare_key(const void *a, const void *b);
int domain_compare_toplist(const void *a, const void *b);
void domain_countToGo(void);
void domain_decompose(void);
void domain_determineTopTree(void);
void domain_exchangeParticles(int partner, int sphflag, int send_count, int recv_count);
void domain_findExchangeNumbers(int task, int partner, int sphflag, int *send, int *recv);
void domain_findExtent(void);
int domain_findSplit(int cpustart, int ncpu, int first, int last);
int domain_findSplityr(int cpustart, int ncpu, int first, int last);
void domain_shiftSplit(void);
void domain_shiftSplityr(void);
void domain_sumCost(void);
void domain_topsplit(int node, peanokey startkey);
void domain_topsplit_local(int node, peanokey startkey);
double drift_integ(double a, void *param);
void dump_particles(void);
void empty_read_buffer(enum iofields blocknr, int offset, int pc, int type);
void endrun(int);
void energy_statistics(void);
#ifdef ADVANCEDSTATISTICS
void advanced_energy_statistics(void);
#endif
void every_timestep_stuff(void);
void ewald_corr(double dx, double dy, double dz, double *fper);
void ewald_force(int ii, int jj, int kk, double x[3], double force[3]);
void ewald_init(void);
double ewald_pot_corr(double dx, double dy, double dz);
double ewald_psi(double x[3]);
void fill_Tab_IO_Labels(void);
void fill_write_buffer(enum iofields blocknr, int *pindex, int pc, int type);
void find_dt_displacement_constraint(double hfac);
int find_files(char *fname);
int find_next_outputtime(int time);
void find_next_sync_point_and_drift(void);
void force_create_empty_nodes(int no, int topnode, int bits, int x, int y, int z, int *nodecount, int *nextfree);
void force_exchange_pseudodata(void);
void force_flag_localnodes(void);
void force_insert_pseudo_particles(void);
void force_setupnonrecursive(int no);
void force_treeallocate(int maxnodes, int maxpart);
int force_treebuild(int npart);
int force_treebuild_single(int npart);
int force_treeevaluate(int target, int mode, double *ewaldcountsum);
int force_treeevaluate_direct(int target, int mode);
int force_treeevaluate_ewald_correction(int target, int mode, double pos_x, double pos_y, double pos_z, double aold);
void force_treeevaluate_potential(int target, int type);
void force_treeevaluate_potential_shortrange(int target, int mode);
int force_treeevaluate_shortrange(int target, int mode);
void force_treefree(void);
void force_treeupdate_pseudos(void);
void force_update_hmax(void);
void force_update_len(void);
void force_update_node(int no, int flag);
void force_update_node_hmax_local(void);
void force_update_node_hmax_toptree(void);
void force_update_node_len_local(void);
void force_update_node_len_toptree(void);
void force_update_node_recursive(int no, int sib, int father);
void force_update_pseudoparticles(void);
void force_update_size_of_parent_node(int no);
void free_memory(void);
int get_bytes_per_blockelement(enum iofields blocknr);
void get_dataset_name(enum iofields blocknr, char *buf);
int get_datatype_in_block(enum iofields blocknr);
double get_drift_factor(int time0, int time1);
double get_gravkick_factor(int time0, int time1);
double get_hydrokick_factor(int time0, int time1);
int get_particles_in_block(enum iofields blocknr, int *typelist);
double get_random_number(int id);
#ifdef SFR
double get_StarFormation_random_number(int id);
#endif
#ifdef FEEDBACK_WIND
double get_FeedbackWind_random_number(int id);
#endif
#ifdef CHIMIE
double get_Chimie_random_number(int id);
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
double get_ChimieKineticFeedback_random_number(int id);
#endif
#ifdef GAS_ACCRETION
double get_gasAccretion_random_number(int id);
void update_entropy_for_accreated_particles(void);
void allocate_gas_accretion(void);
#endif
-#ifdef VANISHING_PARTICLES
-void vanishing_particles(void);
-void vanishing_particles_flag(void);
+
+#ifdef HOT_HALO
+void Halo_order_particles_using_mass(void);
+void Halo_reorder_particles_using_mass(void);
+void allocate_accretion(void);
+void init_accretion(void);
+#endif
+#ifdef TRACE_ACC
+void trace_pos(void);
+int pot_ind_compare_key(const void *a, const void *b);
+int pot_tasks_compare_key(const void *a, const void *b);
+#endif
+
+#if defined(VANISHING_PARTICLES)|| defined(MERGE_SPLIT)
void vanishing_particles_remove(void);
+int compact_StP(int oldN_stars);
#endif
+#ifdef VANISHING_PARTICLES
+void vanishing_particles(int time0, int time1);
+void vanishing_particles_flag(int time0, int time1);
+#endif
+
+
int get_timestep(int p, double *a, int flag);
int get_values_per_blockelement(enum iofields blocknr);
#ifdef SYNCHRONIZE_NGB_TIMESTEP
void synchronize_ngb_timestep();
int synchronize_ngb_timestep_evaluate(int target, int mode);
int synchronize_ngb_timestep_compare_key(const void *a, const void *b);
#endif
int grav_tree_compare_key(const void *a, const void *b);
void gravity_forcetest(void);
void gravity_tree(void);
void gravity_tree_shortrange(void);
double gravkick_integ(double a, void *param);
int hydro_compare_key(const void *a, const void *b);
void hydro_evaluate(int target, int mode);
void hydro_force(void);
double hydrokick_integ(double a, void *param);
int imax(int, int);
int imin(int, int);
void init(void);
void init_drift_table(void);
void init_peano_map(void);
#ifdef COSMICTIME
void init_cosmictime_table(void);
double get_cosmictime_difference(int time0, int time1);
void init_full_cosmictime_table(void);
double get_da_from_dt(double a, double dt);
double get_dt_from_da(double a, double da);
double get_CosmicTime_from_a(double a);
double get_a_from_CosmicTime(double t);
double get_Redshift_from_a(double a);
double get_a_from_Redshift(double z);
#endif
void long_range_force(void);
void long_range_init(void);
void long_range_init_regionsize(void);
void move_particles(int time0, int time1);
size_t my_fread(void *ptr, size_t size, size_t nmemb, FILE * stream);
size_t my_fwrite(void *ptr, size_t size, size_t nmemb, FILE * stream);
int ngb_clear_buf(FLOAT searchcenter[3], FLOAT hguess, int numngb);
void ngb_treeallocate(int npart);
void ngb_treebuild(void);
int ngb_treefind_pairs(FLOAT searchcenter[3], FLOAT hsml, int phase, int *startnode);
#ifdef MULTIPHASE
int ngb_treefind_phase_pairs(FLOAT searchcenter[3], FLOAT hsml, int phase, int *startnode);
int ngb_treefind_sticky_collisions(FLOAT searchcenter[3], FLOAT hguess, int phase, int *startnode);
#endif
int ngb_treefind_variable(FLOAT searchcenter[3], FLOAT hguess, int phase, int *startnode);
#ifdef CHIMIE
int ngb_treefind_variable_for_chimie(FLOAT searchcenter[3], FLOAT hguess, int *startnode);
#endif
void ngb_treefree(void);
void ngb_treesearch(int);
void ngb_treesearch_pairs(int);
void ngb_update_nodes(void);
void open_outputfiles(void);
peanokey peano_hilbert_key(int x, int y, int z, int bits);
void peano_hilbert_order(void);
void pm_init_nonperiodic(void);
void pm_init_nonperiodic_allocate(int dimprod);
void pm_init_nonperiodic_free(void);
void pm_init_periodic(void);
void pm_init_periodic_allocate(int dimprod);
void pm_init_periodic_free(void);
void pm_init_regionsize(void);
void pm_setup_nonperiodic_kernel(void);
int pmforce_nonperiodic(int grnr);
void pmforce_periodic(void);
int pmpotential_nonperiodic(int grnr);
void pmpotential_periodic(void);
double pow(double, double); /* on some old DEC Alphas, the correct prototype for pow() is missing, even when math.h is included */
void read_file(char *fname, int readTask, int lastTask);
void read_header_attributes_in_hdf5(char *fname);
void read_ic(char *fname);
int read_outputlist(char *fname);
void read_parameter_file(char *fname);
void readjust_timebase(double TimeMax_old, double TimeMax_new);
void reorder_gas(void);
void reorder_particles(void);
#ifdef STELLAR_PROP
void reorder_stars(void);
void reorder_st(void);
#endif
void restart(int mod);
void run(void);
void savepositions(int num);
double second(void);
void seed_glass(void);
void set_random_numbers(void);
void set_softenings(void);
void set_units(void);
void init_local_sys_state(void);
void setup_smoothinglengths(void);
#ifdef CHIMIE
void stars_setup_smoothinglengths(void);
#endif
void statistics(void);
void terminate_processes(void);
double timediff(double t0, double t1);
#ifdef HAVE_HDF5
void write_header_attributes_in_hdf5(hid_t handle);
#endif
void write_file(char *fname, int readTask, int lastTask);
void write_pid_file(void);
#ifdef COOLING
int init_cooling(FLOAT metallicity);
int init_cooling_with_metals();
double cooling_function(double temperature);
double cooling_function_with_metals(double temperature,double metal);
void init_from_new_redshift(double Redshift);
double J_0();
double J_nu(double e);
double sigma_rad_HI(double e);
double sigma_rad_HeI(double e);
double sigma_rad_HeII(double e);
double cooling_bremstrahlung_HI(double T);
double cooling_bremstrahlung_HeI(double T);
double cooling_bremstrahlung_HeII(double T);
double cooling_ionization_HI(double T);
double cooling_ionization_HeI(double T);
double cooling_ionization_HeII(double T);
double cooling_recombination_HI(double T);
double cooling_recombination_HeI(double T);
double cooling_recombination_HeII(double T);
double cooling_dielectric_recombination(double T);
double cooling_excitation_HI(double T);
double cooling_excitation_HII(double T);
double cooling_compton(double T);
double A_HII(double T);
double A_HeIId(double T);
double A_HeII(double T);
double A_HeIII(double T);
double G_HI(double T);
double G_HeI(double T);
double G_HeII(double T);
double G_gHI();
double G_gHeI();
double G_gHeII();
double G_gHI_t(double J0);
double G_gHeI_t(double J0);
double G_gHeII_t(double J0);
double G_gHI_w();
double G_gHeI_w();
double G_gHeII_w();
double heating_radiative_HI();
double heating_radiative_HeI();
double heating_radiative_HeII();
double heating_radiative_HI_t(double J0);
double heating_radiative_HeI_t(double J0);
double heating_radiative_HeII_t(double J0);
double heating_radiative_HI_w();
double heating_radiative_HeI_w();
double heating_radiative_HeII_w();
double heating_compton();
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);
void compute_densities(double T,double X,double* n_H, double* n_HI,double* n_HII,double* n_HEI,double* n_HEII,double* n_HEIII,double* n_E,double* mu);
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 compute_cooling_from_Egyspec_and_Density(double Egyspec,double Density, double *MeanWeight);
double DoCooling(FLOAT Density,FLOAT Entropy,int Phase,int i,FLOAT DtEntropyVisc, double dt, double hubble_a);
void CoolingForOne(int i,int t0,int t1,int ti_step,double dt_entr3,double a3inv,double hubble_a);
void cooling();
double lambda(FLOAT density,FLOAT egyspec,FLOAT Metal, int phase, int i);
#endif
#ifdef HEATING
void heating();
double gamma_fct(FLOAT Density,FLOAT Entropy,int i);
#endif
#ifdef AGN_HEATING
void agn_heating();
double gamma_fct(FLOAT density,double r, double SpecPower);
double HeatingRadialDependency(double r);
#endif
#ifdef MULTIPHASE
void update_phase(void);
void init_sticky(void);
void sticky(void);
void sticky_compute_energy_kin(int mode);
void sticky_collisions(void);
void sticky_collisions2(int loop);
void sticky_evaluate(int target, int mode, int loop);
int sticky_compare_key(const void *a, const void *b);
#endif
#ifdef FEEDBACK_WIND
void feedbackwind_compute_energy_kin(int mode);
#endif
#ifdef CHIMIE
void init_chimie(void);
void check_chimie(void);
void chimie(void);
void do_chimie(void);
void set_table(int i);
void chimie_evaluate(int target, int mode);
int chimie_compare_key(const void *a, const void *b);
int get_nelts();
-char* get_Element(i);
-float get_SolarMassAbundance(i);
+char* get_Element(int i);
+float get_SolarMassAbundance(int i);
#if defined(CHIMIE_THERMAL_FEEDBACK) && defined(CHIMIE_COMPUTE_THERMAL_FEEDBACK_ENERGY)
void chimie_compute_energy_int(int mode);
#endif
#if defined(CHIMIE_KINETIC_FEEDBACK) && defined(CHIMIE_COMPUTE_KINETIC_FEEDBACK_ENERGY)
void chimie_compute_energy_kin(int mode);
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
void chimie_apply_wind(void);
#endif
#ifdef CHIMIE_OPTIMAL_SAMPLING
double init_optimal_imf_sampling(int i);
double optimal_get_next_mass(double m);
double optimal_get_next_mass_for_one_particle(int j);
double optimal_get_m1_from_m2(double m2, double mp);
double optimal_init_norm(double Mecl);
int optimal_stop_loop(double m);
float optimal_get_k_normalisation_factor();
#endif
#endif
#ifdef DISSIPATION_FORCES
void dissipation_forces(void);
int dissipation_forces_compare_key(const void *a, const void *b);
void dissipation_forces_evaluate(int target, int mode);
#endif
#ifdef INTEGRAL_CONSERVING_DISSIPATION
void icd_set_LocalDissipationOn(void);
void icd_set_LocalDissipationOff(void);
void icd_set_des_nngb(int n);
void icd_set_xc(double x[3]);
void integral_conserving_dissipation(void);
void global_ic_dissipation_m1(void);
void local_ic_dissipation_m1(void);
int set_dissipation_list(void);
void set_dissipation_center(void);
void compute_integrals_m1(void);
void compute_alpha_m1(void);
void apply_transformation_m1(void);
void compute_energy_kin(void);
double get_Total_Gas_energy_kin(void);
double get_Gas_energy_kin(void);
void icd_find_ngbs(void);
double icd_get_alpha(void);
double icd_get_M(void);
double icd_get_X(double x[3]);
double icd_get_V(double v[3]);
double icd_get_T(void);
double icd_get_I(void);
double icd_get_J(void);
double icd_get_DeltaTmin(void);
int setup_integral_conserving_dissipation_local(int flag,int n,double x[3]);
int compare_icd_key(const void *a, const void *b);
void icd_allocate_numlist(void);
void icd_free_numlist(void);
#endif
#ifdef OUTERPOTENTIAL
void init_outer_potential(void);
void outer_forces(void);
void outer_potential(void);
+void forces_potentials(FLOAT pos[3], FLOAT vel[3], FLOAT acc[3]);
+void potential_components(FLOAT pos[3], FLOAT Phi[1]);
#ifdef NFW
void init_outer_potential_nfw(void);
-void outer_forces_nfw(void);
-void outer_potential_nfw(void);
+void outer_forces_nfw(FLOAT pos[3], FLOAT acc[3]);
+void outer_potential_nfw(FLOAT pos[3], FLOAT Phi[1]);
+#endif
+
+#ifdef MIYAMOTONAGAI
+void init_outer_potential_miyamotonagai(void);
+void outer_forces_miyamotonagai(FLOAT pos[3], FLOAT acc[3]);
+void outer_potential_miyamotonagai(FLOAT pos[3], FLOAT Phi[1]);
#endif
#ifdef PLUMMER
void init_outer_potential_plummer(void);
-void outer_forces_plummer(void);
-void outer_potential_plummer(void);
+void outer_forces_plummer(FLOAT pos[3], FLOAT acc[3]);
+void outer_potential_plummer(FLOAT pos[3], FLOAT Phi[1]);
#endif
#ifdef PISOTHERM
void init_outer_potential_pisotherm(void);
-void outer_forces_pisotherm(void);
-void outer_potential_pisotherm(void);
+void outer_forces_pisotherm(FLOAT pos[3], FLOAT acc[3]);
+void outer_potential_pisotherm(FLOAT pos[3], FLOAT Phi[1]);
double potential_f(double r, void * params);
double get_potential(double r);
#endif
-#ifdef CORIOLIS
-void init_outer_potential_coriolis(void);
-void set_outer_potential_coriolis(void);
-void outer_forces_coriolis(void);
-void outer_potential_coriolis(void);
+
+#ifdef EVOLVE_POT
+void init_outer_potential_evolve(void);
+int NumVars(int pottype);
+void adapt_evolve_variables(int pottype, double *vars, int nlines);
+void interp_evolve_vals(void);
+void outer_potential_evolve(FLOAT pos[3], FLOAT Phi[1]);
+void outer_forces_evolve(FLOAT pos[3], FLOAT acc[3]);
+#endif
+
+#ifdef PERIODICOUTER
+void forces_rotating(FLOAT pos[3], FLOAT vel[3], FLOAT acc[3], FLOAT RotAng[4], FLOAT RotAcc[3]);
+void move_tracer(double dt);//int time0, int time1);
+void kick_tracer(double dt);
+void update_tracequat(double dt);
+void fictitious_forces(void);
+void update_traceacc(void);
+void update_tracepotential(void);
+void update_rotang(void);
+void inertialv(void);
+void init_quat(void);
+#endif
+
+#if defined(PERIODICOUTER) || defined(MERGE_SPLIT)
+double *quatproduct(double z[4], double x[4], double y[4]);
+double *quatconj(double y[4], double x[4]);
+double *quatrot(double z[4], double x[4], double y[4]);
+#endif
+
+#ifdef HOT_HALO
+void halo_creation(void);
+void halo_creation_time(double dt);
+FLOAT num_gas_created(FLOAT dt);
+FLOAT halo_dens(void);
+void update_entropy_for_accreted_particles(void);
+double get_Halo_random_number(int id);
+double *angcorrection(FLOAT pos[3], double vel[3]);
#endif
#endif
#ifdef SFR
void star_formation(void);
void rearrange_particle_sequence(void);
void sfr_compute_energy_int(int mode);
void sfr_check_number_of_stars(int mode);
#endif
#ifdef AGN_ACCRETION
void compute_agn_accretion(void);
#endif
#ifdef BUBBLES
void init_bubble(void);
void make_bubble(void);
void create_bubble(int sign);
#endif
#ifdef BONDI_ACCRETION
void bondi_accretion(void);
#endif
#ifdef PNBODY
void init_pnbody();
void finalize_pnbody();
void compute_pnbody();
#endif
#ifdef AB_TURB
void init_turb();
#endif
double artificial_viscosity(double r,double vdotr2,double soundspeed_i,double soundspeed_j,double dwk_i,double dwk_j,int timestep,int j,FLOAT mass,FLOAT rho,FLOAT f1,double *maxSignalVel);
#if defined(ART_VISCO_MM)|| defined(ART_VISCO_RO)
double artificial_viscosity_improved(double r,double vdotr2,double soundspeed_i,double soundspeed_j,double dwk_i,double dwk_j,double h_i,double alpha_i,int timestep,int j,FLOAT mass,FLOAT rho,FLOAT f1,double *maxSignalVel);
#endif
#if defined(ART_VISCO_CD)
double artificial_viscosity_CD(double r,double vdotr2,double soundspeed_i,double soundspeed_j,double dwk_i,double dwk_j,int timestep,int j,FLOAT mass,FLOAT rho,FLOAT f1,double *maxSignalVel);
double artificial_viscosity_CD_prediction(double r,double vdotr2,double soundspeed_i,double soundspeed_j,double dwk_i,double dwk_j,int timestep,int j,FLOAT mass,FLOAT rho,FLOAT f1,double *maxSignalVel);
#endif
#if defined(ART_VISCO_MM)|| defined(ART_VISCO_RO) || defined(ART_VISCO_CD)
void move_art_visc(int i,double dt_drift);
#ifdef ART_VISCO_CD
void art_visc_allocate();
void art_visc_free();
void compute_art_visc(int i);
#endif
#endif
#ifdef TIMESTEP_UPDATE_FOR_FEEDBACK
FLOAT updated_pressure(FLOAT EntropyPred,FLOAT Density,FLOAT DeltaEgySpec);
FLOAT updated_pressure_hydra(FLOAT EntropyPred,FLOAT Density,FLOAT DeltaEgySpec);
void make_particle_active(int target);
void kickback(int i,int tstart,int tend);
#endif
#ifdef GAS_ACCRETION
void init_gas_accretion(void);
void gas_accretion(void);
#endif
#ifdef COOLING_FCT_FROM_HDF5
float computeLambda(float rho_H_in, float T_in, float nHe_in, float metalicity);
int endsWith(const char *str, const char *suffix);
void closestMatch1D(float* TABLE, int SIZE, float input, float match[2], int index[2]);
void checkRedshiftForUpdate();
int updateCoolingTable();
void loadDataInTable1D(hid_t table, char* table_key, float** TABLE, int* SIZE);
void loadDataInTable2D(hid_t table, char* table_key, float*** TABLE);
void loadDataInTable3D(hid_t table, char* table_key, float**** TABLE);
void BroadcastTablesToAllFromMaster();
int freeMemory();
#endif
#ifdef COOLING_WIERSMA
int InitWiersmaCooling(char * TablesDirectory);
int setTablesFromRedshift(double RedShift);
double compute_LambdaTotal(double T,double nH,double HeMfrac,double Z, double Zsol);
#endif
#ifdef COOLING_GRACKLE
void init_cooling_GRACKLE();
void CoolingForOne_GRACKLE(int i, double tstart, double tend, double dt_entr, double dt_entr2, double dt_entr3, double a_now, double a3inv);
#endif
#ifdef JEANS_PRESSURE_FLOOR
double JeansPressureFloor(int i);
#endif
#ifdef FOF
void fof(void);
void fof_init(void);
void fof_find_densest_neighbour(void);
int fof_compare_key(const void *a, const void *b);
int fof_compare_groups_key(const void *a, const void *b);
int fof_compare_phdata(const void *a, const void *b);
int fof_compare_particles(const void *a, const void *b);
void fof_evaluate(int target, int mode);
void fof_link_particles_to_local_head(void);
void fof_link_to_local_head(int i);
void fof_link_pseudo_heads(int i);
void fof_find_local_heads(void);
void fof_regroup_pseudo_heads(void);
void fof_regroup_exported_pseudo_heads(void);
void fof_clean_local_groups(void);
void fof_compute_local_tails(void);
void fof_send_and_link_pseudo_heads(void);
void fof_write_local_groups(void);
void fof_write_all_groups(void);
void fof_group_info(void);
void fof_compute_groups_properties(void);
void fof_init_group_properties(int gid);
void fof_add_particle_properties(int i, int gid, int mode);
void fof_final_operations_on_groups_properties();
void fof_write_groups_properties();
void fof_write_particles_id_and_indicies(void);
void fof_set_groups_for_sfr(void);
#ifdef SFR
void fof_star_formation(void);
void fof_star_formation_and_IMF_sampling(void);
#endif
void fof_allocate_groups(void);
void fof_free_groups(void);
#endif //FOF
#ifdef TESSEL
void ConstructDelaunay();
void ComputeVoronoi();
void setup_searching_radius();
int ngb_treefind_variable_for_tessel(FLOAT searchcenter[3], FLOAT hsml, int phase, int *startnode);
void ghost();
void tessel_compute_accelerations();
void tessel_convert_energy_to_entropy();
void tessel_kick(float dt_kick);
void tessel_drift(float dt_drift);
double tessel_get_timestep();
int CheckCompletenessForThisPoint(int i);
int ghost_compare_key(const void *a, const void *b);
void CheckTriangles();
void AddGhostPoints(int istart,int nadd);
void dump_triangles(char *filename);
void dump_voronoi(char *filename);
#ifdef PY_INTERFACE
#include <Python.h>
PyObject *gadget_GetAllDelaunayTriangles(self, args);
PyObject *gadget_GetAllvPoints(self, args);
PyObject *gadget_GetAllvDensities(PyObject* self);
PyObject *gadget_GetAllvVolumes(PyObject* self);
PyObject *gadget_GetAllvPressures(PyObject* self);
PyObject *gadget_GetAllvEnergySpec(PyObject* self);
PyObject *gadget_GetAllvAccelerations(PyObject* self);
PyObject *gadget_GetvPointsForOnePoint(self, args);
PyObject *gadget_GetNgbPointsForOnePoint(self, args);
PyObject *gadget_GetNgbPointsAndFacesForOnePoint(self, args);
PyObject *gadget_GetAllGhostPositions(PyObject* self);
PyObject *gadget_GetAllGhostvDensities(PyObject* self);
PyObject *gadget_GetAllGhostvVolumes(PyObject* self);
#endif
#endif
#ifdef PY_INTERFACE
#include <Python.h>
void allocate_commbuffersQ(void);
void density_sub(void);
void density_evaluate_sub(int i, int mode);
void do_box_wrappingQ(void);
void domain_DecompositionQ(void);
void domain_decomposeQ(void);
int domain_findSplitQ(int cpustart, int ncpu, int first, int last);
void domain_shiftSplitQ(void);
void domain_findExchangeNumbersQ(int task, int partner, int sphflag, int *send, int *recv);
void domain_exchangeParticlesQ(int partner, int sphflag, int send_count, int recv_count);
void domain_countToGoQ(void);
void domain_walktoptreeQ(int no);
void domain_sumCostQ(void);
void domain_findExtentQ(void);
void domain_determineTopTreeQ(void);
void domain_topsplit_localQ(int node, peanokey startkey);
void domain_topsplitQ(int node, peanokey startkey);
int force_treeevaluate_sub(int target, int mode, double *ewaldcountsum);
void force_treeevaluate_potential_sub(int target, int type);
void force_treeevaluate_potential_shortrange_sub(int target, int mode);
int force_treeevaluate_shortrange_sub(int target, int mode);
void gravity_tree_sub(void);
void sph(void);
void sph_evaluate(int target, int mode);
void sph_sub(void);
void sph_evaluate_sub(int target, int mode);
void sph_thermal_conductivity(void);
void sph_evaluate_thermal_conductivity(int target, int mode);
int sph_compare_key(const void *a, const void *b);
void peano_hilbert_orderQ(void);
void reorder_gasQ(void);
void reorder_particlesQ(void);
void setup_smoothinglengths_sub(void);
#ifdef SFR
PyObject * sfr_SetParameters(PyObject *self, PyObject *args);
PyObject * sfr_GetParameters();
#endif
#endif
diff --git a/src/read_ic.c b/src/read_ic.c
index 3451324..8adfa02 100644
--- a/src/read_ic.c
+++ b/src/read_ic.c
@@ -1,956 +1,958 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <string.h>
#include <mpi.h>
#include "allvars.h"
#include "proto.h"
/*! \file read_ic.c
* \brief Read initial conditions in one of Gadget's file formats
*/
/*! This function reads initial conditions, in one of the three possible file
* formats currently supported by Gadget. Note: When a snapshot file is
* started from initial conditions (start-option 0), not all the information
* in the header is used, in particular, the STARTING TIME needs to be set in
* the parameterfile. Also, for gas particles, only the internal energy is
* read, the density and mean molecular weight will be recomputed by the
* code. When InitGasTemp>0 is given, the gas temperature will be initialzed
* to this value assuming a mean colecular weight either corresponding to
* complete neutrality, or full ionization.
*
* However, when the code is started with start-option 2, then all the this
* data in the snapshot files is preserved, i.e. this is also the way to
* resume a simulation from a snapshot file in case a regular restart file is
* not available.
*/
void read_ic(char *fname)
{
int i, num_files, rest_files, ngroups, gr, filenr, masterTask, lastTask, groupMaster;
double u_init;
char buf[500];
#ifndef ISOTHERM_EQS
double molecular_weight;
#endif
NumPart = 0;
N_gas = 0;
#ifdef SFR
N_stars = 0;
#endif
All.TotNumPart = 0;
num_files = find_files(fname);
rest_files = num_files;
fill_Tab_IO_Labels();
while(rest_files > NTask)
{
sprintf(buf, "%s.%d", fname, ThisTask + (rest_files - NTask));
if(All.ICFormat == 3)
sprintf(buf, "%s.%d.hdf5", fname, ThisTask + (rest_files - NTask));
ngroups = NTask / All.NumFilesWrittenInParallel;
if((NTask % All.NumFilesWrittenInParallel))
ngroups++;
groupMaster = (ThisTask / ngroups) * ngroups;
for(gr = 0; gr < ngroups; gr++)
{
if(ThisTask == (groupMaster + gr)) /* ok, it's this processor's turn */
read_file(buf, ThisTask, ThisTask);
MPI_Barrier(MPI_COMM_WORLD);
}
rest_files -= NTask;
}
if(rest_files > 0)
{
distribute_file(rest_files, 0, 0, NTask - 1, &filenr, &masterTask, &lastTask);
if(num_files > 1)
{
sprintf(buf, "%s.%d", fname, filenr);
if(All.ICFormat == 3)
sprintf(buf, "%s.%d.hdf5", fname, filenr);
}
else
{
sprintf(buf, "%s", fname);
if(All.ICFormat == 3)
sprintf(buf, "%s.hdf5", fname);
}
ngroups = rest_files / All.NumFilesWrittenInParallel;
if((rest_files % All.NumFilesWrittenInParallel))
ngroups++;
for(gr = 0; gr < ngroups; gr++)
{
if((filenr / All.NumFilesWrittenInParallel) == gr) /* ok, it's this processor's turn */
read_file(buf, masterTask, lastTask);
MPI_Barrier(MPI_COMM_WORLD);
}
}
/* this makes sure that masses are initialized in the case that the mass-block
is completely empty */
for(i = 0; i < NumPart; i++)
{
if(All.MassTable[P[i].Type] != 0)
P[i].Mass = All.MassTable[P[i].Type];
}
if(RestartFlag == 0)
{
if(All.InitGasTemp > 0)
{
u_init = (BOLTZMANN / PROTONMASS) * All.InitGasTemp;
u_init *= All.UnitMass_in_g / All.UnitEnergy_in_cgs; /* unit conversion */
#ifdef ISOTHERM_EQS
u_init *= (3.0/2);
#else
u_init *= (1.0 / GAMMA_MINUS1);
if(All.InitGasTemp > 1.0e4) /* assuming FULL ionization */
molecular_weight = 4 / (8 - 5 * (1 - HYDROGEN_MASSFRAC));
else /* assuming NEUTRAL GAS */
molecular_weight = 4 / (1 + 3 * HYDROGEN_MASSFRAC);
u_init /= molecular_weight;
#endif
for(i = 0; i < N_gas; i++)
{
if(SphP[i].Entropy == 0)
SphP[i].Entropy = u_init;
/* Note: the conversion to entropy will be done in the function init(),
after the densities have been computed */
}
}
}
#ifdef WRITE_ALL_MASSES
for(i = 0; i < 6; i++)
All.MassTable[i] = 0;
#endif
#ifdef MULTIPHASE
for(i = 0; i < N_gas; i++)
{
if(SphP[i].Entropy>0)
SphP[i].Entropy = dmax(All.MinEgySpec, SphP[i].Entropy);
else
SphP[i].Entropy = -dmax(All.MinEgySpec, -SphP[i].Entropy);
}
#else
for(i = 0; i < N_gas; i++)
SphP[i].Entropy = dmax(All.MinEgySpec, SphP[i].Entropy);
#endif
MPI_Barrier(MPI_COMM_WORLD);
if(ThisTask == 0)
{
printf("reading done.\n");
fflush(stdout);
}
if(ThisTask == 0)
{
printf("Total number of particles : %d%09d\n\n",
(int) (All.TotNumPart / 1000000000), (int) (All.TotNumPart % 1000000000));
fflush(stdout);
}
#ifdef GAS_ACCRETION
init_gas_accretion();
#endif
-
+#ifdef HOT_HALO
+ init_accretion();
+#endif
}
/*! This function reads out the buffer that was filled with particle data, and
* stores it at the appropriate place in the particle structures.
*/
void empty_read_buffer(enum iofields blocknr, int offset, int pc, int type)
{
int n, k;
float *fp;
#ifdef LONGIDS
long long *ip;
#else
int *ip;
#endif
fp = CommBuffer;
ip = CommBuffer;
switch (blocknr)
{
case IO_POS: /* positions */
for(n = 0; n < pc; n++)
for(k = 0; k < 3; k++)
P[offset + n].Pos[k] = *fp++;
for(n = 0; n < pc; n++)
P[offset + n].Type = type; /* initialize type here as well */
break;
case IO_VEL: /* velocities */
for(n = 0; n < pc; n++)
for(k = 0; k < 3; k++)
P[offset + n].Vel[k] = *fp++;
break;
case IO_ID: /* particle ID */
for(n = 0; n < pc; n++)
P[offset + n].ID = *ip++;
break;
case IO_MASS: /* particle mass */
for(n = 0; n < pc; n++)
P[offset + n].Mass = *fp++;
break;
case IO_U: /* temperature */
for(n = 0; n < pc; n++)
SphP[offset + n].Entropy = *fp++;
break;
case IO_RHO: /* density */
for(n = 0; n < pc; n++)
SphP[offset + n].Density = *fp++;
break;
case IO_HSML: /* SPH smoothing length */
for(n = 0; n < pc; n++)
SphP[offset + n].Hsml = *fp++;
break;
/* the other input fields (if present) are not needed to define the
initial conditions of the code */
case IO_POT:
case IO_ACCEL:
case IO_DTENTR:
case IO_TSTP:
case IO_ERADSPH:
case IO_ERADSTICKY:
case IO_ERADFEEDBACK:
case IO_ENERGYFLUX:
case IO_OPTVAR1:
case IO_OPTVAR2:
break;
case IO_METALS: /* gas metallicity */
#ifdef CHIMIE
for(n = 0; n < pc; n++)
{
for(k = 0; k < NELEMENTS; k++)
{
SphP[offset + n].Metal[k] = *fp++;
}
}
#endif
break;
case IO_STAR_FORMATIONTIME:
#ifdef STELLAR_PROP
for(n = 0; n < pc; n++)
StP[n].FormationTime = *fp++;
#endif
break;
case IO_INITIAL_MASS:
#ifdef STELLAR_PROP
for(n = 0; n < pc; n++)
StP[n].InitialMass = *fp++;
#endif
break;
case IO_STAR_IDPROJ:
#ifdef STELLAR_PROP
for(n = 0; n < pc; n++)
StP[n].IDProj = *ip++;
#endif
break;
case IO_STAR_RHO:
#ifdef STELLAR_PROP
for(n = 0; n < pc; n++)
StP[n].Density = *fp++;
#endif
break;
case IO_STAR_HSML:
#ifdef STELLAR_PROP
for(n = 0; n < pc; n++)
StP[n].Hsml = *fp++;
#endif
break;
case IO_STAR_METALS:
#ifdef CHIMIE
for(n = 0; n < pc; n++)
{
for(k = 0; k < NELEMENTS; k++)
{
StP[n].Metal[k] = *fp++;
}
}
#endif
break;
}
}
/*! This function reads a snapshot file and distributes the data it contains
* to tasks 'readTask' to 'lastTask'.
*/
void read_file(char *fname, int readTask, int lastTask)
{
int blockmaxlen;
int i, n_in_file, n_for_this_task, ntask, pc, offset = 0, task;
int blksize1, blksize2;
MPI_Status status;
FILE *fd = 0;
int nall;
int type;
char label[4];
int nstart, bytes_per_blockelement, npart, nextblock, typelist[6];
enum iofields blocknr;
#ifdef HAVE_HDF5
char buf[500];
int rank, pcsum;
hid_t hdf5_file, hdf5_grp[6], hdf5_dataspace_in_file;
hid_t hdf5_datatype, hdf5_dataspace_in_memory, hdf5_dataset;
hsize_t dims[2], count[2], start[2];
#endif
#define SKIP {my_fread(&blksize1,sizeof(int),1,fd);}
#define SKIP2 {my_fread(&blksize2,sizeof(int),1,fd);}
if(ThisTask == readTask)
{
if(All.ICFormat == 1 || All.ICFormat == 2)
{
if(!(fd = fopen(fname, "r")))
{
printf("can't open file `%s' for reading initial conditions.\n", fname);
endrun(123);
}
if(All.ICFormat == 2)
{
SKIP;
my_fread(&label, sizeof(char), 4, fd);
my_fread(&nextblock, sizeof(int), 1, fd);
printf("Reading header => '%c%c%c%c' (%d byte)\n", label[0], label[1], label[2], label[3],
nextblock);
SKIP2;
}
SKIP;
my_fread(&header, sizeof(header), 1, fd);
SKIP2;
if(blksize1 != 256 || blksize2 != 256)
{
printf("incorrect header format\n");
fflush(stdout);
endrun(890);
}
#ifdef CHIMIE
if((header.flag_metals!= 0) && (header.flag_metals!= NELEMENTS))
{
printf("\n(Tasks=%d) NELEMENTS (=%d) != header.flag_metals (=%d) !!!\n\n",ThisTask,NELEMENTS,header.flag_metals);
printf("This means that the number of chemical elements stored in your initial condition file is different \n");
printf("from the variable NELEMENTS equal to the one in the chimie parameter file.\n");
printf("You can either modify you initial condition file or change the NELEMENTS and the chimie parameter file.");
endrun(12323);
}
#endif
#ifdef CHIMIE_EXTRAHEADER
if (header.flag_chimie_extraheader)
{
SKIP;
my_fread(&chimie_extraheader, sizeof(chimie_extraheader), 1, fd);
SKIP2;
if(blksize1 != 256 || blksize2 != 256)
{
printf("incorrect chimie_extraheader format\n");
fflush(stdout);
endrun(891);
}
}
#endif
}
#ifdef HAVE_HDF5
if(All.ICFormat == 3)
{
read_header_attributes_in_hdf5(fname);
hdf5_file = H5Fopen(fname, H5F_ACC_RDONLY, H5P_DEFAULT);
for(type = 0; type < 6; type++)
{
if(header.npart[type] > 0)
{
sprintf(buf, "/PartType%d", type);
hdf5_grp[type] = H5Gopen(hdf5_file, buf);
}
}
}
#endif
for(task = readTask + 1; task <= lastTask; task++)
{
MPI_Ssend(&header, sizeof(header), MPI_BYTE, task, TAG_HEADER, MPI_COMM_WORLD);
#ifdef CHIMIE_EXTRAHEADER
if (header.flag_chimie_extraheader)
MPI_Ssend(&header, sizeof(chimie_extraheader), MPI_BYTE, task, TAG_CHIMIE_EXTRAHEADER, MPI_COMM_WORLD);
#endif
}
}
else
{
MPI_Recv(&header, sizeof(header), MPI_BYTE, readTask, TAG_HEADER, MPI_COMM_WORLD, &status);
#ifdef CHIMIE_EXTRAHEADER
if (header.flag_chimie_extraheader)
MPI_Recv(&chimie_extraheader, sizeof(chimie_extraheader), MPI_BYTE, readTask, TAG_CHIMIE_EXTRAHEADER, MPI_COMM_WORLD, &status);
#endif
}
if(All.TotNumPart == 0)
{
if(header.num_files <= 1)
for(i = 0; i < 6; i++)
header.npartTotal[i] = header.npart[i];
All.TotN_gas = header.npartTotal[0] + (((long long) header.npartTotalHighWord[0]) << 32);
#if defined(SFR) || defined(STELLAR_PROP)
All.TotN_stars = header.npartTotal[ST] + (((long long) header.npartTotalHighWord[ST]) << 32);
#endif
for(i = 0, All.TotNumPart = 0; i < 6; i++)
{
All.TotNumPart += header.npartTotal[i];
All.TotNumPart += (((long long) header.npartTotalHighWord[i]) << 32);
}
for(i = 0; i < 6; i++)
All.MassTable[i] = header.mass[i];
All.MaxPart = All.PartAllocFactor * (All.TotNumPart / NTask); /* sets the maximum number of particles that may */
All.MaxPartSph = All.PartAllocFactor * (All.TotN_gas / NTask); /* sets the maximum number of particles that may
reside on a processor */
#ifdef STELLAR_PROP
All.MaxPartStars = All.PartAllocFactor * (All.TotN_stars / NTask); /* existing star particles */
#ifdef SFR
All.MaxPartStars = All.MaxPartStars + All.StarFormationNStarsFromGas*All.MaxPartSph*All.StarsAllocFactor; /* potental star particles */
#endif
#endif
allocate_memory();
if(RestartFlag == 2)
All.Time = All.TimeBegin = header.time;
}
if(ThisTask == readTask)
{
for(i = 0, n_in_file = 0; i < 6; i++)
n_in_file += header.npart[i];
printf("\nreading file `%s' on task=%d (contains %d particles.)\n"
"distributing this file to tasks %d-%d\n"
"Type 0 (gas): %8d (tot=%6d%09d) masstab=%g\n"
"Type 1 (halo): %8d (tot=%6d%09d) masstab=%g\n"
"Type 2 (disk): %8d (tot=%6d%09d) masstab=%g\n"
"Type 3 (bulge): %8d (tot=%6d%09d) masstab=%g\n"
"Type 4 (stars): %8d (tot=%6d%09d) masstab=%g\n"
"Type 5 (bndry): %8d (tot=%6d%09d) masstab=%g\n\n", fname, ThisTask, n_in_file, readTask,
lastTask, header.npart[0], (int) (header.npartTotal[0] / 1000000000),
(int) (header.npartTotal[0] % 1000000000), All.MassTable[0], header.npart[1],
(int) (header.npartTotal[1] / 1000000000), (int) (header.npartTotal[1] % 1000000000),
All.MassTable[1], header.npart[2], (int) (header.npartTotal[2] / 1000000000),
(int) (header.npartTotal[2] % 1000000000), All.MassTable[2], header.npart[3],
(int) (header.npartTotal[3] / 1000000000), (int) (header.npartTotal[3] % 1000000000),
All.MassTable[3], header.npart[4], (int) (header.npartTotal[4] / 1000000000),
(int) (header.npartTotal[4] % 1000000000), All.MassTable[4], header.npart[5],
(int) (header.npartTotal[5] / 1000000000), (int) (header.npartTotal[5] % 1000000000),
All.MassTable[5]);
fflush(stdout);
}
ntask = lastTask - readTask + 1;
/* to collect the gas particles all at the beginning (in case several
snapshot files are read on the current CPU) we move the collisionless
particles such that a gap of the right size is created */
for(type = 0, nall = 0; type < 6; type++)
{
n_in_file = header.npart[type];
n_for_this_task = n_in_file / ntask;
if((ThisTask - readTask) < (n_in_file % ntask))
n_for_this_task++;
nall += n_for_this_task;
}
memmove(&P[N_gas + nall], &P[N_gas], (NumPart - N_gas) * sizeof(struct particle_data));
nstart = N_gas;
for(blocknr = 0; blocknr < IO_NBLOCKS; blocknr++)
{
if(blockpresent(blocknr))
{
#ifndef BLOCK_SKIPPING
if(RestartFlag == 0 && blocknr > IO_U)
continue; /* ignore all other blocks in initial conditions */
#else
if(blockabsent(blocknr))
continue;
#endif
bytes_per_blockelement = get_bytes_per_blockelement(blocknr);
blockmaxlen = ((int) (All.BufferSize * 1024 * 1024)) / bytes_per_blockelement;
npart = get_particles_in_block(blocknr, &typelist[0]);
if(npart > 0)
{
if(ThisTask == readTask)
{
if(All.ICFormat == 2)
{
SKIP;
my_fread(&label, sizeof(char), 4, fd);
my_fread(&nextblock, sizeof(int), 1, fd);
printf("Reading header => '%c%c%c%c' (%d byte)\n", label[0], label[1], label[2],
label[3], nextblock);
SKIP2;
if(strncmp(label, Tab_IO_Labels[blocknr], 4) != 0)
{
printf("incorrect block-structure!\n");
printf("expected '%c%c%c%c' but found '%c%c%c%c'\n",
label[0], label[1], label[2], label[3],
Tab_IO_Labels[blocknr][0], Tab_IO_Labels[blocknr][1],
Tab_IO_Labels[blocknr][2], Tab_IO_Labels[blocknr][3]);
fflush(stdout);
endrun(1890);
}
}
if(All.ICFormat == 1 || All.ICFormat == 2)
SKIP;
}
for(type = 0, offset = 0; type < 6; type++)
{
n_in_file = header.npart[type];
#ifdef HAVE_HDF5
pcsum = 0;
#endif
if(typelist[type] == 0)
{
n_for_this_task = n_in_file / ntask;
if((ThisTask - readTask) < (n_in_file % ntask))
n_for_this_task++;
offset += n_for_this_task;
}
else
{
for(task = readTask; task <= lastTask; task++)
{
n_for_this_task = n_in_file / ntask;
if((task - readTask) < (n_in_file % ntask))
n_for_this_task++;
if(task == ThisTask)
if(NumPart + n_for_this_task > All.MaxPart)
{
printf("too many particles\n");
endrun(1313);
}
do
{
pc = n_for_this_task;
if(pc > blockmaxlen)
pc = blockmaxlen;
if(ThisTask == readTask)
{
if(All.ICFormat == 1 || All.ICFormat == 2)
my_fread(CommBuffer, bytes_per_blockelement, pc, fd);
#ifdef HAVE_HDF5
if(All.ICFormat == 3)
{
get_dataset_name(blocknr, buf);
hdf5_dataset = H5Dopen(hdf5_grp[type], buf);
dims[0] = header.npart[type];
dims[1] = get_values_per_blockelement(blocknr);
if(dims[1] == 1)
rank = 1;
else
rank = 2;
hdf5_dataspace_in_file = H5Screate_simple(rank, dims, NULL);
dims[0] = pc;
hdf5_dataspace_in_memory = H5Screate_simple(rank, dims, NULL);
start[0] = pcsum;
start[1] = 0;
count[0] = pc;
count[1] = get_values_per_blockelement(blocknr);
pcsum += pc;
H5Sselect_hyperslab(hdf5_dataspace_in_file, H5S_SELECT_SET,
start, NULL, count, NULL);
switch (get_datatype_in_block(blocknr))
{
case 0:
hdf5_datatype = H5Tcopy(H5T_NATIVE_UINT);
break;
case 1:
hdf5_datatype = H5Tcopy(H5T_NATIVE_FLOAT);
break;
case 2:
hdf5_datatype = H5Tcopy(H5T_NATIVE_UINT64);
break;
}
H5Dread(hdf5_dataset, hdf5_datatype, hdf5_dataspace_in_memory,
hdf5_dataspace_in_file, H5P_DEFAULT, CommBuffer);
H5Tclose(hdf5_datatype);
H5Sclose(hdf5_dataspace_in_memory);
H5Sclose(hdf5_dataspace_in_file);
H5Dclose(hdf5_dataset);
}
#endif
}
if(ThisTask == readTask && task != readTask)
MPI_Ssend(CommBuffer, bytes_per_blockelement * pc, MPI_BYTE, task, TAG_PDATA,
MPI_COMM_WORLD);
if(ThisTask != readTask && task == ThisTask)
MPI_Recv(CommBuffer, bytes_per_blockelement * pc, MPI_BYTE, readTask,
TAG_PDATA, MPI_COMM_WORLD, &status);
if(ThisTask == task)
{
empty_read_buffer(blocknr, nstart + offset, pc, type);
offset += pc;
}
n_for_this_task -= pc;
}
while(n_for_this_task > 0);
}
}
}
if(ThisTask == readTask)
{
if(All.ICFormat == 1 || All.ICFormat == 2)
{
SKIP2;
if(blksize1 != blksize2)
{
printf("incorrect block-sizes detected!\n");
printf("Task=%d blocknr=%d blksize1=%d blksize2=%d\n", ThisTask, blocknr,
blksize1, blksize2);
fflush(stdout);
endrun(1889);
}
}
}
}
}
}
for(type = 0; type < 6; type++)
{
n_in_file = header.npart[type];
n_for_this_task = n_in_file / ntask;
if((ThisTask - readTask) < (n_in_file % ntask))
n_for_this_task++;
NumPart += n_for_this_task;
if(type == 0)
N_gas += n_for_this_task;
#ifdef SFR
if(type == ST)
N_stars += n_for_this_task;
#endif
}
if(ThisTask == readTask)
{
if(All.ICFormat == 1 || All.ICFormat == 2)
fclose(fd);
#ifdef HAVE_HDF5
if(All.ICFormat == 3)
{
for(type = 5; type >= 0; type--)
if(header.npart[type] > 0)
H5Gclose(hdf5_grp[type]);
H5Fclose(hdf5_file);
}
#endif
}
}
/*! This function determines onto how many files a given snapshot is
* distributed.
*/
int find_files(char *fname)
{
FILE *fd;
char buf[200], buf1[200];
int dummy;
sprintf(buf, "%s.%d", fname, 0);
sprintf(buf1, "%s", fname);
if(All.SnapFormat == 3)
{
sprintf(buf, "%s.%d.hdf5", fname, 0);
sprintf(buf1, "%s.hdf5", fname);
}
#ifndef HAVE_HDF5
if(All.SnapFormat == 3)
{
if(ThisTask == 0)
printf("Code wasn't compiled with HDF5 support enabled!\n");
endrun(0);
}
#endif
header.num_files = 0;
if(ThisTask == 0)
{
if((fd = fopen(buf, "r")))
{
if(All.ICFormat == 1 || All.ICFormat == 2)
{
if(All.ICFormat == 2)
{
fread(&dummy, sizeof(dummy), 1, fd);
fread(&dummy, sizeof(dummy), 1, fd);
fread(&dummy, sizeof(dummy), 1, fd);
fread(&dummy, sizeof(dummy), 1, fd);
}
fread(&dummy, sizeof(dummy), 1, fd);
fread(&header, sizeof(header), 1, fd);
fread(&dummy, sizeof(dummy), 1, fd);
}
fclose(fd);
#ifdef HAVE_HDF5
if(All.ICFormat == 3)
read_header_attributes_in_hdf5(buf);
#endif
}
}
MPI_Bcast(&header, sizeof(header), MPI_BYTE, 0, MPI_COMM_WORLD);
if(header.num_files > 0)
return header.num_files;
if(ThisTask == 0)
{
if((fd = fopen(buf1, "r")))
{
if(All.ICFormat == 1 || All.ICFormat == 2)
{
if(All.ICFormat == 2)
{
fread(&dummy, sizeof(dummy), 1, fd);
fread(&dummy, sizeof(dummy), 1, fd);
fread(&dummy, sizeof(dummy), 1, fd);
fread(&dummy, sizeof(dummy), 1, fd);
}
fread(&dummy, sizeof(dummy), 1, fd);
fread(&header, sizeof(header), 1, fd);
fread(&dummy, sizeof(dummy), 1, fd);
}
fclose(fd);
#ifdef HAVE_HDF5
if(All.ICFormat == 3)
read_header_attributes_in_hdf5(buf1);
#endif
header.num_files = 1;
}
}
MPI_Bcast(&header, sizeof(header), MPI_BYTE, 0, MPI_COMM_WORLD);
if(header.num_files > 0)
return header.num_files;
if(ThisTask == 0)
{
printf("\nCan't find initial conditions file.");
printf("neither as '%s'\nnor as '%s'\n", buf, buf1);
fflush(stdout);
}
endrun(0);
return 0;
}
/*! This function assigns a certain number of files to processors, such that
* each processor is exactly assigned to one file, and the number of cpus per
* file is as homogenous as possible. The number of files may at most be
* equal to the number of processors.
*/
void distribute_file(int nfiles, int firstfile, int firsttask, int lasttask, int *filenr, int *master,
int *last)
{
int ntask, filesleft, filesright, tasksleft, tasksright;
if(nfiles > 1)
{
ntask = lasttask - firsttask + 1;
filesleft = (((double) (ntask / 2)) / ntask) * nfiles;
if(filesleft <= 0)
filesleft = 1;
if(filesleft >= nfiles)
filesleft = nfiles - 1;
filesright = nfiles - filesleft;
tasksleft = ntask / 2;
tasksright = ntask - tasksleft;
distribute_file(filesleft, firstfile, firsttask, firsttask + tasksleft - 1, filenr, master, last);
distribute_file(filesright, firstfile + filesleft, firsttask + tasksleft, lasttask, filenr, master,
last);
}
else
{
if(ThisTask >= firsttask && ThisTask <= lasttask)
{
*filenr = firstfile;
*master = firsttask;
*last = lasttask;
}
}
}
/*! This function reads the header information in case the HDF5 file format is
* used.
*/
#ifdef HAVE_HDF5
void read_header_attributes_in_hdf5(char *fname)
{
hid_t hdf5_file, hdf5_headergrp, hdf5_attribute;
hdf5_file = H5Fopen(fname, H5F_ACC_RDONLY, H5P_DEFAULT);
hdf5_headergrp = H5Gopen(hdf5_file, "/Header");
hdf5_attribute = H5Aopen_name(hdf5_headergrp, "NumPart_ThisFile");
H5Aread(hdf5_attribute, H5T_NATIVE_INT, header.npart);
H5Aclose(hdf5_attribute);
hdf5_attribute = H5Aopen_name(hdf5_headergrp, "NumPart_Total");
H5Aread(hdf5_attribute, H5T_NATIVE_UINT, header.npartTotal);
H5Aclose(hdf5_attribute);
hdf5_attribute = H5Aopen_name(hdf5_headergrp, "NumPart_Total_HighWord");
H5Aread(hdf5_attribute, H5T_NATIVE_UINT, header.npartTotalHighWord);
H5Aclose(hdf5_attribute);
hdf5_attribute = H5Aopen_name(hdf5_headergrp, "MassTable");
H5Aread(hdf5_attribute, H5T_NATIVE_DOUBLE, header.mass);
H5Aclose(hdf5_attribute);
hdf5_attribute = H5Aopen_name(hdf5_headergrp, "Time");
H5Aread(hdf5_attribute, H5T_NATIVE_DOUBLE, &header.time);
H5Aclose(hdf5_attribute);
hdf5_attribute = H5Aopen_name(hdf5_headergrp, "NumFilesPerSnapshot");
H5Aread(hdf5_attribute, H5T_NATIVE_INT, &header.num_files);
H5Aclose(hdf5_attribute);
hdf5_attribute = H5Aopen_name(hdf5_headergrp, "Flag_Entropy_ICs");
H5Aread(hdf5_attribute, H5T_NATIVE_INT, &header.flag_entropy_instead_u);
H5Aclose(hdf5_attribute);
H5Gclose(hdf5_headergrp);
H5Fclose(hdf5_file);
}
#endif
diff --git a/src/restart.c b/src/restart.c
index ff5318e..2a9cbd3 100644
--- a/src/restart.c
+++ b/src/restart.c
@@ -1,425 +1,437 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <mpi.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/file.h>
#include <unistd.h>
#include <gsl/gsl_rng.h>
#include "allvars.h"
#include "proto.h"
/*! \file restart.c
* \brief Code for reading and writing restart files
*/
static FILE *fd,*fd_bak;
static void in(int *x, int modus);
static void byten(void *x, size_t n, int modus);
/*! This function reads or writes the restart files. Each processor writes
* its own restart file, with the I/O being done in parallel. To avoid
* congestion of the disks you can tell the program to restrict the number of
* files that are simultaneously written to NumFilesWrittenInParallel.
*
* If modus>0 the restart()-routine reads, if modus==0 it writes a restart
* file.
*/
void restart(int modus)
{
char buf[200], buf_bak[200], buf_mv[500];
double save_PartAllocFactor, save_TreeAllocFactor;
int i, nprocgroup, masterTask, groupTask, old_MaxPart, old_MaxNodes;
struct global_data_all_processes all_task0;
sprintf(buf, "%s%s.%d", All.OutputDir, All.RestartFile, ThisTask);
sprintf(buf_bak, "%s%s.%d.bak", All.OutputDir, All.RestartFile, ThisTask);
sprintf(buf_mv, "mv %s %s", buf, buf_bak);
if((NTask < All.NumFilesWrittenInParallel))
{
printf
("Fatal error.\nNumber of processors must be a smaller or equal than `NumFilesWrittenInParallel'.\n");
endrun(2131);
}
nprocgroup = NTask / All.NumFilesWrittenInParallel;
if((NTask % All.NumFilesWrittenInParallel))
{
nprocgroup++;
}
masterTask = (ThisTask / nprocgroup) * nprocgroup;
for(groupTask = 0; groupTask < nprocgroup; groupTask++)
{
if(ThisTask == (masterTask + groupTask)) /* ok, it's this processor's turn */
{
if(modus)
{
if(!(fd = fopen(buf, "r")))
{
printf("Restart file '%s' not found.\n", buf);
endrun(7870);
}
}
else
{
system(buf_mv); /* move old restart files to .bak files */
/*
/* move old restart files to .bak files */
/*
system(buf_mv);
This does not work !!!
fd = fopen(buf,"r");
fd_bak = fopen(buf_bak,"w");
while(1)
{
fgets(buf, 200, fd);
if (feof(fd)) break;
fprintf(fd_bak, buf, 200);
}
fclose(fd);
fclose(fd_bak);
*/
if(!(fd = fopen(buf, "w")))
{
printf("Restart file '%s' cannot be opened.\n", buf);
endrun(7878);
}
}
save_PartAllocFactor = All.PartAllocFactor;
save_TreeAllocFactor = All.TreeAllocFactor;
/* common data */
byten(&All, sizeof(struct global_data_all_processes), modus);
if(ThisTask == 0 && modus > 0)
all_task0 = All;
if(modus > 0 && groupTask == 0) /* read */
{
MPI_Bcast(&all_task0, sizeof(struct global_data_all_processes), MPI_BYTE, 0, MPI_COMM_WORLD);
}
old_MaxPart = All.MaxPart;
old_MaxNodes = All.TreeAllocFactor * All.MaxPart;
if(modus) /* read */
{
if(All.PartAllocFactor != save_PartAllocFactor)
{
All.PartAllocFactor = save_PartAllocFactor;
All.MaxPart = All.PartAllocFactor * (All.TotNumPart / NTask);
All.MaxPartSph = All.PartAllocFactor * (All.TotN_gas / NTask);
#ifdef STELLAR_PROP
All.MaxPartStars = All.PartAllocFactor * (All.TotN_stars / NTask); /* existing star particles */
#ifdef SFR
All.MaxPartStars = All.MaxPartStars = + All.StarFormationNStarsFromGas*All.MaxPartSph; /* potental star particles */
#endif
#endif
save_PartAllocFactor = -1;
}
if(All.TreeAllocFactor != save_TreeAllocFactor)
{
All.TreeAllocFactor = save_TreeAllocFactor;
save_TreeAllocFactor = -1;
}
if(all_task0.Time != All.Time)
{
printf("The restart file on task=%d is not consistent with the one on task=0\n", ThisTask);
fflush(stdout);
endrun(16);
}
allocate_memory();
}
in(&NumPart, modus);
if(NumPart > All.MaxPart)
{
printf
("it seems you have reduced(!) 'PartAllocFactor' below the value of %g needed to load the restart file.\n",
NumPart / (((double) All.TotNumPart) / NTask));
printf("fatal error\n");
endrun(22);
}
/* Particle data */
byten(&P[0], NumPart * sizeof(struct particle_data), modus);
in(&N_gas, modus);
if(N_gas > 0)
{
if(N_gas > All.MaxPartSph)
{
printf
("SPH: it seems you have reduced(!) 'PartAllocFactor' below the value of %g needed to load the restart file.\n",
N_gas / (((double) All.TotN_gas) / NTask));
printf("fatal error\n");
endrun(222);
}
/* Sph-Particle data */
byten(&SphP[0], N_gas * sizeof(struct sph_particle_data), modus);
}
#ifdef SFR
in(&N_stars, modus);
#ifdef STELLAR_PROP
if(N_stars > 0)
{
if(N_stars > All.MaxPartStars)
{
printf
("StP : it seems you have reduced(!) 'PartAllocFactor' below the value of %g needed to load the restart file.\n",
N_stars / (((double) All.TotN_stars) / NTask));
printf("fatal error\n");
endrun(2222);
}
/* Particle data */
byten(&StP[0], N_stars * sizeof(struct st_particle_data), modus);
}
/* this is a test, in case the restart fails */
//for(i=0;i<N_stars;i++)
// {
// printf("(%d) %d %15g %15g \n",ThisTask,N_stars,StP[i].FormationTime,StP[i].Hsml);
// }
#endif
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
in(&SetMinTimeStepForActives, modus);
#endif
#ifdef AB_TURB
byten(gsl_rng_state(StRng), gsl_rng_size(StRng), modus);
byten(&StNModes, sizeof(StNModes), modus);
byten(&StOUVar, sizeof(StOUVar),modus);
byten(StOUPhases, StNModes*6*sizeof(double),modus);
byten(StAmpl, StNModes*sizeof(double),modus);
byten(StAka, StNModes*3*sizeof(double),modus);
byten(StAkb, StNModes*3*sizeof(double),modus);
byten(StMode, StNModes*3*sizeof(double),modus);
byten(&StTPrev, sizeof(StTPrev),modus);
byten(&StSolWeightNorm, sizeof(StSolWeightNorm),modus);
#endif
#ifdef GAS_ACCRETION
in(&NumPart_acc, modus);
in(&N_gas_acc, modus);
if(modus) /* read */
allocate_gas_accretion();
if(NumPart_acc > 0)
{
/* Particle data */
byten(&Acc[0], NumPart_acc * sizeof(struct acc_particle_data), modus);
}
if(N_gas_acc > 0)
{
/* Particle data */
byten(&SphAcc[0], N_gas_acc * sizeof(struct gas_acc_particle_data), modus);
}
#endif
+#ifdef HOT_HALO
+ in(&NumPart_HaloAcc,modus);
+ if(modus)
+ allocate_accretion();
+
+ if(NumPart_HaloAcc > 0)
+ {
+ /* Particle data */
+ byten(&HaloAcc[0], NumPart_HaloAcc * sizeof(struct haloacc_pos_data), modus);
+ }
+#endif
+
/* write state of random number generator */
byten(gsl_rng_state(random_generator), gsl_rng_size(random_generator), modus);
/* now store relevant data for tree */
if(modus) /* read */
{
ngb_treeallocate(MAX_NGB);
force_treeallocate(All.TreeAllocFactor * All.MaxPart, All.MaxPart);
}
in(&Numnodestree, modus);
in(&NTopleaves, modus); /* yr : Thu Mar 17 16:54:34 CET 2011 */
if(Numnodestree > MaxNodes)
{
printf
("Tree storage: it seems you have reduced(!) 'PartAllocFactor' below the value needed to load the restart file (task=%d). "
"Numnodestree=%d MaxNodes=%d\n", ThisTask, Numnodestree, MaxNodes);
endrun(221);
}
byten(Nodes_base, Numnodestree * sizeof(struct NODE), modus);
byten(Extnodes_base, Numnodestree * sizeof(struct extNODE), modus);
byten(Father, NumPart * sizeof(int), modus);
byten(Nextnode, NumPart * sizeof(int), modus);
byten(Nextnode + All.MaxPart, MAXTOPNODES * sizeof(int), modus);
byten(DomainStartList, NTask * sizeof(int), modus);
byten(DomainEndList, NTask * sizeof(int), modus);
byten(DomainTask, MAXTOPNODES * sizeof(int), modus);
byten(DomainNodeIndex, MAXTOPNODES * sizeof(int), modus);
byten(DomainTreeNodeLen, MAXTOPNODES * sizeof(FLOAT), modus);
byten(DomainHmax, MAXTOPNODES * sizeof(FLOAT), modus);
byten(DomainMoment, MAXTOPNODES * sizeof(struct DomainNODE), modus);
byten(DomainCorner, 3 * sizeof(double), modus);
byten(DomainCenter, 3 * sizeof(double), modus);
byten(&DomainLen, sizeof(double), modus);
byten(&DomainFac, sizeof(double), modus);
byten(&DomainMyStart, sizeof(int), modus);
byten(&DomainMyLast, sizeof(int), modus);
if(modus) /* read */
if(All.PartAllocFactor != save_PartAllocFactor || All.TreeAllocFactor != save_TreeAllocFactor)
{
for(i = 0; i < NumPart; i++)
Father[i] += (All.MaxPart - old_MaxPart);
for(i = 0; i < NumPart; i++)
if(Nextnode[i] >= old_MaxPart)
{
if(Nextnode[i] >= old_MaxPart + old_MaxNodes)
Nextnode[i] += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxPart);
else
Nextnode[i] += (All.MaxPart - old_MaxPart);
}
for(i = 0; i < Numnodestree; i++)
{
if(Nodes_base[i].u.d.sibling >= old_MaxPart)
{
if(Nodes_base[i].u.d.sibling >= old_MaxPart + old_MaxNodes)
Nodes_base[i].u.d.sibling +=
(All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes);
else
Nodes_base[i].u.d.sibling += (All.MaxPart - old_MaxPart);
}
if(Nodes_base[i].u.d.father >= old_MaxPart)
{
if(Nodes_base[i].u.d.father >= old_MaxPart + old_MaxNodes)
Nodes_base[i].u.d.father += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes);
else
Nodes_base[i].u.d.father += (All.MaxPart - old_MaxPart);
}
if(Nodes_base[i].u.d.nextnode >= old_MaxPart)
{
if(Nodes_base[i].u.d.nextnode >= old_MaxPart + old_MaxNodes)
Nodes_base[i].u.d.nextnode +=
(All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes);
else
Nodes_base[i].u.d.nextnode += (All.MaxPart - old_MaxPart);
}
}
for(i = 0; i < MAXTOPNODES; i++)
if(Nextnode[i + All.MaxPart] >= old_MaxPart)
{
if(Nextnode[i + All.MaxPart] >= old_MaxPart + old_MaxNodes)
Nextnode[i + All.MaxPart] += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes);
else
Nextnode[i + All.MaxPart] += (All.MaxPart - old_MaxPart);
}
for(i = 0; i < MAXTOPNODES; i++)
if(DomainNodeIndex[i] >= old_MaxPart)
{
if(DomainNodeIndex[i] >= old_MaxPart + old_MaxNodes)
DomainNodeIndex[i] += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes);
else
DomainNodeIndex[i] += (All.MaxPart - old_MaxPart);
}
}
/* local system state (yr) */
if (sizeof(struct local_state_of_system))
byten(&LocalSysState, sizeof(struct local_state_of_system), modus);
fclose(fd);
}
else /* wait inside the group */
{
if(modus > 0 && groupTask == 0) /* read */
{
MPI_Bcast(&all_task0, sizeof(struct global_data_all_processes), MPI_BYTE, 0, MPI_COMM_WORLD);
}
}
MPI_Barrier(MPI_COMM_WORLD);
}
}
/*! reads/writes n bytes in restart routine
*/
void byten(void *x, size_t n, int modus)
{
if(modus)
my_fread(x, n, 1, fd);
else
my_fwrite(x, n, 1, fd);
}
/*! reads/writes one `int' variable in restart routine
*/
void in(int *x, int modus)
{
if(modus)
my_fread(x, 1, sizeof(int), fd);
else
my_fwrite(x, 1, sizeof(int), fd);
}
diff --git a/src/run.c b/src/run.c
index 291059d..9d1037b 100644
--- a/src/run.c
+++ b/src/run.c
@@ -1,879 +1,901 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <mpi.h>
#include <unistd.h>
#include "allvars.h"
#include "proto.h"
/*! \file run.c
* \brief iterates over timesteps, main loop
*/
/*! This routine contains the main simulation loop that iterates over single
* timesteps. The loop terminates when the cpu-time limit is reached, when a
* `stop' file is found in the output directory, or when the simulation ends
* because we arrived at TimeMax.
*/
void run(void)
{
FILE *fd;
int stopflag = 0;
char stopfname[200], contfname[200];
double t0, t1;
#ifdef DETAILED_CPU
double tstart,tend;
#endif
sprintf(stopfname, "%sstop", All.OutputDir);
sprintf(contfname, "%scont", All.OutputDir);
unlink(contfname);
do /* main loop */
{
t0 = second();
find_next_sync_point_and_drift(); /* find next synchronization point and drift particles to this time.
* If needed, this function will also write an output file
* at the desired time.
*/
every_timestep_stuff(); /* write some info to log-files */
#ifdef PNBODY
compute_pnbody();
#endif
#ifdef OUTPUT_EVERY_TIMESTEP
savepositions(All.SnapshotFileCount++); /* write snapshot file */
#endif
#ifdef DETAILED_CPU
tstart = second();
#endif
#ifdef AGN_ACCRETION
compute_agn_accretion(); /* compute accretion */
#endif
#ifdef BONDI_ACCRETION
compute_bondi_accretion(); /* compute bondi accretion */
#endif
#ifdef BUBBLES
make_bubble(); /* create a bubble */
#endif
#ifdef MULTIPHASE
update_phase(); /* allow particles to change their phase */
#endif
#ifdef CORIOLIS
set_outer_potential_coriolis(); /* coriolis */
#endif
#ifdef CHIMIE
chimie();
#endif
#ifdef COOLING_FCT_FROM_HDF5
checkRedshiftForUpdate();
#endif
#ifdef COOLING_WIERSMA
float a = get_a_from_CosmicTime(All.Time);
float Redshift = get_Redshift_from_a(a);
setTablesFromRedshift(Redshift);
#endif
#ifdef FOF
fof();
#else // FOF
#ifdef SFR
#ifdef COMPUTE_SFR_ENERGY
density(1);
force_update_hmax();
sfr_compute_energy_int(1);
#endif
star_formation(); /* starformation */
#endif // SFR
#endif // FOF
#ifdef GAS_ACCRETION
gas_accretion();
#endif
+
+#ifdef HOT_HALO
+ halo_creation();
+#endif
-#ifdef VANISHING_PARTICLES
- vanishing_particles();
-#endif
+//#ifdef VANISHING_PARTICLES
+// vanishing_particles();
+//#endif
#ifdef MULTIPHASE
sticky();
#endif
#ifdef INTEGRAL_CONSERVING_DISSIPATION
integral_conserving_dissipation();
#endif
#ifdef DETAILED_CPU
tend = second();
All.CPU_Physics += timediff(tstart, tend);
#endif
domain_Decomposition(); /* do domain decomposition if needed */
compute_accelerations(0); /* compute accelerations for
* the particles that are to be advanced
*/
#if defined(SFR) && defined(COMPUTE_SFR_ENERGY)
#ifdef DETAILED_CPU
tstart = second();
#endif
//sfr_compute_energy_int(2);
#ifdef DETAILED_CPU
tend = second();
All.CPU_Physics += timediff(tstart, tend);
#endif
#endif
/* check whether we want a full energy statistics */
if((All.Time - All.TimeLastStatistics) >= All.TimeBetStatistics)
{
#ifdef COMPUTE_POTENTIAL_ENERGY
compute_potential();
#endif
#ifndef ADVANCEDSTATISTICS
energy_statistics(); /* compute and output energy statistics */
#else
advanced_energy_statistics(); /* compute and output energy statistics */
#endif
All.TimeLastStatistics += All.TimeBetStatistics;
}
advance_and_find_timesteps(); /* 'kick' active particles in
* momentum space and compute new
* timesteps for them
*/
+#ifdef PERIODICOUTER
+ move_tracer(All.TimeStep);
+#ifdef FLEXSTEPS
+ kick_tracer(All.PresentMinStep*All.Timebase_interval/2. + All.TimeStep/2.);
+ update_tracequat(All.PresentMinStep*All.Timebase_interval/2. + All.TimeStep/2.);
+#else
+ if(All.Time - All.TimeStep == All.TimeBegin)
+ {
+ kick_tracer(All.TimeStep/2.);
+ update_tracequat(All.TimeStep/2.);
+ }
+ else
+ {
+ kick_tracer(All.TimeStep);
+ update_tracequat(All.TimeStep);
+ }
+#endif
+#endif
All.NumCurrentTiStep++;
/* Check whether we need to interrupt the run */
if(ThisTask == 0)
{
/* Is the stop-file present? If yes, interrupt the run. */
if((fd = fopen(stopfname, "r")))
{
fclose(fd);
stopflag = 1;
unlink(stopfname);
}
/* are we running out of CPU-time ? If yes, interrupt run. */
//if(CPUThisRun > 0.85 * All.TimeLimitCPU)
if(CPUThisRun > 1.0 * All.TimeLimitCPU)
{
printf("reaching time-limit. stopping.\n");
stopflag = 2;
}
}
MPI_Bcast(&stopflag, 1, MPI_INT, 0, MPI_COMM_WORLD);
if(stopflag)
{
restart(0); /* write restart file */
MPI_Barrier(MPI_COMM_WORLD);
if(stopflag == 2 && ThisTask == 0)
{
if((fd = fopen(contfname, "w")))
fclose(fd);
}
if(stopflag == 2 && All.ResubmitOn && ThisTask == 0)
{
close_outputfiles();
system(All.ResubmitCommand);
}
return;
}
/* is it time to write a regular restart-file? (for security) */
if(ThisTask == 0)
{
if((CPUThisRun - All.TimeLastRestartFile) >= All.CpuTimeBetRestartFile)
{
All.TimeLastRestartFile = CPUThisRun;
stopflag = 3;
}
else
stopflag = 0;
}
MPI_Bcast(&stopflag, 1, MPI_INT, 0, MPI_COMM_WORLD);
if(stopflag == 3)
{
restart(0); /* write an occasional restart file */
stopflag = 0;
}
t1 = second();
All.CPU_Total += timediff(t0, t1);
CPUThisRun += timediff(t0, t1);
}
while(All.Ti_Current < TIMEBASE && All.Time <= All.TimeMax);
restart(0);
savepositions(All.SnapshotFileCount++); /* write a last snapshot
* file at final time (will
* be overwritten if
* All.TimeMax is increased
* and the run is continued)
*/
}
/*! This function finds the next synchronization point of the system (i.e. the
* earliest point of time any of the particles needs a force computation),
* and drifts the system to this point of time. If the system drifts over
* the desired time of a snapshot file, the function will drift to this
* moment, generate an output, and then resume the drift.
*/
void find_next_sync_point_and_drift(void)
{
int n, min, min_glob, flag, *temp;
double timeold;
double t0, t1;
#ifdef DETAILED_CPU
double tstart,tend;
#endif
t0 = second();
#ifdef DETAILED_CPU
tstart = t0;
#endif
timeold = All.Time;
for(n = 1, min = P[0].Ti_endstep; n < NumPart; n++)
if(min > P[n].Ti_endstep)
min = P[n].Ti_endstep;
MPI_Allreduce(&min, &min_glob, 1, MPI_INT, MPI_MIN, MPI_COMM_WORLD);
/* We check whether this is a full step where all particles are synchronized */
flag = 1;
for(n = 0; n < NumPart; n++)
if(P[n].Ti_endstep > min_glob)
flag = 0;
MPI_Allreduce(&flag, &Flag_FullStep, 1, MPI_INT, MPI_MIN, MPI_COMM_WORLD);
#ifdef PMGRID
if(min_glob >= All.PM_Ti_endstep)
{
min_glob = All.PM_Ti_endstep;
Flag_FullStep = 1;
}
#endif
/* Determine 'NumForceUpdate', i.e. the number of particles on this processor that are going to be active */
for(n = 0, NumForceUpdate = 0; n < NumPart; n++)
{
if(P[n].Ti_endstep == min_glob)
#ifdef SELECTIVE_NO_GRAVITY
if(!((1 << P[n].Type) & (SELECTIVE_NO_GRAVITY)))
#endif
NumForceUpdate++;
}
/* note: NumForcesSinceLastDomainDecomp has type "long long" */
temp = malloc(NTask * sizeof(int));
MPI_Allgather(&NumForceUpdate, 1, MPI_INT, temp, 1, MPI_INT, MPI_COMM_WORLD);
for(n = 0; n < NTask; n++)
All.NumForcesSinceLastDomainDecomp += temp[n];
#ifdef COUNT_ACTIVE_PARTICLES
long long NumActivePatricles;
NumActivePatricles=0;
for(n = 0; n < NTask; n++)
NumActivePatricles+=temp[n];
#endif
free(temp);
t1 = second();
All.CPU_Predict += timediff(t0, t1);
while(min_glob >= All.Ti_nextoutput && All.Ti_nextoutput >= 0)
{
move_particles(All.Ti_Current, All.Ti_nextoutput);
All.Ti_Current = All.Ti_nextoutput;
if(All.ComovingIntegrationOn)
All.Time = All.TimeBegin * exp(All.Ti_Current * All.Timebase_interval);
else
All.Time = All.TimeBegin + All.Ti_Current * All.Timebase_interval;
#ifdef OUTPUTPOTENTIAL
All.NumForcesSinceLastDomainDecomp = 1 + All.TotNumPart * All.TreeDomainUpdateFrequency;
domain_Decomposition();
compute_potential();
#endif
#ifndef OUTPUT_EVERY_TIMESTEP
savepositions(All.SnapshotFileCount++); /* write snapshot file */
#endif
All.Ti_nextoutput = find_next_outputtime(All.Ti_nextoutput + 1);
}
move_particles(All.Ti_Current, min_glob);
All.Ti_Current = min_glob;
if(All.ComovingIntegrationOn)
All.Time = All.TimeBegin * exp(All.Ti_Current * All.Timebase_interval);
else
All.Time = All.TimeBegin + All.Ti_Current * All.Timebase_interval;
All.TimeStep = All.Time - timeold;
#ifdef COUNT_ACTIVE_PARTICLES
if (ThisTask==0)
{
fprintf(FdTimings,"===========================================================================================\n");
fprintf(FdTimings,"Step = %06d Time = %g \n\n",All.NumCurrentTiStep,All.Time);
fprintf(FdTimings,"%g %g : Total number of active particles : %d%09d\n\n",All.Time,All.TimeStep,(int) (NumActivePatricles / 1000000000), (int) (NumActivePatricles % 1000000000));
}
int *numpartlist;
int i;
int tot;
numpartlist = malloc(sizeof(int) * NTask*6);
MPI_Gather(&N_gas, 1, MPI_INT, &numpartlist[NTask*0], 1, MPI_INT, 0, MPI_COMM_WORLD);
#ifdef STELLAR_PROP
MPI_Gather(&N_stars, 1, MPI_INT, &numpartlist[NTask*1], 1, MPI_INT, 0, MPI_COMM_WORLD);
#endif
MPI_Gather(&NumPart, 1, MPI_INT, &numpartlist[NTask*2], 1, MPI_INT, 0, MPI_COMM_WORLD);
if (ThisTask==0)
{
tot = 0;
fprintf(FdTimings,"gas ");
for (i=0;i<NTask;i++)
{
fprintf(FdTimings, "%12d ",numpartlist[NTask*0+i]); /* nombre de part par proc */
tot += numpartlist[NTask*0+i];
}
fprintf(FdTimings, " : %12d ",tot);
fprintf(FdTimings,"\n");
tot = 0;
fprintf(FdTimings,"stars ");
for (i=0;i<NTask;i++)
{
fprintf(FdTimings, "%12d ",numpartlist[NTask*1+i]); /* nombre de part par proc */
tot += numpartlist[NTask*1+i];
}
fprintf(FdTimings, " : %12d ",tot);
fprintf(FdTimings,"\n");
tot = 0;
fprintf(FdTimings,"remaining ");
for (i=0;i<NTask;i++)
{
fprintf(FdTimings, "%12d ",numpartlist[NTask*2+i]-numpartlist[NTask*1+i]-numpartlist[NTask*0+i]); /* nombre de part par proc */
tot += numpartlist[NTask*2+i]-numpartlist[NTask*1+i]-numpartlist[NTask*0+i];
}
fprintf(FdTimings, " : %12d ",tot);
fprintf(FdTimings,"\n\n");
tot = 0;
fprintf(FdTimings,"total ");
for (i=0;i<NTask;i++)
{
fprintf(FdTimings, "%12d ",numpartlist[NTask*2+i]); /* nombre de part par proc */
tot += numpartlist[NTask*2+i];
}
fprintf(FdTimings, " : %12d ",tot);
fprintf(FdTimings,"\n\n");
fflush(FdTimings);
}
free(numpartlist);
#endif
#ifdef DETAILED_CPU
tend = second();
All.CPU_Leapfrog += timediff(tstart, tend);
#endif
}
/*! this function returns the next output time that is equal or larger to
* ti_curr
*/
int find_next_outputtime(int ti_curr)
{
int i, ti, ti_next, iter = 0;
double next, time;
ti_next = -1;
if(All.OutputListOn)
{
for(i = 0; i < All.OutputListLength; i++)
{
time = All.OutputListTimes[i];
if(time >= All.TimeBegin && time <= All.TimeMax)
{
if(All.ComovingIntegrationOn)
ti = log(time / All.TimeBegin) / All.Timebase_interval;
else
ti = (time - All.TimeBegin) / All.Timebase_interval;
if(ti >= ti_curr)
{
if(ti_next == -1)
ti_next = ti;
if(ti_next > ti)
ti_next = ti;
}
}
}
}
else
{
if(All.ComovingIntegrationOn)
{
if(All.TimeBetSnapshot <= 1.0)
{
printf("TimeBetSnapshot > 1.0 required for your simulation.\n");
endrun(13123);
}
}
else
{
if(All.TimeBetSnapshot <= 0.0)
{
printf("TimeBetSnapshot > 0.0 required for your simulation.\n");
endrun(13123);
}
}
time = All.TimeOfFirstSnapshot;
iter = 0;
while(time < All.TimeBegin)
{
if(All.ComovingIntegrationOn)
time *= All.TimeBetSnapshot;
else
time += All.TimeBetSnapshot;
iter++;
if(iter > 1000000)
{
printf("Can't determine next output time.\n");
endrun(110);
}
}
while(time <= All.TimeMax)
{
if(All.ComovingIntegrationOn)
ti = log(time / All.TimeBegin) / All.Timebase_interval;
else
ti = (time - All.TimeBegin) / All.Timebase_interval;
if(ti >= ti_curr)
{
ti_next = ti;
break;
}
if(All.ComovingIntegrationOn)
time *= All.TimeBetSnapshot;
else
time += All.TimeBetSnapshot;
iter++;
if(iter > 1000000)
{
printf("Can't determine next output time.\n");
endrun(111);
}
}
}
if(ti_next == -1)
{
ti_next = 2 * TIMEBASE; /* this will prevent any further output */
if(ThisTask == 0)
printf("\nThere is no valid time for a further snapshot file.\n");
}
else
{
if(All.ComovingIntegrationOn)
next = All.TimeBegin * exp(ti_next * All.Timebase_interval);
else
next = All.TimeBegin + ti_next * All.Timebase_interval;
if(ThisTask == 0)
printf("\nSetting next time for snapshot file to Time_next= %g\n\n", next);
}
return ti_next;
}
/*! This routine writes one line for every timestep to two log-files. In
* FdInfo, we just list the timesteps that have been done, while in FdCPU the
* cumulative cpu-time consumption in various parts of the code is stored.
*/
void every_timestep_stuff(void)
{
double z;
#ifdef DETAILED_CPU
double tstart,tend;
tstart = second();
#endif
if(ThisTask == 0)
{
if(All.ComovingIntegrationOn)
{
z = 1.0 / (All.Time) - 1;
fprintf(FdInfo, "\nBegin Step %d, Time: %g, Redshift: %g, Systemstep: %g, Dloga: %g\n",
All.NumCurrentTiStep, All.Time, z, All.TimeStep,
log(All.Time) - log(All.Time - All.TimeStep));
printf("\nBegin Step %d, Time: %g, Redshift: %g, Systemstep: %g, Dloga: %g\n", All.NumCurrentTiStep,
All.Time, z, All.TimeStep, log(All.Time) - log(All.Time - All.TimeStep));
fflush(FdInfo);
}
else
{
fprintf(FdInfo, "\nBegin Step %d, Time: %g, Systemstep: %g\n", All.NumCurrentTiStep, All.Time,
All.TimeStep);
printf("\nBegin Step %d, Time: %g, Systemstep: %g\n", All.NumCurrentTiStep, All.Time, All.TimeStep);
fflush(FdInfo);
}
printf("-------------------------------------------------------------\n");
fflush(stdout);
#ifdef ADVANCEDCPUSTATISTICS
fprintf(FdCPU, "%d ", All.NumCurrentTiStep);
fprintf(FdCPU, "%g ", All.Time);
fprintf(FdCPU, "%d ", NTask);
fprintf(FdCPU,"%10.2f ",All.CPU_Total);
#ifdef DETAILED_CPU
fprintf(FdCPU,"%10.2f ",All.CPU_Leapfrog);
fprintf(FdCPU,"%10.2f ",All.CPU_Physics);
fprintf(FdCPU,"%10.2f ",All.CPU_Residual);
fprintf(FdCPU,"%10.2f ",All.CPU_Accel);
fprintf(FdCPU,"%10.2f ",All.CPU_Begrun);
#endif
fprintf(FdCPU,"%10.2f ",All.CPU_Gravity);
fprintf(FdCPU,"%10.2f ",All.CPU_Hydro);
#ifdef COOLING
fprintf(FdCPU,"%10.2f ",All.CPU_Cooling);
#endif
#ifdef SFR
fprintf(FdCPU,"%10.2f ",All.CPU_StarFormation);
#endif
#ifdef CHIMIE
fprintf(FdCPU,"%10.2f ",All.CPU_Chimie);
#endif
#ifdef MULTIPHASE
fprintf(FdCPU,"%10.2f ",All.CPU_Sticky);
#endif
fprintf(FdCPU,"%10.2f ",All.CPU_Domain);
fprintf(FdCPU,"%10.2f ",All.CPU_Potential);
fprintf(FdCPU,"%10.2f ",All.CPU_Predict);
fprintf(FdCPU,"%10.2f ",All.CPU_TimeLine);
fprintf(FdCPU,"%10.2f ",All.CPU_Snapshot);
fprintf(FdCPU,"%10.2f ",All.CPU_TreeWalk);
fprintf(FdCPU,"%10.2f ",All.CPU_TreeConstruction);
fprintf(FdCPU,"%10.2f ",All.CPU_CommSum);
fprintf(FdCPU,"%10.2f ",All.CPU_Imbalance);
fprintf(FdCPU,"%10.2f ",All.CPU_HydCompWalk);
fprintf(FdCPU,"%10.2f ",All.CPU_HydCommSumm);
fprintf(FdCPU,"%10.2f ",All.CPU_HydImbalance);
fprintf(FdCPU,"%10.2f ",All.CPU_EnsureNgb);
fprintf(FdCPU,"%10.2f ",All.CPU_PM);
fprintf(FdCPU,"%10.2f ",All.CPU_Peano);
#ifdef DETAILED_CPU_DOMAIN
fprintf(FdCPU,"%10.2f ",All.CPU_Domain_findExtend);
fprintf(FdCPU,"%10.2f ",All.CPU_Domain_determineTopTree);
fprintf(FdCPU,"%10.2f ",All.CPU_Domain_sumCost);
fprintf(FdCPU,"%10.2f ",All.CPU_Domain_findSplit);
fprintf(FdCPU,"%10.2f ",All.CPU_Domain_shiftSplit);
fprintf(FdCPU,"%10.2f ",All.CPU_Domain_countToGo);
fprintf(FdCPU,"%10.2f ",All.CPU_Domain_exchange);
#endif
#ifdef DETAILED_CPU_GRAVITY
fprintf(FdCPU,"%10.2f ",All.CPU_Gravity_TreeWalk1);
fprintf(FdCPU,"%10.2f ",All.CPU_Gravity_TreeWalk2);
fprintf(FdCPU,"%10.2f ",All.CPU_Gravity_CommSum1);
fprintf(FdCPU,"%10.2f ",All.CPU_Gravity_CommSum2);
fprintf(FdCPU,"%10.2f ",All.CPU_Gravity_Imbalance1);
fprintf(FdCPU,"%10.2f ",All.CPU_Gravity_Imbalance2);
#endif
fprintf(FdCPU,"\n");
fflush(FdCPU);
#else
fprintf(FdCPU, "Step %d, Time: %g, CPUs: %d\n", All.NumCurrentTiStep, All.Time, NTask);
fprintf(FdCPU,
"%10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f\n",
All.CPU_Total, All.CPU_Gravity, All.CPU_Hydro, All.CPU_Domain, All.CPU_Potential,
All.CPU_Predict, All.CPU_TimeLine, All.CPU_Snapshot, All.CPU_TreeWalk, All.CPU_TreeConstruction,
All.CPU_CommSum, All.CPU_Imbalance, All.CPU_HydCompWalk, All.CPU_HydCommSumm,
All.CPU_HydImbalance, All.CPU_EnsureNgb, All.CPU_PM, All.CPU_Peano);
fflush(FdCPU);
#endif
}
set_random_numbers();
#ifdef DETAILED_CPU
tend = second();
All.CPU_Residual += timediff(tstart, tend);
#endif
}
/*! This routine first calls a computation of various global quantities of the
* particle distribution, and then writes some statistics about the energies
* in the various particle components to the file FdEnergy.
*/
void energy_statistics(void)
{
compute_global_quantities_of_system();
if(ThisTask == 0)
{
fprintf(FdEnergy,
"%g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g\n",
All.Time, SysState.EnergyInt, SysState.EnergyPot, SysState.EnergyKin, SysState.EnergyIntComp[0],
SysState.EnergyPotComp[0], SysState.EnergyKinComp[0], SysState.EnergyIntComp[1],
SysState.EnergyPotComp[1], SysState.EnergyKinComp[1], SysState.EnergyIntComp[2],
SysState.EnergyPotComp[2], SysState.EnergyKinComp[2], SysState.EnergyIntComp[3],
SysState.EnergyPotComp[3], SysState.EnergyKinComp[3], SysState.EnergyIntComp[4],
SysState.EnergyPotComp[4], SysState.EnergyKinComp[4], SysState.EnergyIntComp[5],
SysState.EnergyPotComp[5], SysState.EnergyKinComp[5], SysState.MassComp[0],
SysState.MassComp[1], SysState.MassComp[2], SysState.MassComp[3], SysState.MassComp[4],
SysState.MassComp[5]);
fflush(FdEnergy);
}
}
/*! This routine first calls a computation of various global quantities of the
* particle distribution, and then writes some statistics about the energies
* in the various particle components to the file FdEnergy.
*/
#ifdef ADVANCEDSTATISTICS
void advanced_energy_statistics(void)
{
int i;
#ifdef DETAILED_CPU
double tstart,tend;
tstart = second();
#endif
compute_global_quantities_of_system();
if(ThisTask == 0)
{
/**************/
/* energy */
/**************/
/* time */
fprintf(FdEnergy,"%g ",All.Time);
/* total */
fprintf(FdEnergy,"%g %g %g ",SysState.EnergyInt, SysState.EnergyPot, SysState.EnergyKin);
#ifdef COOLING
fprintf(FdEnergy,"%g ",SysState.EnergyRadSph);
#endif
#ifdef AGN_HEATING
fprintf(FdEnergy,"%g ",SysState.EnergyAGNHeat);
#endif
#ifdef DISSIPATION_FORCES
fprintf(FdEnergy,"%g ",SysState.EnergyDissipationForces);
#endif
#ifdef INTEGRAL_CONSERVING_DISSIPATION
fprintf(FdEnergy,"%g ",SysState.EnergyICDissipation);
#endif
#ifdef MULTIPHASE
fprintf(FdEnergy,"%g ",SysState.EnergyRadSticky);
#endif
#ifdef FEEDBACK_WIND
fprintf(FdEnergy,"%g ",SysState.EnergyFeedbackWind);
#endif
#ifdef BUBBLES
fprintf(FdEnergy,"%g ",SysState.EnergyBubbles);
#endif
#ifdef CHIMIE_THERMAL_FEEDBACK
fprintf(FdEnergy,"%g ",SysState.EnergyThermalFeedback);
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
fprintf(FdEnergy,"%g ",SysState.EnergyKineticFeedback);
#endif
/* comp */
for (i=0;i<6;i++)
{
fprintf(FdEnergy,"%g %g %g ",SysState.EnergyIntComp[i],SysState.EnergyPotComp[i], SysState.EnergyKinComp[i]);
#ifdef COOLING
fprintf(FdEnergy,"%g ",SysState.EnergyRadSphComp[i]);
#endif
#ifdef AGN_HEATING
fprintf(FdEnergy,"%g ",SysState.EnergyAGNHeatComp[i]);
#endif
#ifdef DISSIPATION_FORCES
fprintf(FdEnergy,"%g ",SysState.EnergyDissipationForcesComp[i]);
#endif
#ifdef INTEGRAL_CONSERVING_DISSIPATION
fprintf(FdEnergy,"%g ",SysState.EnergyICDissipationComp[i]);
#endif
#ifdef MULTIPHASE
fprintf(FdEnergy,"%g ",SysState.EnergyRadStickyComp[i]);
#endif
#ifdef FEEDBACK_WIND
fprintf(FdEnergy,"%g ",SysState.EnergyFeedbackWindComp[i]);
#endif
#ifdef BUBBLES
fprintf(FdEnergy,"%g ",SysState.EnergyBubblesComp[i]);
#endif
#ifdef CHIMIE_THERMAL_FEEDBACK
fprintf(FdEnergy,"%g ",SysState.EnergyThermalFeedbackComp[i]);
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
fprintf(FdEnergy,"%g ",SysState.EnergyKineticFeedbackComp[i]);
#endif
}
/* mass */
for (i=0;i<6;i++)
{
fprintf(FdEnergy,"%g ",SysState.MassComp[i]);
}
/* return */
fprintf(FdEnergy,"\n");
fflush(FdEnergy);
#ifdef SYSTEMSTATISTICS
/**************/
/* system */
/**************/
fprintf(FdSystem,"%g %g %g %g %g %g %g %g %g %g %g %g %g\n",
All.Time,
SysState.Momentum[0], SysState.Momentum[1], SysState.Momentum[2], SysState.Momentum[3],
SysState.AngMomentum[0], SysState.AngMomentum[1], SysState.AngMomentum[2], SysState.AngMomentum[3],
SysState.CenterOfMass[0], SysState.CenterOfMass[1], SysState.CenterOfMass[2], SysState.CenterOfMass[3]);
fflush(FdSystem);
#endif
}
#ifdef DETAILED_CPU
tend = second();
All.CPU_Residual += timediff(tstart, tend);
#endif
}
#endif
diff --git a/src/system.c b/src/system.c
index e761625..89990af 100644
--- a/src/system.c
+++ b/src/system.c
@@ -1,191 +1,203 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
#include <signal.h>
#include <gsl/gsl_rng.h>
#include <mpi.h>
#include "allvars.h"
#include "proto.h"
/*! \file system.c
* \brief contains miscellaneous routines, e.g. elapsed time measurements
*/
/*! This routine returns a random number taken from a table of random numbers,
* which is refilled every timestep. This method is used to allow random
* number application to particles independent of the number of processors
* used, and independent of the particular order the particles have. In order
* to work properly, the particle IDs should be set properly to unique
* integer values.
*/
double get_random_number(int id)
{
return RndTable[(id % RNDTABLE)];
}
#ifdef SFR
double get_StarFormation_random_number(int id)
{
return StarFormationRndTable[(id % RNDTABLE)];
}
#endif
#ifdef FEEDBACK_WIND
double get_FeedbackWind_random_number(int id)
{
return FeedbackWindRndTable[(id % RNDTABLE)];
}
#endif
#ifdef CHIMIE
double get_Chimie_random_number(int id)
{
return ChimieRndTable[(id % RNDTABLE)];
}
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
double get_ChimieKineticFeedback_random_number(int id)
{
return ChimieKineticFeedbackRndTable[(id % RNDTABLE)];
}
#endif
#ifdef GAS_ACCRETION
double get_gasAccretion_random_number(int id)
{
return gasAccretionRndTable[(id % RNDTABLE)];
}
#endif
+#ifdef HOT_HALO
+double get_Halo_random_number(int id)
+{
+ return HaloRndTable[(id % RNDTABLE)];
+}
+#endif
+
+
/*! This routine fills the random number table.
*/
void set_random_numbers(void)
{
int i;
for(i = 0; i < RNDTABLE; i++)
RndTable[i] = gsl_rng_uniform(random_generator);
#ifdef SFR
for(i = 0; i < RNDTABLE; i++)
StarFormationRndTable[i] = gsl_rng_uniform(random_generator);
#endif
#ifdef FEEDBACK_WIND
for(i = 0; i < RNDTABLE; i++)
FeedbackWindRndTable[i] = gsl_rng_uniform(random_generator);
#endif
#ifdef CHIMIE
for(i = 0; i < RNDTABLE; i++)
ChimieRndTable[i] = gsl_rng_uniform(random_generator);
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
for(i = 0; i < RNDTABLE; i++)
ChimieKineticFeedbackRndTable[i] = gsl_rng_uniform(random_generator);
#endif
#ifdef GAS_ACCRETION
for(i = 0; i < RNDTABLE; i++)
gasAccretionRndTable[i] = gsl_rng_uniform(random_generator);
#endif
+#ifdef HOT_HALO
+ for(i = 0; i < RNDTABLE; i++)
+ HaloRndTable[i] = gsl_rng_uniform(random_generator);
+#endif
}
/*! returns the number of cpu-ticks in seconds that have elapsed, or the
* wall-clock time obtained with MPI_Wtime().
*/
double second(void)
{
#ifdef WALLCLOCK
return MPI_Wtime();
#else
return ((double) clock()) / CLOCKS_PER_SEC;
#endif
/* note: on AIX and presumably many other 32bit systems,
* clock() has only a resolution of 10ms=0.01sec
*/
}
/*! returns the time difference between two measurements obtained with
* second(). The routine takes care of the possible overflow of the tick
* counter on 32bit systems, but depending on the system, this may not always
* work properly. Similarly, in some MPI implementations, the MPI_Wtime()
* function may also overflow, in which case a negative time difference would
* be returned. The routine returns instead a time difference equal to 0.
*/
double timediff(double t0, double t1)
{
double dt;
dt = t1 - t0;
if(dt < 0) /* overflow has occured (for systems with 32bit tick counter) */
{
#ifdef WALLCLOCK
dt = 0;
#else
dt = t1 + pow(2, 32) / CLOCKS_PER_SEC - t0;
#endif
}
return dt;
}
/*! returns the maximum of two double
*/
double dmax(double x, double y)
{
if(x > y)
return x;
else
return y;
}
/*! returns the minimum of two double
*/
double dmin(double x, double y)
{
if(x < y)
return x;
else
return y;
}
/*! returns the maximum of two integers
*/
int imax(int x, int y)
{
if(x > y)
return x;
else
return y;
}
/*! returns the minimum of two integers
*/
int imin(int x, int y)
{
if(x < y)
return x;
else
return y;
}
diff --git a/src/vanishing.c b/src/vanishing.c
index e2b59a9..38d8a89 100644
--- a/src/vanishing.c
+++ b/src/vanishing.c
@@ -1,360 +1,440 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <mpi.h>
#include "allvars.h"
#include "proto.h"
#ifdef VANISHING_PARTICLES
/*
* This routine compute the accretion of gas
*/
-void vanishing_particles(void)
+void vanishing_particles(int time0, int time1)
{
-
+ int i;
if (ThisTask==0)
printf("Start vanishing particles...\n");
-
-
- /* flag the particles to be removed */
- vanishing_particles_flag();
-
-
+
/* remove the flaged particles */
vanishing_particles_remove();
+ /* flag the particles to be removed */
+ vanishing_particles_flag(time0, time1);
if (ThisTask==0)
printf("vanishing particles done.\n");
+ fflush(stdout);
+
+ NumForceUpdate = 0;
+ for(i=0;i<NumPart;i++)
+ {
+ if(P[i].Ti_endstep == All.Ti_Current)
+ NumForceUpdate++;
+ }
}
/*
* This routine flag the particles that needs
* to be removed.
* This routine can in principle be called anywere in the code.
*/
-void vanishing_particles_flag(void)
+void vanishing_particles_flag(int time0, int time1)
{
-
- int i;
-
-
- for(i = 0; i < NumPart; i++)
+ FLOAT vel;
+ int i,j;
+ //TODO: this with external functions otherwise looping over gas twice
+ for(i = 0; i < N_gas; i++)
{
/* here we flag the particles according to a condition */
-
- if (P[i].Pos[1]>49.5)
+#ifdef PERIODICOUTER
+ vel = P[i].Vel[1] - (All.TraceAngular[0]*(P[i].Pos[2]-All.TracePeriodPos[2]) - All.TraceAngular[2] * (P[i].Pos[0]-All.TracePeriodPos[0]));
+#else
+ vel = P[i].Vel[1];
+#endif
+ if (P[i].Pos[1] + All.Timebase_interval*(time1-time0)*vel> All.BoxSize-0.1)
{
- P[i].VanishingFlag=1;
+ if(P[i].VanishingFlag > 1)
+ P[i].VanishingFlag = 0;
+ else
+ {
+ P[i].VanishingFlag=1;
+ }
//printf("--> vanishing %d\n",i);
}
else
P[i].VanishingFlag=0;
}
-
-
+ for(i = 0; i < N_gas; i++)
+ {
+ //if(P[i].ID > P[N_gas+N_stars+1].ID) //New particle so follows old rules
+ //continue;
+ if(P[i].Pos[1] < 45)
+ continue;
+ for(j = 0;j<3;j++)
+ {
+ if (P[i].Pos[j] + All.Timebase_interval*(time1-time0)*P[i].Vel[j]> All.BoxSize-0.1)
+ P[i].VanishingFlag = 1;
+ else if (P[i].Pos[j] + All.Timebase_interval*(time1-time0)*P[i].Vel[j]< 0.1)
+ P[i].VanishingFlag = 1;
+ }
+ }
+ for(i = N_gas; i<NumPart;i++)
+ {
+ //if(P[i].Type == 0)
+ // if(P[i].ID > P[N_gas+N_stars+1].ID) //New particle so follows old rules
+ // continue;
+ P[i].VanishingFlag = 0; //Should already be 0 but just in case
+ for(j = 0;j<3;j++)
+ {
+ if (P[i].Pos[j] + All.Timebase_interval*(time1-time0)*P[i].Vel[j]> All.BoxSize-.1)
+ P[i].VanishingFlag = 1;
+ else if (P[i].Pos[j] + All.Timebase_interval*(time1-time0)*P[i].Vel[j]< 0.1)
+ P[i].VanishingFlag = 1;
+ }
+ }
}
int compact_StP(int oldN_stars)
{
int i,j;
int N_StP_removed=0;
for(i = 0, j = oldN_stars-1; i <oldN_stars; i++)
{
if (StP[i].PIdx==-1)
{
/* skip last particles that must be removed too */
while (StP[j].PIdx==-1)
{
N_StP_removed++;
j--;
}
if (i>=j)
{
break;
}
/* replace the particle */
P[StP[j].PIdx].StPIdx = i;
StP[i] = StP[j];
N_StP_removed++;
j--;
}
}
- printf("N_StP_removed=%d\n",N_StP_removed);
+ //printf("N_StP_removed=%d\n",N_StP_removed);
return N_StP_removed;
}
/*
* This routine remove the particles that have been flagged
* to be removed.
*/
void vanishing_particles_remove(void)
{
int DomainDecompFlag,DomainDecompFlagMax;
int i,j;
int N_gas_removed=0;
int N_stars_removed=0;
int N_other_removed=0;
int NumPart_removed=0;
int oldN_stars;
oldN_stars=N_stars;
/* be sure that all particles are in the right block */
rearrange_particle_sequence();
//printf("NumPart=%d\n",NumPart);
//printf("N_gas=%d\n",N_gas);
/******************************************/
/* remove block 0
/******************************************/
for(i = 0, j = N_gas-1; i < N_gas; i++)
{
if (P[i].VanishingFlag)
{
/* skip last particles that must be removed too */
while (P[j].VanishingFlag)
{
N_gas_removed++;
j--;
+
+ /* replace the particle */
+ //if(P[j].Ti_endstep == All.Ti_Current) /* if the particle was active, we need to decrease NumForceUpdate */
+ // NumForceUpdate--;
}
-
-
+
+
if (i>=j)
{
break;
}
-
- /* replace the particle */
- if(P[i].Ti_endstep == All.Ti_Current) /* if the particle was active, we need to decrease NumForceUpdate */
- NumForceUpdate--;
-
P[i] = P[j];
SphP[i] = SphP[j];
-
N_gas_removed++;
j--;
+
+ /* replace the particle */
+ //if(P[i].Ti_endstep == All.Ti_Current) /* if the particle was active, we need to decrease NumForceUpdate */
+ // NumForceUpdate--;
}
}
-
/* shift 1 */
- for(i = N_gas-N_gas_removed,j = (N_gas+N_stars)-1; i <N_gas ; i++,j--)
+ //for(i = N_gas-N_gas_removed,j = (N_gas+N_stars)-1; i <N_gas ; i++,j--)
+ if(N_gas_removed < N_stars)
{
- P[i] = P[j];
- StP[P[i].StPIdx].PIdx=i;
+ for(i = N_gas-N_gas_removed,j = (N_gas+N_stars)-1; i <N_gas ; i++,j--)
+ {
+
+ P[i] = P[j];
+ StP[P[i].StPIdx].PIdx=i;
+ }
+ }
+ else
+ {
+ for(i=N_gas-N_gas_removed; i < N_gas-N_gas_removed+N_stars;i++)
+ {
+
+ P[i] = P[i+N_gas_removed];
+ StP[P[i].StPIdx].PIdx=i;
+ }
}
/* shift others */
for(i = N_gas-N_gas_removed+N_stars,j = NumPart-1; i <(N_gas-N_gas_removed+N_stars)+N_gas_removed ; i++,j--)
{
P[i] = P[j];
}
N_gas=N_gas-N_gas_removed;
NumPart=NumPart-N_gas_removed;
/******************************************/
/* remove 1
/******************************************/
for(i = N_gas,j = N_gas+N_stars-1; i < N_gas+N_stars; i++)
{
if (P[i].VanishingFlag)
{
/* skip last particles that must be removed too */
while (P[j].VanishingFlag)
{
N_stars_removed++;
- j--;
+ j--;
+
+
+ /* replace the particle */
+ //if(P[j].Ti_endstep == All.Ti_Current) /* if the particle was active, we need to decrease NumForceUpdate */
+ // NumForceUpdate--;
}
+
if (i>=j)
{
break;
}
-
- /* replace the particle */
- if(P[i].Ti_endstep == All.Ti_Current) /* if the particle was active, we need to decrease NumForceUpdate */
- NumForceUpdate--;
-
- StP[P[i].StPIdx].PIdx=-1; /* set it as free */
- P[i] = P[j];
- StP[P[i].StPIdx].PIdx=i;
+ StP[P[i].StPIdx].PIdx=-1; /* set it as free */
+ P[i] = P[j];
+ StP[P[i].StPIdx].PIdx=i;
N_stars_removed++;
j--;
-
+
+ /* replace the particle */
+ //if(P[i].Ti_endstep == All.Ti_Current) /* if the particle was active, we need to decrease NumForceUpdate */
+ // NumForceUpdate--;
+
}
}
/* shift others */
for(i = N_gas+N_stars-N_stars_removed,j = NumPart-1; i < N_gas+N_stars ; i++,j--)
{
P[i] = P[j];
}
N_stars=N_stars-N_stars_removed;
NumPart=NumPart-N_stars_removed;
-
+#ifdef STELLAR_PROP
+ if(N_stars_removed > 0)
+ {
+ /* recover the link between P and StP */
+ for(i = N_gas; i < N_gas+N_stars; i++)
+ {
+ P[i].StPIdx = i-N_gas;
+ StP[P[i].StPIdx].PIdx=i;
+#ifdef CHECK_ID_CORRESPONDENCE
+ StP[P[i].StPIdx].ID = P[i].ID;
+#endif
+ }
+ }
+#endif
/******************************************/
/* remove others
/******************************************/
for(i = N_gas+N_stars,j = NumPart-1; i < NumPart; i++)
{
if (P[i].VanishingFlag)
{
/* skip last particles that must be removed too */
while (P[j].VanishingFlag)
{
//printf("skip j=%2d %2d\n",j,P[j]);
N_other_removed++;
- j--;
+ j--;
+
+ /* replace the particle */
+ //if(P[j].Ti_endstep == All.Ti_Current) /* if the particle was active, we need to decrease NumForceUpdate */
+ // NumForceUpdate--;
+
}
-
+
+
if (i>=j)
{
break;
}
- /* replace the particle */
- if(P[i].Ti_endstep == All.Ti_Current) /* if the particle was active, we need to decrease NumForceUpdate */
- NumForceUpdate--;
-
P[i] = P[j];
N_other_removed++;
- j--;
+ j--;
+
+ /* replace the particle */
+ //if(P[i].Ti_endstep == All.Ti_Current) /* if the particle was active, we need to decrease NumForceUpdate */
+ // NumForceUpdate--;
+
- }
+ }
+
}
NumPart=NumPart-N_other_removed;
compact_StP(oldN_stars);
NumPart_removed = N_gas_removed+N_stars_removed+N_other_removed;
//printf("N_gas_removed =%d\n",N_gas_removed);
//printf("N_stars_removed=%d\n",N_stars_removed);
//printf("N_other_removed=%d\n",N_other_removed);
//printf("NumPart_removed=%d\n",NumPart_removed);
if (NumPart_removed>0)
DomainDecompFlag=1;
/* gather flags */
MPI_Allreduce(&DomainDecompFlag, &DomainDecompFlagMax, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD);
if (DomainDecompFlagMax>0)
All.NumForcesSinceLastDomainDecomp = All.TotNumPart * All.TreeDomainUpdateFrequency + 1;
/* some checks */
for(i = 0; i < N_gas; i++)
{
//printf("%07d %d %g %g %g %g\n",i,P[i].Type,P[i].Pos[0],P[i].Pos[1],P[i].Pos[2],SphP[i].Hsml);
if (P[i].Type!=0)
{
endrun(999888777);
}
}
for(i = N_gas; i < NumPart; i++)
{
//printf("%07d %d %g %g %g\n",i,P[i].Type,P[i].Pos[0],P[i].Pos[1],P[i].Pos[2]);
if (P[i].Type==0)
{
endrun(999888778);
}
}
//printf("NumPart=%d\n",NumPart);
//printf("N_gas=%d\n",N_gas);
}
#endif

Event Timeline