Page MenuHomec4science

No OneTemporary

File Metadata

Created
Sun, Jul 21, 08:08
This file is larger than 256 KB, so syntax highlighting was skipped.
This document is not UTF8. It was detected as ISO-8859-1 (Latin 1) and converted to UTF8 for display.
diff --git a/PyGear/examples.tessel/TODO b/PyGear/examples.tessel/TODO
index 511de80..0c4a6e3 100644
--- a/PyGear/examples.tessel/TODO
+++ b/PyGear/examples.tessel/TODO
@@ -1,36 +1,31 @@
ghost.c
-- multiple insertion
- 1) on check le coté ou il est inséré (6 possibilités)
- 2) on vérifie qu'il existe déjà... (mais comment ???)
+-- check density, compare with sph (./plot_density.py)
+-- ittération pour trouver correctement les voisins
+-- parallelisme
+--
+
-All.BunchSizeDensity BunchSizeGhost
-DensDataPartialResult
-DensDataResult
-densdata_in
-densdata_out
-DensDataIn
-DensDataGet
//
1) include some points, using h_i
2) insert in the tesselation
3) compute for each point, s_i,
the 2* the max of the radius of all curcumsphere
belonging to triangles that have Pi as point
4) if h_i > s_i -> stop for this point
5) else, increase h_i and do 1) again.
diff --git a/PyGear/examples.tessel/area/area.py b/PyGear/examples.tessel/area/area.py
new file mode 100644
index 0000000..a1252e3
--- /dev/null
+++ b/PyGear/examples.tessel/area/area.py
@@ -0,0 +1,80 @@
+# http://fr.wikipedia.org/wiki/Aire_et_centre_de_masse_d%27un_polygone
+# info pour le centre de masse
+
+from numpy import *
+
+"""
+
+3.37792690924
+[[ 7.89272115e-02 3.56209427e-01 0.00000000e+00]
+ [ 7.86051601e-02 3.44835401e-01 0.00000000e+00]
+ [ -1.65303441e-04 2.60916293e-01 0.00000000e+00]
+ [ -3.71612213e-03 2.62126237e-01 0.00000000e+00]
+ [ -2.41694115e-02 3.86349469e-01 0.00000000e+00]]
+0.333918269909
+[[ 0.99983442 0.2609162 0. ]
+ [ 0.99628341 0.26212624 0. ]
+ [ 0.97583008 0.3863498 0. ]
+ [ 1.07892728 0.35620958 0. ]
+ [ 1.07860518 0.34483576 0. ]]
+"""
+
+
+pos = array([[ 7.89272115e-02, 3.56209427e-01, 0.00000000e+00],
+ [ 7.86051601e-02, 3.44835401e-01, 0.00000000e+00],
+ [ -1.65303441e-04, 2.60916293e-01, 0.00000000e+00],
+ [ -3.71612213e-03, 2.62126237e-01, 0.00000000e+00],
+ [ -2.41694115e-02, 3.86349469e-01, 0.00000000e+00]])
+
+'''
+pos = array([[ 0.99983442, 0.2609162, 0. ],
+ [ 0.99628341, 0.26212624, 0. ],
+ [ 0.97583008, 0.3863498, 0. ],
+ [ 1.07892728, 0.35620958, 0. ],
+ [ 1.07860518, 0.34483576, 0. ]])
+'''
+
+print pos
+print
+
+
+A = 0
+
+for i in xrange(len(pos)-1):
+
+ pos1 = pos[i]
+ pos2 = pos[i+1]
+
+ x1 = pos1[0]
+ y1 = pos1[1]
+ x2 = pos2[0]
+ y2 = pos2[1]
+
+ print x1,y1
+ print x2,y2
+
+ A = A + (x1*y2 - x2*y1)
+
+
+# first again
+pos1 = pos[len(pos)-1]
+pos2 = pos[0]
+
+x1 = pos1[0]
+y1 = pos1[1]
+x2 = pos2[0]
+y2 = pos2[1]
+
+print x1,y1
+print x2,y2
+
+A = A + (x1*y2 - x2*y1)
+
+
+
+A = 0.5*A
+
+print
+print A
+
+
diff --git a/PyGear/examples.tessel/ghost.dat.0 b/PyGear/examples.tessel/ghost.dat.0
deleted file mode 100644
index 805098a..0000000
Binary files a/PyGear/examples.tessel/ghost.dat.0 and /dev/null differ
diff --git a/PyGear/examples.tessel/mksnap.py b/PyGear/examples.tessel/mksnap.py
index 0529b17..8a5ec95 100755
--- a/PyGear/examples.tessel/mksnap.py
+++ b/PyGear/examples.tessel/mksnap.py
@@ -1,30 +1,29 @@
#!/usr/bin/env python
from pNbody import ic
from pNbody import libutil
from numpy import *
import sys
import time
import copy
from PyGear import gadget
-#random.seed(0) # 2 for two points
###################################
# generate model
-n = 100
-nb = ic.box(n,0.5,0.5,0.5,ftype='gadget')
+n = 1000
+nb = ic.box(n,0.5,0.5,0.5,ftype='gadget',irand=0)
#nb = ic.plummer(n,1,1,1,eps=0.1,rmax=1.,ftype='gadget')
nb.pos[:,2] = nb.pos[:,2]*0
nb.pos = nb.pos + 0.5
nb.rename('snap.dat')
nb.write()
diff --git a/PyGear/examples.tessel/mksnap.py b/PyGear/examples.tessel/mksnap2.py
similarity index 67%
copy from PyGear/examples.tessel/mksnap.py
copy to PyGear/examples.tessel/mksnap2.py
index 0529b17..e55f4d4 100755
--- a/PyGear/examples.tessel/mksnap.py
+++ b/PyGear/examples.tessel/mksnap2.py
@@ -1,30 +1,29 @@
#!/usr/bin/env python
from pNbody import ic
from pNbody import libutil
from numpy import *
import sys
import time
import copy
from PyGear import gadget
-#random.seed(0) # 2 for two points
###################################
# generate model
-n = 100
-nb = ic.box(n,0.5,0.5,0.5,ftype='gadget')
-#nb = ic.plummer(n,1,1,1,eps=0.1,rmax=1.,ftype='gadget')
+n = 1000
+#nb = ic.box(n,0.5,0.5,0.5,ftype='gadget',irand=0)
+nb = ic.plummer(n,1,1,1,eps=0.1,rmax=1.,ftype='gadget')
nb.pos[:,2] = nb.pos[:,2]*0
nb.pos = nb.pos + 0.5
nb.rename('snap.dat')
nb.write()
diff --git a/PyGear/examples.tessel/plot_density.py b/PyGear/examples.tessel/plot_density.py
new file mode 100755
index 0000000..4e14315
--- /dev/null
+++ b/PyGear/examples.tessel/plot_density.py
@@ -0,0 +1,18 @@
+#!/usr/bin/env python
+
+import Ptools as pt
+from pNbody import *
+
+nb = Nbody(sys.argv[1],ftype='gadget')
+
+
+nb.cmcenter()
+
+r = nb.rxyz()
+
+pt.scatter(r,nb.rho,s=1)
+pt.scatter(r,nb.rsp,color='red',s=1)
+
+
+
+pt.show()
diff --git a/PyGear/examples.tessel/snap+ghost.dat.0 b/PyGear/examples.tessel/snap+ghost.dat.0
deleted file mode 100644
index 6b6019b..0000000
Binary files a/PyGear/examples.tessel/snap+ghost.dat.0 and /dev/null differ
diff --git a/PyGear/examples.tessel/snap.dat b/PyGear/examples.tessel/snap.dat
deleted file mode 100644
index 72cd46f..0000000
Binary files a/PyGear/examples.tessel/snap.dat and /dev/null differ
diff --git a/PyGear/examples.tessel/snap2.dat.0 b/PyGear/examples.tessel/snap2.dat.0
deleted file mode 100644
index 031e8c5..0000000
Binary files a/PyGear/examples.tessel/snap2.dat.0 and /dev/null differ
diff --git a/PyGear/examples.tessel/test_mpi.py b/PyGear/examples.tessel/test_mpi.py
index abf5974..e2e1171 100755
--- a/PyGear/examples.tessel/test_mpi.py
+++ b/PyGear/examples.tessel/test_mpi.py
@@ -1,105 +1,187 @@
#!/usr/bin/env python
from pNbody import *
from pNbody import ic
from pNbody import libutil
from numpy import *
import sys
import time
import copy
from PyGear import gadget
nb = Nbody("snap.dat",ftype="gadget")
###################################
# init PyGear
gadget.InitMPI() # init MPI
gadget.InitDefaultParameters() # init default parameters
gadget.Info()
params = {}
params['ErrTolTheta'] = 0.7
params['DesNumNgb'] = 50
params['MaxNumNgbDeviation'] = 1
params['UnitLength_in_cm'] = 3.085e+21
params['UnitMass_in_g'] = 4.435693e+44
params['UnitVelocity_in_cm_per_s'] = 97824708.2699
params['BoxSize'] = 1.0
+params['PartAllocFactor'] = 10
gadget.SetParameters(params)
###################################
# load particles
gadget.LoadParticles(array(nb.npart),nb.pos,nb.vel,nb.mass,nb.num,nb.tpe)
###################################
# compute Delaunay
t1 = time.time()
gadget.ConstructDelaunay()
t2 = time.time()
print "Delaunay","in",(t2-t1),"s"
+###################################
+# compute Voronoi
+
+t1 = time.time()
+gadget.ComputeVoronoi()
+t2 = time.time()
+
+print "Voronoi","in",(t2-t1),"s"
+
+
+
+
+
+
###################################
# retrieve ghost points
gpos = gadget.GetAllGhostPositions()
-
gnb = Nbody(pos=gpos,ftype='gadget')
+
+gnb.u = zeros(gnb.nbody)
+gnb.rho = gadget.GetAllGhostvDensities()
+gnb.rsp = gadget.GetAllGhostvVolumes()
+gnb.init()
+
# save
gnb.rename('ghost.dat')
gnb.set_pio("yes")
gnb.write()
###################################
-# retrieve physical values
+# retrieve points
nb.pos = gadget.GetAllPositions()
nb.vel = gadget.GetAllVelocities()
nb.mass = gadget.GetAllMasses()
nb.num = gadget.GetAllID()
nb.tpe = None
nb.u = gadget.GetAllEnergySpec() # not defined
-nb.rho = gadget.GetAllDensities()
-nb.rsp = gadget.GetAllHsml()
+nb.rho = gadget.GetAllvDensities() # note the v
+nb.rsp = gadget.GetAllvVolumes()
+nb.rsp = gadget.GetAllDensities() # put sph densities in rsp
+
nb.init()
+
# save
nb.rename('snap2.dat')
nb.set_pio("yes")
nb.write()
-
# save all
-gnb.u = zeros(gnb.nbody)
-gnb.rho = zeros(gnb.nbody)
-gnb.rsp = zeros(gnb.nbody)
+#nbtot = nb + gnb
+nbtot = copy.deepcopy(nb) # this is important to avoid to mix particles
+nbtot.append(gnb,do_not_sort=True) # then they are incompatible with vpos below
-nb = nb + gnb
-nb.rename('snap+ghost.dat')
-nb.write()
+nbtot.rename('snap+ghost.dat')
+nbtot.write()
+
+
+
+
+
+###################################
+# get some values
+TriangleList = gadget.GetAllDelaunayTriangles()
+
+
+rho,mn,mx,cd = libutil.set_ranges(nbtot.rho,scale='log')
+rho = rho/255.
+#rho = clip(nbtot.rho,0,1)
+
+
+
+###################################
+# plot
+###################################
+sys.exit()
+
+import Ptools as pt
+import plot
+
+
+########################
+# draw a box
+plot.draw_box(x=array([0,1,1,0]),y=array([0,0,1,1]))
+
+########################
+# draw the triangles
+
+i = 0
+for Triangle in TriangleList:
+ P1 = Triangle['coord'][0]
+ P2 = Triangle['coord'][1]
+ P3 = Triangle['coord'][2]
+ #plot.draw_triangle(P1,P2,P3,c='r')
+
+ #cm = 1/3.*(P1+P2+P3)
+ #pt.text(cm[0],cm[1],Triangle['id'],fontsize=12,horizontalalignment='center',verticalalignment='center')
+
+
+########################
+# draw the points
+#pt.scatter( nb.pos[:,0], nb.pos[:,1],lw=0,s=50,color='r')
+#pt.scatter(gnb.pos[:,0],gnb.pos[:,1],lw=0,s=50)
+
+
+
+########################
+# draw the Voronoi
+
+cmap = pt.GetColormap('rainbow4',revesed=False)
+# single point with vpoints
+for i in xrange(nbtot.nbody):
+ vpos = gadget.GetvPointsForOnePoint(i)
+ #pt.scatter(nb.pos[i,0],nb.pos[i,1],lw=0,s=50)
+ plot.draw_cell(vpos,color=[rho[i],rho[i],rho[i]],alpha=0.8)
+pt.axis([-0.1,1.1,-0.1,1.1])
+pt.show()
diff --git a/PyGear/setup.py b/PyGear/setup.py
index fd7c31e..602a7d3 100644
--- a/PyGear/setup.py
+++ b/PyGear/setup.py
@@ -1,58 +1,58 @@
#!/usr/bin/env python
import os,sys
from distutils.core import setup, Extension
from distutils.sysconfig import get_python_inc
from distutils.sysconfig import get_python_lib
import glob
'''
In order to compile with mpi,
export CC=mpicc
python setup.py build
'''
incdir = os.path.join(get_python_inc(plat_specific=1), 'numpy')
libdir = os.path.join(get_python_lib(plat_specific=1), 'numpy')
gadget_files=glob.glob("src/*.c")
PYTHON_INC = "/usr/include/python2.6/"
MPI_DIR = "/usr/lib64/openmpi/lib/"
MPI_LIB = "mpi"
MPI_INC = "/usr/include/openmpi-x86_64/"
setup(name='PyGear',
version='0.0',
description='Python Gadget Wrapping',
author='Yves Revaz',
author_email='yves.revaz@epfl.ch',
url='http://obswww.unige.ch/~revaz/pNbody',
packages=['PyGear'],
# ext_modules=[
# Extension('PyGear.gadget', gadget_files,include_dirs=[MPI_INC,"src/",PYTHON_INC],define_macros=[('PY_INTERFACE', '1'),('UNEQUALSOFTENINGS', '1') ,('PERIODIC', '1'),('PEANOHILBERT', '1'),('NOGRAVITY', '1'),('LONG_X', '1'),('LONG_Y', '1'),('LONG_Z', '0.125')] , library_dirs=[MPI_DIR],libraries=['gsl','gslcblas','m',MPI_LIB] )
# ]
# ext_modules=[
# Extension('PyGear.gadget', gadget_files,include_dirs=[MPI_INC,"src/",PYTHON_INC],define_macros=[('PY_INTERFACE', '1'),('UNEQUALSOFTENINGS', '1') ,('PERIODIC', '1'),('PEANOHILBERT', '1')] , library_dirs=[MPI_DIR],libraries=['gsl','gslcblas','m',MPI_LIB] )
# ]
ext_modules=[
- Extension('PyGear.gadget', gadget_files,include_dirs=[MPI_INC,"src/",PYTHON_INC],define_macros=[('PY_INTERFACE', '1'),('UNEQUALSOFTENINGS', '1') ,('PEANOHILBERT', '1'),('PERIODIC', '1'),('TESSEL', '1'),('NOGRAVITY', '1'),('LONG_X', '1'),('LONG_Y', '1'),('LONG_Z', '1')] , library_dirs=[MPI_DIR],libraries=['gsl','gslcblas','m',MPI_LIB] )
+ Extension('PyGear.gadget', gadget_files,include_dirs=[MPI_INC,"src/",PYTHON_INC],define_macros=[('PY_INTERFACE', '1'),('UNEQUALSOFTENINGS', '1') ,('PEANOHILBERT', '1'),('PERIODIC', '1'),('TESSEL', '1'),('NOGRAVITY', '1'),('LONG_X', '1'),('LONG_Y', '1'),('LONG_Z', '1'),('TWODIMS', '1')] , library_dirs=[MPI_DIR],libraries=['gsl','gslcblas','m',MPI_LIB] )
]
)
diff --git a/src/allvars.c b/src/allvars.c
index 35386f8..27a4ea8 100644
--- a/src/allvars.c
+++ b/src/allvars.c
@@ -1,454 +1,454 @@
/*! \file allvars.c
* \brief provides instances of all global variables.
*/
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include "tags.h"
#include "allvars.h"
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
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 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. */
#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
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 */
#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 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 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 particle_data
- *gP;
+//struct ghost_particle_data
+// *gP;
int NumgPart;
#endif /* TESSEL */
#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 a61a47f..6cc436d 100644
--- a/src/allvars.h
+++ b/src/allvars.h
@@ -1,1916 +1,1921 @@
/*! \file allvars.h
* \brief declares global variables.
*
* This file declares all global variables. Further variables should be added here, and declared as
* 'extern'. The actual existence of these variables is provided by the file 'allvars.c'. To produce
* 'allvars.c' from 'allvars.h', do the following:
*
* - Erase all #define's, typedef's, and enum's
* - add #include "allvars.h", delete the #ifndef ALLVARS_H conditional
* - delete all keywords 'extern'
* - delete all struct definitions enclosed in {...}, e.g.
* "extern struct global_data_all_processes {....} All;"
* becomes "struct global_data_all_processes All;"
*/
#ifndef ALLVARS_H
#define ALLVARS_H
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_integration.h>
#include "tags.h"
#define GADGETVERSION "2.0" /*!< code version string */
#define TIMEBASE (1<<28) /*!< The simulated timespan is mapped onto the integer interval [0,TIMESPAN],
* where TIMESPAN needs to be a power of 2. Note that (1<<28) corresponds to 2^29
*/
#define MAXTOPNODES 200000 /*!< Maximum number of nodes in the top-level tree used for domain decomposition */
typedef long long peanokey; /*!< defines the variable type used for Peano-Hilbert keys */
#define BITS_PER_DIMENSION 18 /*!< Bits per dimension available for Peano-Hilbert order.
Note: If peanokey is defined as type int, the allowed maximum is 10.
If 64-bit integers are used, the maximum is 21 */
#define PEANOCELLS (((peanokey)1)<<(3*BITS_PER_DIMENSION)) /*!< The number of different Peano-Hilbert cells */
#define RNDTABLE 3000 /*!< gives the length of a table with random numbers, refreshed at every timestep.
This is used to allow application of random numbers to a specific particle
in a way that is independent of the number of processors used. */
#define MAX_REAL_NUMBER 1e37
#define MIN_REAL_NUMBER 1e-37
#define MAXLEN_FILENAME 100 /*!< Maximum number of characters for filenames (including the full path) */
#ifdef ISOTHERM_EQS
#define GAMMA (1.0) /*!< index for isothermal gas */
#else
#define GAMMA (5.0/3) /*!< adiabatic index of simulated gas */
#endif
#define GAMMA_MINUS1 (GAMMA-1)
#define HYDROGEN_MASSFRAC 0.76 /*!< mass fraction of hydrogen, relevant only for radiative cooling */
/* Some physical constants in cgs units */
#define GRAVITY 6.672e-8 /*!< Gravitational constant (in cgs units) */
#define SOLAR_MASS 1.989e33
#define SOLAR_LUM 3.826e33
#define RAD_CONST 7.565e-15
#define AVOGADRO 6.0222e23
#define BOLTZMANN 1.3806e-16
#define GAS_CONST 8.31425e7
#define C 2.9979e10
#define PLANCK 6.6262e-27
#define CM_PER_MPC 3.085678e24
#define PROTONMASS 1.6726e-24
#define ELECTRONMASS 9.10953e-28
#define THOMPSON 6.65245e-25
#define ELECTRONCHARGE 4.8032e-10
#define HUBBLE 3.2407789e-18 /* in h/sec */
#define YEAR_IN_SECOND 31536000.0 /* year in sec */
#define FEH_SOLAR 0.00181 /* used only if cooling with metal is on and chimie is off */
#define PI 3.1415926535897931
#define TWOPI 6.2831853071795862
/* Some conversion factors */
#define SEC_PER_MEGAYEAR 3.155e13
#define SEC_PER_YEAR 3.155e7
#ifndef ASMTH
#define ASMTH 1.25 /*!< ASMTH gives the scale of the short-range/long-range force split in units of FFT-mesh cells */
#endif
#ifndef RCUT
#define RCUT 4.5 /*!< RCUT gives the maximum distance (in units of the scale used for the force split) out to
which short-range forces are evaluated in the short-range tree walk. */
#endif
#define MAX_NGB 20000 /*!< defines maximum length of neighbour list */
#define MAXLEN_OUTPUTLIST 500 /*!< maxmimum number of entries in list of snapshot output times */
#define DRIFT_TABLE_LENGTH 1000 /*!< length of the lookup table used to hold the drift and kick factors */
#ifdef COSMICTIME
#define COSMICTIME_TABLE_LENGTH 1000 /*!< length of the lookup table used for the cosmic time computation */
#endif
#define MAXITER 1000 /*!< maxmimum number of steps for SPH neighbour iteration */
#ifdef DOUBLEPRECISION /*!< If defined, the variable type FLOAT is set to "double", otherwise to FLOAT */
#define FLOAT double
#else
#define FLOAT float
#endif
#ifndef TWODIMS
#define NUMDIMS 3 /*!< For 3D-normalized kernel */
#define KERNEL_COEFF_1 2.546479089470 /*!< Coefficients for SPH spline kernel and its derivative */
#define KERNEL_COEFF_2 15.278874536822
#define KERNEL_COEFF_3 45.836623610466
#define KERNEL_COEFF_4 30.557749073644
#define KERNEL_COEFF_5 5.092958178941
#define KERNEL_COEFF_6 (-15.278874536822)
#define NORM_COEFF 4.188790204786 /*!< Coefficient for kernel normalization. Note: 4.0/3 * PI = 4.188790204786 */
#else
#define NUMDIMS 2 /*!< For 2D-normalized kernel */
#define KERNEL_COEFF_1 (5.0/7*2.546479089470) /*!< Coefficients for SPH spline kernel and its derivative */
#define KERNEL_COEFF_2 (5.0/7*15.278874536822)
#define KERNEL_COEFF_3 (5.0/7*45.836623610466)
#define KERNEL_COEFF_4 (5.0/7*30.557749073644)
#define KERNEL_COEFF_5 (5.0/7*5.092958178941)
#define KERNEL_COEFF_6 (5.0/7*(-15.278874536822))
#define NORM_COEFF M_PI /*!< Coefficient for kernel normalization. */
#endif
#ifdef MULTIPHASE
#define GAS_SPH 0
#define GAS_STICKY 1
#define GAS_DARK 2
#endif
#if defined(SFR) || defined(STELLAR_PROP)
#define ST 1
#endif
#ifdef CHIMIE
#define NELEMENTS 5
#define MAXNELEMENTS 64
#define FIRST_ELEMENT "Fe"
#define FE 0
#endif
#ifdef COOLING
#define COOLING_NMETALICITIES 9
#define COOLING_NTEMPERATURES 171
#endif
#ifdef COMPUTE_VELOCITY_DISPERSION
#define VELOCITY_DISPERSION_SIZE 3
#endif
extern int SetMinTimeStepForActives;
extern int ThisTask; /*!< the rank of the local processor */
extern int NTask; /*!< number of processors */
extern int PTask; /*!< smallest integer such that NTask <= 2^PTask */
extern int NumPart; /*!< number of particles on the LOCAL processor */
extern int N_gas; /*!< number of gas particles on the LOCAL processor */
#if defined(SFR) || defined(STELLAR_PROP)
extern int N_stars; /*!< number of stars particle on the LOCAL processor */
#endif
#ifdef MULTIPHASE
extern int N_sph;
extern int N_sticky;
extern int N_stickyflaged;
extern int N_dark;
extern int NumColPotLocal; /*!< local number of potentially collisional particles */
extern int NumColPot; /*!< total number of potentially collisional particles */
extern int NumColLocal; /*!< local number of collisions */
extern int NumCol; /*!< total number of collisions */
extern int NumNoColLocal;
extern int NumNoCol;
#endif
extern long long Ntype[6]; /*!< total number of particles of each type */
extern int NtypeLocal[6]; /*!< local number of particles of each type */
extern int NumForceUpdate; /*!< number of active particles on local processor in current timestep */
extern int NumSphUpdate; /*!< number of active SPH particles on local processor in current timestep */
#ifdef CHIMIE
extern int NumStUpdate;
#endif
#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 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. */
#endif
#ifdef MULTIPHASE
extern FILE *FdPhase; /*!< file handle for pase.txt log-file. */
extern FILE *FdSticky; /*!< file handle for sticky.txt log-file. */
#endif
#ifdef AGN_ACCRETION
extern FILE *FdAccretion; /*!< file handle for accretion.txt log-file. */
#endif
#ifdef BONDI_ACCRETION
extern FILE *FdBondi; /*!< file handle for bondi.txt log-file. */
#endif
#ifdef BUBBLES
extern FILE *FdBubble; /*!< file handle for bubble.txt log-file. */
#endif
extern double DriftTable[DRIFT_TABLE_LENGTH]; /*!< table for the cosmological drift factors */
extern double GravKickTable[DRIFT_TABLE_LENGTH]; /*!< table for the cosmological kick factor for gravitational forces */
extern double HydroKickTable[DRIFT_TABLE_LENGTH]; /*!< table for the cosmological kick factor for hydrodynmical forces */
#ifdef COSMICTIME
extern double CosmicTimeTable[COSMICTIME_TABLE_LENGTH]; /*!< table for the computation of cosmic time */
#endif
extern void *CommBuffer; /*!< points to communication buffer, which is used in the domain decomposition, the
parallel tree-force computation, the SPH routines, etc. */
/*! This structure contains data which is the SAME for all tasks (mostly code parameters read from the
* parameter file). Holding this data in a structure is convenient for writing/reading the restart file, and
* it allows the introduction of new global variables in a simple way. The only thing to do is to introduce
* them into this structure.
*/
extern struct global_data_all_processes
{
long long TotNumPart; /*!< total particle numbers (global value) */
long long TotN_gas; /*!< total gas particle number (global value) */
#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 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;
char CoolingFile[MAXLEN_FILENAME]; /*!< cooling file */
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_cooling_data_max;
double CoolingParameters_cooling_data[COOLING_NMETALICITIES][COOLING_NTEMPERATURES];
int CoolingParameters_p;
int CoolingParameters_q;
#endif
#ifdef CHIMIE
int ChimieNumberOfParameterFiles;
char ChimieParameterFile[MAXLEN_FILENAME]; /*!< chimie parameter file */
double ChimieSupernovaEnergy;
double ChimieKineticFeedbackFraction;
double ChimieWindSpeed;
double ChimieWindTime;
double ChimieSNIaThermalTime;
double ChimieSNIIThermalTime;
double ChimieMaxSizeTimestep;
#endif
#if defined (CHIMIE) || defined (COOLING)
double InitGasMetallicity;
#endif
#if !defined (HEATING_PE)
double HeatingPeElectronFraction;
#endif
#if !defined (HEATING_PE) || defined (STELLAR_FLUX) || defined (EXTERNAL_FLUX)
double HeatingPeSolarEnergyDensity;
#endif
#if !defined (HEATING_PE) || defined (STELLAR_FLUX)
double HeatingPeLMRatioGas;
double HeatingPeLMRatioHalo;
double HeatingPeLMRatioDisk;
double HeatingPeLMRatioBulge;
double HeatingPeLMRatioStars;
double HeatingPeLMRatioBndry;
double HeatingPeLMRatio[6];
#endif
#ifdef EXTERNAL_FLUX
double HeatingExternalFLuxEnergyDensity;
#endif
#ifdef MULTIPHASE
double CriticalTemperature;
double CriticalEgySpec;
double CriticalNonCollisionalTemperature;
double CriticalNonCollisionalEgySpec;
#ifdef COLDGAS_CYCLE
double ColdGasCycleTransitionTime;
double ColdGasCycleTransitionParameter;
#endif
#endif
#ifdef MULTIPHASE
/* some STICKY parameters */
int StickyUseGridForCollisions;
double StickyTime; /*!< Cooling time of sticky particle collision */
double StickyCollisionTime;
double StickyLastCollisionTime;
double StickyIdleTime;
double StickyMinVelocity;
double StickyMaxVelocity;
int StickyGridNx;
int StickyGridNy;
int StickyGridNz;
double StickyGridXmin;
double StickyGridXmax;
double StickyGridYmin;
double StickyGridYmax;
double StickyGridZmin;
double StickyGridZmax;
double StickyLambda;
double StickyDensity;
double StickyDensityPower;
double StickyBetaR;
double StickyBetaT;
double StickyRsphFact; /*!< Fraction of the sph radius used in sticky particle */
#endif
#ifdef OUTERPOTENTIAL
#ifdef NFW
double HaloConcentration;
double HaloMass;
double GasMassFraction;
double NFWPotentialCte;
double Rs;
#endif
#ifdef PLUMMER
double PlummerMass;
double PlummerSoftenning;
double PlummerPotentialCte;
#endif
#ifdef MIYAMOTONAGAI
double MiyamotoNagaiMass;
double MiyamotoNagaiHr;
double MiyamotoNagaiHz;
double MiyamotoNagaiPotentialCte;
#endif
#ifdef PISOTHERM
double Rho0;
double Rc;
double PisothermPotentialCte;
double GasMassFraction;
double PotentialInf;
gsl_function PotentialF;
gsl_integration_workspace *Potentialw;
#endif
#ifdef CORIOLIS
double CoriolisOmegaX;
double CoriolisOmegaY;
double CoriolisOmegaZ;
double CoriolisOmegaX0;
double CoriolisOmegaY0;
double CoriolisOmegaZ0;
#endif
#endif
#ifdef SFR
int StarFormationNStarsFromGas;
double StarFormationStarMass;
double StarFormationMgMsFraction;
int StarFormationType;
double StarFormationCstar;
double StarFormationTime;
double StarFormationDensity;
double StarFormationTemperature;
double ThresholdDensity;
#endif
#ifdef FEEDBACK
double SupernovaTime;
#endif
#ifdef FEEDBACK_WIND
double SupernovaWindEgySpecPerMassUnit;
double SupernovaWindFractionInEgyKin;
double SupernovaWindParameter;
double SupernovaWindSpeed;
double SupernovaWindIntAccuracy;
#endif
#ifdef AGN_ACCRETION
double TimeBetAccretion;
double AccretionRadius;
double AGNFactor;
double MinMTotInRa;
double TimeLastAccretion;
double LastMTotInRa;
double MTotInRa;
double dMTotInRa;
#endif
#ifdef BUBBLES
char BubblesInitFile[MAXLEN_FILENAME]; /*!< bubble file */
double *BubblesTime;
double *BubblesD;
double *BubblesR;
double *BubblesE;
double *BubblesA;
double *BubblesB;
int BubblesIndex;
double BubblesAlpha;
double BubblesBeta;
double BubblesDelta;
double BubblesRadiusFactor;
double EnergyBubbles;
#endif
#ifdef AGN_HEATING
double AGNHeatingPower;
double AGNHeatingRmax;
#endif
#ifdef BONDI_ACCRETION
double BondiEfficiency;
double BondiBlackHoleMass;
double BondiHsmlFactor;
double BondiPower;
double BondiTimeBet;
double BondiTimeLast;
#endif
#if defined (AGN_ACCRETION) || defined (BONDI_ACCRETION)
double LightSpeed;
#endif
#if defined(ART_VISCO_MM)|| defined(ART_VISCO_RO) || defined(ART_VISCO_CD)
double ArtBulkViscConstMin;
double ArtBulkViscConstMax;
double ArtBulkViscConstL;
#endif
#ifdef AB_TURB
double StDecay;
double StEnergy;
double StDtFreq;
double StKmin;
double StKmax;
double StSolWeight;
double StAmplFac;
int StSpectForm;
int StSeed;
#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
char TimingsFile[MAXLEN_FILENAME]; /*!< name of file with performance metrics of gravitational tree algorithm */
char RestartFile[MAXLEN_FILENAME]; /*!< basename of restart-files */
char ResubmitCommand[MAXLEN_FILENAME]; /*!< name of script-file that will be executed for automatic restart */
char OutputListFilename[MAXLEN_FILENAME]; /*!< name of file with list of desired output times */
double OutputListTimes[MAXLEN_OUTPUTLIST]; /*!< table with desired output times */
int OutputListLength; /*!< number of output times stored in the table of desired output times */
#ifdef RANDOMSEED_AS_PARAMETER
int RandomSeed; /*!< initial random seed >*/
#endif
}
All; /*!< a container variable for global variables that are equal on all processors */
/*! This structure holds all the information that is
* stored for each particle of the simulation.
*/
extern struct particle_data
{
FLOAT Pos[3]; /*!< particle position at its current time */
FLOAT Mass; /*!< particle mass */
FLOAT Vel[3]; /*!< particle velocity at its current time */
FLOAT GravAccel[3]; /*!< particle acceleration due to gravity */
#ifdef PMGRID
FLOAT GravPM[3]; /*!< particle acceleration due to long-range PM gravity force*/
#endif
#ifdef FORCETEST
FLOAT GravAccelDirect[3]; /*!< particle acceleration when computed with direct summation */
#endif
FLOAT Potential; /*!< gravitational potential */
FLOAT OldAcc; /*!< magnitude of old gravitational force. Used in relative opening criterion */
#ifndef LONGIDS
unsigned int ID; /*!< particle identifier */
#else
unsigned long long ID; /*!< particle identifier */
#endif
int Type; /*!< flags particle type. 0=gas, 1=halo, 2=disk, 3=bulge, 4=stars, 5=bndry */
int Ti_endstep; /*!< marks start of current timestep of particle on integer timeline */
int Ti_begstep; /*!< marks end of current timestep of particle on integer timeline */
#ifdef FLEXSTEPS
int FlexStepGrp; /*!< a random 'offset' on the timeline to create a smooth groouping of particles */
#endif
float GravCost; /*!< weight factor used for balancing the work-load */
#ifdef PSEUDOSYMMETRIC
float AphysOld; /*!< magnitude of acceleration in last timestep. Used to make a first order
prediction of the change of acceleration expected in the future, thereby
allowing to guess whether a decrease/increase of the timestep should occur
in the timestep that is started. */
#endif
#ifdef PARTICLE_FLAG
float Flag;
#endif
#ifdef STELLAR_PROP
unsigned int StPIdx; /*!< index to the corresponding StP particle */
#endif
#ifdef TESSEL
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 rSearch; /* radius in which particles must search for ngbs */
#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 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];
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
#if PY_INTERFACE
FLOAT Observable;
FLOAT ObsMoment0;
FLOAT ObsMoment1;
FLOAT GradObservable[3];
#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 STELLAR_PROP
/* the following struture holds data that is stored for each SPH particle in addition to the collisionless
* variables.
*/
extern struct st_particle_data
{
#ifdef CHECK_ID_CORRESPONDENCE
unsigned int ID; /*!< particle identifier (must be the same as P[].ID) only used to check ID correspondance */
#endif
FLOAT FormationTime; /*!< star formation time of particle */
FLOAT InitialMass; /*!< initial stellar mass */
#ifndef LONGIDS
unsigned int IDProj; /*!< id of projenitor particle */
#else
unsigned long long IDProj; /*!< id of projenitor particle */
#endif
FLOAT Metal[NELEMENTS];
FLOAT Density; /*!< current baryonic mass density of particle */
FLOAT Volume; /*!< current volume of particle */
FLOAT Hsml; /*!< current smoothing length */
FLOAT Left; /*!< lower bound in iterative smoothing length search */
FLOAT Right; /*!< upper bound in iterative smoothing length search */
FLOAT NumNgb; /*!< weighted number of neighbours found */
unsigned int PIdx; /*!< index to the corresponding particle */
#ifdef AVOIDNUMNGBPROBLEM
FLOAT OldNumNgb;
#endif
FLOAT DhsmlDensityFactor; /*!< correction factor needed in the equation of motion of the conservative entropy formulation of SPH */
double TotalEjectedGasMass;
double TotalEjectedEltMass[NELEMENTS];
double TotalEjectedEgySpec;
double NumberOfSNIa;
double NumberOfSNII;
#ifdef CHIMIE_KINETIC_FEEDBACK
double NgbMass; /*!< mass of neighbours */
#endif
#ifdef CHIMIE
unsigned int Flag;
#endif
}
*StP, /*!< holds ST particle data on local processor */
*DomainStBuf; /*!< buffer for ST particle data in domain decomposition */
#endif
/* Variables for Tree
*/
extern int MaxNodes; /*!< maximum allowed number of internal nodes */
extern int Numnodestree; /*!< number of (internal) nodes in each tree */
extern struct NODE
{
FLOAT len; /*!< sidelength of treenode */
FLOAT center[3]; /*!< geometrical center of node */
#ifdef ADAPTIVE_GRAVSOFT_FORGAS
FLOAT maxsoft; /*!< hold the maximum gravitational softening of particles in the
node if the ADAPTIVE_GRAVSOFT_FORGAS option is selected */
#endif
#ifdef STELLAR_FLUX
FLOAT starlum ; /*!< star luminosity of node */
#endif
union
{
int suns[8]; /*!< temporary pointers to daughter nodes */
struct
{
FLOAT s[3]; /*!< center of mass of node */
FLOAT mass; /*!< mass of node */
int bitflags; /*!< a bit-field with various information on the node */
int sibling; /*!< this gives the next node in the walk in case the current node can be used */
int nextnode; /*!< this gives the next node in case the current node needs to be opened */
int father; /*!< this gives the parent node of each node (or -1 if we have the root node) */
}
d;
}
u;
}
*Nodes_base, /*!< points to the actual memory allocted for the nodes */
*Nodes; /*!< this is a pointer used to access the nodes which is shifted such that Nodes[All.MaxPart]
gives the first allocated node */
extern int *Nextnode; /*!< gives next node in tree walk */
extern int *Father; /*!< gives parent node in tree */
extern struct extNODE /*!< this structure holds additional tree-node information which is not needed in the actual gravity computation */
{
FLOAT hmax; /*!< maximum SPH smoothing length in node. Only used for gas particles */
FLOAT vs[3]; /*!< center-of-mass velocity */
}
*Extnodes_base, /*!< points to the actual memory allocted for the extended node information */
*Extnodes; /*!< provides shifted access to extended node information, parallel to Nodes/Nodes_base */
/*! Header for the standard file format.
*/
extern struct io_header
{
int npart[6]; /*!< number of particles of each type in this file */
double mass[6]; /*!< mass of particles of each type. If 0, then the masses are explicitly
stored in the mass-block of the snapshot file, otherwise they are omitted */
double time; /*!< time of snapshot file */
double redshift; /*!< redshift of snapshot file */
int flag_sfr; /*!< flags whether the simulation was including star formation */
int flag_feedback; /*!< flags whether feedback was included (obsolete) */
unsigned int npartTotal[6]; /*!< total number of particles of each type in this snapshot. This can be
different from npart if one is dealing with a multi-file snapshot. */
int flag_cooling; /*!< flags whether cooling was included */
int num_files; /*!< number of files in multi-file snapshot */
double BoxSize; /*!< box-size of simulation in case periodic boundaries were used */
double Omega0; /*!< matter density in units of critical density */
double OmegaLambda; /*!< cosmological constant parameter */
double HubbleParam; /*!< Hubble parameter in units of 100 km/sec/Mpc */
int flag_stellarage; /*!< flags whether the file contains formation times of star particles */
int flag_metals; /*!< flags whether the file contains metallicity values for gas and star particles */
unsigned int npartTotalHighWord[6]; /*!< High word of the total number of particles of each type */
int flag_entropy_instead_u; /*!< flags that IC-file contains entropy instead of u */
int flag_chimie_extraheader; /*!< flags that IC-file contains extra-header for chimie */
#ifdef MULTIPHASE
double critical_energy_spec;
#ifdef MESOMACHINE
char fill[38];
#else
char fill[48]; /* use 42 with regor... */
#endif
#else
char fill[56]; /*!< fills to 256 Bytes */
#endif
}
header; /*!< holds header for snapshot files */
#ifdef CHIMIE_EXTRAHEADER
/*! Header for the chimie part.
*/
extern struct io_chimie_extraheader
{
int nelts; /*!< number of chemical element followed */
float SolarAbundances[NELEMENTS];
char labels[256-4-4*(NELEMENTS)];
}
chimie_extraheader;
#endif
#define IO_NBLOCKS 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 MULTIPHASE
double EnergyRadSticky;
#endif
#ifdef FEEDBACK_WIND
double EnergyFeedbackWind;
#endif
#ifdef BUBBLES
double EnergyBubbles;
#endif
#ifdef CHIMIE_THERMAL_FEEDBACK
double EnergyThermalFeedback;
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
double EnergyKineticFeedback;
#endif
double EnergyTot;
double Momentum[4];
double AngMomentum[4];
double CenterOfMass[4];
double MassComp[6];
double EnergyKinComp[6];
double EnergyPotComp[6];
double EnergyIntComp[6];
#ifdef COOLING
double EnergyRadSphComp[6];
#endif
#ifdef AGN_HEATING
double EnergyAGNHeatComp[6];
#endif
#ifdef MULTIPHASE
double EnergyRadStickyComp[6];
#endif
#ifdef FEEDBACK_WIND
double EnergyFeedbackWindComp[6];
#endif
#ifdef BUBBLES
double EnergyBubblesComp[6];
#endif
#ifdef CHIMIE_THERMAL_FEEDBACK
double EnergyThermalFeedbackComp[6];
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
double EnergyKineticFeedbackComp[6];
#endif
double EnergyTotComp[6];
double MomentumComp[6][4];
double AngMomentumComp[6][4];
double CenterOfMassComp[6][4];
}
SysState; /*<! Structure for storing some global statistics about the simulation. */
/*! This structure contains data related to the energy budget.
These values are different for each task. It need to be stored
in the restart flag.
*/
extern struct local_state_of_system
{
double EnergyTest;
double EnergyInt1;
double EnergyInt2;
double EnergyKin1;
double EnergyKin2;
#ifdef COOLING
double RadiatedEnergy;
#endif
#ifdef SFR
double StarEnergyInt;
#ifdef FEEDBACK
double StarEnergyFeedback;
#endif
#endif
#ifdef CHIMIE_THERMAL_FEEDBACK
double EnergyThermalFeedback;
#endif
#ifdef CHIMIE_KINETIC_FEEDBACK
double EnergyKineticFeedback;
#endif
#ifdef MULTIPHASE
double EnergyRadSticky;
#endif
#ifdef FEEDBACK_WIND
double EnergyFeedbackWind;
#endif
}
LocalSysState; /*<! Structure for storing some local statistics about the simulation. */
/* Various structures for communication
*/
extern struct gravdata_in
{
union
{
FLOAT Pos[3];
FLOAT Acc[3];
FLOAT Potential;
}
u;
#if defined(UNEQUALSOFTENINGS) || defined(STELLAR_FLUX)
int Type;
#ifdef ADAPTIVE_GRAVSOFT_FORGAS
FLOAT Soft;
#endif
#endif
#ifdef STELLAR_FLUX
FLOAT EnergyFlux;
#endif
union
{
FLOAT OldAcc;
int Ninteractions;
}
w;
}
*GravDataIn, /*!< holds particle data to be exported to other processors */
*GravDataGet, /*!< holds particle data imported from other processors */
*GravDataResult, /*!< holds the partial results computed for imported particles. Note: We use GravDataResult = GravDataGet, such that the result replaces the imported data */
*GravDataOut; /*!< holds partial results received from other processors. This will overwrite the GravDataIn array */
extern struct gravdata_index
{
int Task;
int Index;
int SortIndex;
}
*GravDataIndexTable; /*!< the particles to be exported are grouped by task-number. This table allows the results to be disentangled again and to be assigned to the correct particle */
extern struct densdata_in
{
FLOAT Pos[3];
FLOAT Vel[3];
FLOAT Hsml;
#ifdef MULTIPHASE
int Phase;
#endif
int Index;
int Task;
#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
}
*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
}
*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
}
*HydroDataResult, /*!< stores the locally computed SPH hydro results for imported particles */
*HydroDataPartialResult; /*!< imported partial SPH hydro-force results from other processors */
#ifdef MULTIPHASE
extern struct stickydata_in
{
FLOAT Pos[3];
FLOAT Vel[3];
FLOAT Mass;
FLOAT Hsml;
int ID;
int StickyMaxID;
int StickyNgb;
float StickyMaxFs;
int Task;
int Index;
}
*StickyDataIn, /*!< holds particle data for sticky computation to be exported to other processors */
*StickyDataGet; /*!< holds imported particle data for sticky computation */
extern struct stickydata_out
{
int StickyMaxID;
int StickyNgb;
float StickyMaxFs;
FLOAT StickyNewVel[3];
}
*StickyDataResult, /*!< stores the locally computed sticky results for imported particles */
*StickyDataPartialResult; /*!< imported partial sticky results from other processors */
extern struct Sticky_index
{
int Index;
int CellIndex;
int Flag;
}
*StickyIndex;
#endif
#ifdef CHIMIE
extern struct chimiedata_in
{
FLOAT Pos[3];
FLOAT Vel[3];
#ifndef LONGIDS
unsigned int ID; /*!< particle identifier */
#else
unsigned long long ID; /*!< particle identifier */
#endif
FLOAT Hsml;
#ifdef FEEDBACK
FLOAT EnergySN;
#endif
#ifdef MULTIPHASE
int Phase;
FLOAT Entropy;
int StickyFlag;
#endif
FLOAT Density;
FLOAT Volume;
FLOAT Pressure;
FLOAT F1;
FLOAT DhsmlDensityFactor;
int Timestep;
int Task;
int Index;
#ifdef WITH_ID_IN_HYDRA
int ID;
#endif
double TotalEjectedGasMass;
double TotalEjectedEltMass[NELEMENTS];
double TotalEjectedEgySpec;
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 Volume;
FLOAT DhsmlDensity;
FLOAT Ngb;
#ifdef CHIMIE_KINETIC_FEEDBACK
FLOAT NgbMass;
#endif
}
*StarsDensDataResult, /*!< stores the locally computed SPH density results for imported particles */
*StarsDensDataPartialResult; /*!< imported partial SPH density results from other processors */
#endif /*CHIMIE*/
#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 particle_data *gP;
+//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 PY_INTERFACE
extern struct denssphdata_in
{
FLOAT Pos[3];
FLOAT Vel[3];
FLOAT Hsml;
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 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/ghost.c b/src/ghost.c
index fdebae3..2fd10a0 100644
--- a/src/ghost.c
+++ b/src/ghost.c
@@ -1,545 +1,549 @@
#ifdef TESSEL
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <mpi.h>
#include "allvars.h"
#include "proto.h"
/*! \file ghost.c
* \brief
*
*/
#ifdef PERIODIC
static double boxSize, boxHalf;
#ifdef LONG_X
static double boxSize_X, boxHalf_X;
#else
#define boxSize_X boxSize
#define boxHalf_X boxHalf
#endif
#ifdef LONG_Y
static double boxSize_Y, boxHalf_Y;
#else
#define boxSize_Y boxSize
#define boxHalf_Y boxHalf
#endif
#ifdef LONG_Z
static double boxSize_Z, boxHalf_Z;
#else
#define boxSize_Z boxSize
#define boxHalf_Z boxHalf
#endif
#endif
/*! This function computes the local density for each active SPH particle,
* the number of neighbours in the current smoothing radius, and the
* divergence and curl of the velocity field. The pressure is updated as
* well. If a particle with its smoothing region is fully inside the
* local domain, it is not exported to the other processors. The function
* also detects particles that have a number of neighbours outside the
* allowed tolerance range. For these particles, the smoothing length is
* adjusted accordingly, and the density computation is executed again.
* Note that the smoothing length is not allowed to fall below the lower
* bound set by MinGasHsml.
*/
void ghost(int mode)
{
long long ntot, ntotleft;
int *noffset, *nbuffer, *nsend, *nsend_local, *numlist, *ndonelist;
int i, j, n, ndone, npleft, maxfill, source, iter = 0;
int level, ngrp, sendTask, recvTask, place, nexport;
double dt_entr, tstart, tend, tstart_ngb = 0, tend_ngb = 0;
double sumt, sumcomm, timengb, sumtimengb;
double timecomp = 0, timeimbalance = 0, timecommsumm = 0, sumimbalance;
MPI_Status status;
#ifdef DETAILED_CPU_OUTPUT_IN_DENSITY
double *timengblist;
double *timecomplist;
double *timecommsummlist;
double *timeimbalancelist;
#endif
#ifdef DETAILED_CPU
double t0=0,t1=0;
#endif
#ifdef PERIODIC
boxSize = All.BoxSize;
boxHalf = 0.5 * All.BoxSize;
#ifdef LONG_X
boxHalf_X = boxHalf * LONG_X;
boxSize_X = boxSize * LONG_X;
#endif
#ifdef LONG_Y
boxHalf_Y = boxHalf * LONG_Y;
boxSize_Y = boxSize * LONG_Y;
#endif
#ifdef LONG_Z
boxHalf_Z = boxHalf * LONG_Z;
boxSize_Z = boxSize * LONG_Z;
#endif
#endif
#ifdef DETAILED_CPU
if (mode==1)
t0 = second();
#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);
for(n = 0, NumPTUpdate = 0; n < N_gas; n++)
{
P[n].IsDone = 0;
P[n].IsAdded = 0;
NumPTUpdate++;
}
numlist = malloc(NTask * sizeof(int) * NTask);
MPI_Allgather(&NumPTUpdate, 1, MPI_INT, numlist, 1, MPI_INT, MPI_COMM_WORLD);
for(i = 0, ntot = 0; i < NTask; i++)
ntot += numlist[i];
free(numlist);
/* we will repeat the whole thing for those particles where we didn't
* find enough neighbours
*/
do
{
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 */
tstart = second();
for(nexport = 0, ndone = 0; i < N_gas && nexport < All.BunchSizeGhost - NTask; i++)
if(P[i].IsDone == 0)
{
ndone++;
for(j = 0; j < NTask; j++)
Exportflag[j] = 0;
ghost_evaluate(i, 0);
for(j = 0; j < NTask; j++)
{
if(Exportflag[j])
{
GhostDataIn[nexport].Pos[0] = P[i].Pos[0];
GhostDataIn[nexport].Pos[1] = P[i].Pos[1];
GhostDataIn[nexport].Pos[2] = P[i].Pos[2];
GhostDataIn[nexport].Index = i;
GhostDataIn[nexport].rSearch = P[i].rSearch;
nexport++;
nsend_local[j]++;
}
}
}
tend = second();
timecomp += timediff(tstart, tend);
qsort(GhostDataIn, nexport, sizeof(struct ghostdata_in), ghost_compare_key);
for(j = 1, noffset[0] = 0; j < NTask; j++)
noffset[j] = noffset[j - 1] + nsend_local[j - 1];
tstart = second();
MPI_Allgather(nsend_local, NTask, MPI_INT, nsend, NTask, MPI_INT, MPI_COMM_WORLD);
tend = second();
timeimbalance += timediff(tstart, tend);
/* now do the particles that need to be exported */
for(level = 1; level < (1 << PTask); level++)
{
tstart = second();
for(j = 0; j < NTask; j++)
nbuffer[j] = 0;
for(ngrp = level; ngrp < (1 << PTask); ngrp++)
{
maxfill = 0;
for(j = 0; j < NTask; j++)
{
if((j ^ ngrp) < NTask)
if(maxfill < nbuffer[j] + nsend[(j ^ ngrp) * NTask + j])
maxfill = nbuffer[j] + nsend[(j ^ ngrp) * NTask + j];
}
if(maxfill >= All.BunchSizeGhost)
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(&GhostDataIn[noffset[recvTask]],
nsend_local[recvTask] * sizeof(struct ghostdata_in), MPI_BYTE,
recvTask, TAG_DENS_A,
&GhostDataGet[nbuffer[ThisTask]],
nsend[recvTask * NTask + ThisTask] * sizeof(struct ghostdata_in),
MPI_BYTE, recvTask, TAG_DENS_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);
tstart = second();
for(j = 0; j < nbuffer[ThisTask]; j++)
ghost_evaluate(j, 1);
tend = second();
timecomp += timediff(tstart, tend);
/* do a block to explicitly measure imbalance */
tstart = second();
MPI_Barrier(MPI_COMM_WORLD);
tend = second();
timeimbalance += timediff(tstart, tend);
/* get the result */
tstart = second();
for(j = 0; j < NTask; j++)
nbuffer[j] = 0;
for(ngrp = level; ngrp < (1 << PTask); ngrp++)
{
maxfill = 0;
for(j = 0; j < NTask; j++)
{
if((j ^ ngrp) < NTask)
if(maxfill < nbuffer[j] + nsend[(j ^ ngrp) * NTask + j])
maxfill = nbuffer[j] + nsend[(j ^ ngrp) * NTask + j];
}
if(maxfill >= All.BunchSizeGhost)
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(&GhostDataResult[nbuffer[ThisTask]],
nsend[recvTask * NTask + ThisTask] * sizeof(struct ghostdata_out),
MPI_BYTE, recvTask, TAG_DENS_B,
&GhostDataPartialResult[noffset[recvTask]],
nsend_local[recvTask] * sizeof(struct ghostdata_out),
MPI_BYTE, recvTask, TAG_DENS_B, MPI_COMM_WORLD, &status);
/* add the result to the particles */
for(j = 0; j < nsend_local[recvTask]; j++)
{
source = j + noffset[recvTask];
place = GhostDataIn[source].Index;
// this is needed if we want to get some values
//SphP[place].Value = GhostDataPartialResult[source].Value;
}
}
}
for(j = 0; j < NTask; j++)
if((j ^ ngrp) < NTask)
nbuffer[j] += nsend[(j ^ ngrp) * NTask + j];
}
tend = second();
timecommsumm += timediff(tstart, tend);
level = ngrp - 1;
}
MPI_Allgather(&ndone, 1, MPI_INT, ndonelist, 1, MPI_INT, MPI_COMM_WORLD);
for(j = 0; j < NTask; j++)
ntotleft -= ndonelist[j];
}
/* do final operations on results */
tstart = second();
/* add all ghost particles to the tesselation */
-
-
+ AddGhostPoints();
for(i = 0, npleft = 0; i < N_gas; i++)
{
{
- AddGhostPoints();
-
/* now check whether we had enough neighbours */
if (0)
{
/* need to redo this particle */
npleft++;
}
else
P[i].IsDone = 1; /* Mark as inactive */
}
}
tend = second();
timecomp += timediff(tstart, tend);
numlist = malloc(NTask * sizeof(int) * NTask);
MPI_Allgather(&npleft, 1, MPI_INT, numlist, 1, MPI_INT, MPI_COMM_WORLD);
for(i = 0, ntot = 0; i < NTask; i++)
ntot += numlist[i];
free(numlist);
if(ntot > 0)
{
if(iter == 0)
tstart_ngb = second();
iter++;
if(iter > 0 && ThisTask == 0)
{
printf("ngb tessel iteration %d: need to repeat for %d%09d particles.\n", iter,
(int) (ntot / 1000000000), (int) (ntot % 1000000000));
fflush(stdout);
}
if(iter > MAXITER)
{
printf("failed to converge in neighbour iteration in density()\n");
fflush(stdout);
endrun(1155);
}
}
else
tend_ngb = second();
}
while(ntot > 0);
/* mark as active again */
//for(i = 0; i < NumPart; i++)
// P[i].IsDone = 0;
free(ndonelist);
free(nsend);
free(nsend_local);
free(nbuffer);
free(noffset);
/* collect some timing information */
if(iter > 0)
timengb = timediff(tstart_ngb, tend_ngb);
else
timengb = 0;
MPI_Reduce(&timengb, &sumtimengb, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(&timecomp, &sumt, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(&timecommsumm, &sumcomm, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(&timeimbalance, &sumimbalance, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
}
#define NGB_PERIODIC_SIGN_X(x) (xtmp=(x),(xtmp>boxHalf_X)?(-1.0):((xtmp<-boxHalf_X)?(1.0):0))
#define NGB_PERIODIC_SIGN_Y(x) (xtmp=(x),(xtmp>boxHalf_Y)?(-1.0):((xtmp<-boxHalf_Y)?(1.0):0))
#define NGB_PERIODIC_SIGN_Z(x) (xtmp=(x),(xtmp>boxHalf_Z)?(-1.0):((xtmp<-boxHalf_Z)?(1.0):0))
#define ADD_TO_QUADRANT(i,qflag)(1<<i | qflag)
#define QUADRANT_IS_EMPTY(i,qflag)(((1<<i & qflag)==0)?1:0)
#define QUADRANT(x,y,z)( x + 3*y + 9*z )
/*! This function represents the core of the SPH density computation. The
* target particle may either be local, or reside in the communication
* buffer.
*/
void ghost_evaluate(int target, int mode)
{
int j, n, startnode, numngb, numngb_inbox;
double h, h2, hinv, hinv3, hinv4;
double dx, dy, dz, r, r2;
FLOAT *pos;
FLOAT posj[3];
int phase=0;
#ifdef PERIODIC
double xtmp;
double sgnx,sgny,sgnz;
int quadrant;
#endif
if(mode == 0)
{
pos = P[target].Pos;
h = P[target].rSearch;
}
else
{
pos = GhostDataGet[target].Pos;
h = GhostDataGet[target].rSearch;
}
h2 = h * h;
hinv = 1.0 / h;
#ifndef TWODIMS
hinv3 = hinv * hinv * hinv;
#else
hinv3 = hinv * hinv / boxSize_Z;
#endif
hinv4 = hinv3 * hinv;
startnode = All.MaxPart;
numngb = 0;
do
{
numngb_inbox = ngb_treefind_variable_for_tessel(&pos[0], h, phase, &startnode);
for(n = 0; n < numngb_inbox; n++)
{
j = Ngblist[n];
#ifdef PERIODIC
sgnx = NGB_PERIODIC_SIGN_X(P[j].Pos[0]-pos[0]);
sgny = NGB_PERIODIC_SIGN_Y(P[j].Pos[1]-pos[1]);
sgnz = NGB_PERIODIC_SIGN_Z(P[j].Pos[2]-pos[2]);
quadrant = QUADRANT((int)(sgnx+1),(int)(sgny+1),(int)(sgnz+1));
#endif
/* check if a particle is already in a quadrant */
//printf("%g %g %g\n",sgnx+1,sgny+1,sgnz+1);
//printf("quadrant=%d %d\n",quadrant,QUADRANT_IS_EMPTY(quadrant,P[j].IsAdded));
if( QUADRANT_IS_EMPTY(quadrant,P[j].IsAdded) )
{
/* add offset */
posj[0] = P[j].Pos[0] + boxSize_X*sgnx;
posj[1] = P[j].Pos[1] + boxSize_Y*sgny;
posj[2] = P[j].Pos[2] + boxSize_Z*sgnz;
dx = pos[0] - posj[0];
dy = pos[1] - posj[1];
dz = pos[2] - posj[2];
r2 = dx * dx + dy * dy + dz * dz;
if(r2 < h2)
{
/* we can add a point j to the tesselation */
- if (NumPart+NumgPart>=All.MaxPart)
+
+ if (NumgPart+NumgPart>=All.MaxPart)
{
- printf("NumPart+NumgPart %d >= MaxPart %d !!!\n",NumPart+NumgPart,All.MaxPart);
+ printf("NumgPart+NumgPart %d >= MaxPart %d !!!\n",NumgPart+NumgPart,All.MaxPart);
endrun(-123);
}
else
{
//printf("this point is added %g %g %g (%g %g %g)\n",posj[0],posj[1],posj[2],P[j].Pos[0],P[j].Pos[1],P[j].Pos[2]);
-
P[j].IsAdded = ADD_TO_QUADRANT(quadrant,P[j].IsAdded);
P[NumPart+NumgPart].Pos[0] = posj[0];
P[NumPart+NumgPart].Pos[1] = posj[1];
P[NumPart+NumgPart].Pos[2] = posj[2];
P[NumPart+NumgPart].Mass = P[j].Mass;
+
+ //printf("this point is added %d %g %g %g (%g %g %g)\n",NumPart+NumgPart,P[NumPart+NumgPart].Pos[0],P[NumPart+NumgPart].Pos[1],P[NumPart+NumgPart].Pos[2],posj[0],posj[1],posj[2]);
+
NumgPart++;
+
}
+
+
+
}
}
}
}
while(startnode >= 0);
if(mode == 0)
{
//SphP[target].Value = value;
}
else
{
//GhostDataResult[target].Value = value;
}
}
/*! This routine is a comparison kernel used in a sort routine to group
* particles that are exported to the same processor.
*/
int ghost_compare_key(const void *a, const void *b)
{
if(((struct ghostdata_in *) a)->Task < (((struct ghostdata_in *) b)->Task))
return -1;
if(((struct ghostdata_in *) a)->Task > (((struct ghostdata_in *) b)->Task))
return +1;
return 0;
}
-#endif
\ No newline at end of file
+#endif
diff --git a/src/proto.h b/src/proto.h
index dd5647e..1a129d7 100644
--- a/src/proto.h
+++ b/src/proto.h
@@ -1,511 +1,513 @@
/*! \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
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
int get_timestep(int p, double *a, int flag);
int get_values_per_blockelement(enum iofields blocknr);
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);
#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,double a3inv,double hubble_a);
void cooling();
double lambda(FLOAT density,FLOAT egyspec, 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 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_SolarAbundance(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
#endif
#ifdef OUTERPOTENTIAL
void init_outer_potential(void);
void outer_forces(void);
void outer_potential(void);
#ifdef NFW
void init_outer_potential_nfw(void);
void outer_forces_nfw(void);
void outer_potential_nfw(void);
#endif
#ifdef PLUMMER
void init_outer_potential_plummer(void);
void outer_forces_plummer(void);
void outer_potential_plummer(void);
#endif
#ifdef PISOTHERM
void init_outer_potential_pisotherm(void);
void outer_forces_pisotherm(void);
void outer_potential_pisotherm(void);
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);
#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
#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 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();
int ghost_compare_key(const void *a, const void *b);
void AddGhostPoints();
#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_GetvPointsForOnePoint(self, args);
PyObject *gadget_GetAllGhostPositions(PyObject* self);
+PyObject *gadget_GetAllGhostvDensities(PyObject* self);
+PyObject *gadget_GetAllGhostvVolumes(PyObject* self);
#endif
#endif
#ifdef PY_INTERFACE
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);
#endif
diff --git a/src/python_interface.c b/src/python_interface.c
index 5ed9c8e..e689c93 100644
--- a/src/python_interface.c
+++ b/src/python_interface.c
@@ -1,3218 +1,3224 @@
#ifdef PY_INTERFACE
#include <Python.h>
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <numpy/arrayobject.h>
#include <mpi.h>
#include "allvars.h"
#include "proto.h"
#define TO_INT(a) ( (PyArrayObject*) PyArray_CastToType(a, PyArray_DescrFromType(NPY_INT) ,0) )
#define TO_DOUBLE(a) ( (PyArrayObject*) PyArray_CastToType(a, PyArray_DescrFromType(NPY_DOUBLE) ,0) )
#define TO_FLOAT(a) ( (PyArrayObject*) PyArray_CastToType(a, PyArray_DescrFromType(NPY_FLOAT) ,0) )
static int Init()
{
/* main.c */
RestartFlag = 0;
All.CPU_TreeConstruction = All.CPU_TreeWalk = All.CPU_Gravity = All.CPU_Potential = All.CPU_Domain =
All.CPU_Snapshot = All.CPU_Total = All.CPU_CommSum = All.CPU_Imbalance = All.CPU_Hydro =
All.CPU_HydCompWalk = All.CPU_HydCommSumm = All.CPU_HydImbalance =
All.CPU_EnsureNgb = All.CPU_Predict = All.CPU_TimeLine = All.CPU_PM = All.CPU_Peano = 0;
CPUThisRun = 0;
/* from init.c, after read ic */
int i, j;
double a3;
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;
}
set_softenings();
All.NumCurrentTiStep = 0; /* setup some counters */
All.SnapshotFileCount = 0;
if(RestartFlag == 2)
All.SnapshotFileCount = atoi(All.InitCondFile + strlen(All.InitCondFile) - 3) + 1;
All.TotNumOfForces = 0;
All.NumForcesSinceLastDomainDecomp = 0;
if(All.ComovingIntegrationOn)
if(All.PeriodicBoundariesOn == 1)
check_omega();
All.TimeLastStatistics = All.TimeBegin - All.TimeBetStatistics;
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 PMGRID
All.PM_Ti_endstep = All.PM_Ti_begstep = 0;
#endif
#ifdef FLEXSTEPS
All.PresentMinStep = TIMEBASE;
for(i = 0; i < NumPart; i++) /* start-up initialization */
{
P[i].FlexStepGrp = (int) (TIMEBASE * get_random_number(P[i].ID));
}
#endif
for(i = 0; i < N_gas; i++) /* initialize sph_properties */
{
for(j = 0; j < 3; j++)
{
SphP[i].VelPred[j] = P[i].Vel[j];
SphP[i].HydroAccel[j] = 0;
}
SphP[i].DtEntropy = 0;
if(RestartFlag == 0)
{
SphP[i].Hsml = 0;
SphP[i].Density = -1;
}
}
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 ISOTHERM_EQS
if(header.flag_entropy_instead_u == 0)
for(i = 0; i < N_gas; i++)
SphP[i].Entropy = GAMMA_MINUS1 * SphP[i].Entropy / pow(SphP[i].Density / a3, GAMMA_MINUS1);
#endif
return 1;
}
static void Begrun1()
{
struct global_data_all_processes all;
if(ThisTask == 0)
{
printf("\nThis is pyGadget, 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);
gsl_rng_set(random_generator, 42); /* start-up seed */
#ifdef PMGRID
long_range_init();
#endif
All.TimeLastRestartFile = CPUThisRun;
if(RestartFlag == 0 || RestartFlag == 2)
{
set_random_numbers();
}
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.
*/
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;
All.TimeLimitCPU = all.TimeLimitCPU;
All.ResubmitOn = all.ResubmitOn;
All.TimeBetSnapshot = all.TimeBetSnapshot;
All.TimeBetStatistics = all.TimeBetStatistics;
All.CpuTimeBetRestartFile = all.CpuTimeBetRestartFile;
All.ErrTolIntAccuracy = all.ErrTolIntAccuracy;
All.MaxRMSDisplacementFac = all.MaxRMSDisplacementFac;
All.ErrTolForceAcc = all.ErrTolForceAcc;
All.TypeOfTimestepCriterion = all.TypeOfTimestepCriterion;
All.TypeOfOpeningCriterion = all.TypeOfOpeningCriterion;
All.NumFilesWrittenInParallel = all.NumFilesWrittenInParallel;
All.TreeDomainUpdateFrequency = all.TreeDomainUpdateFrequency;
All.SnapFormat = all.SnapFormat;
All.NumFilesPerSnapshot = all.NumFilesPerSnapshot;
All.MaxNumNgbDeviation = all.MaxNumNgbDeviation;
All.ArtBulkViscConst = all.ArtBulkViscConst;
All.OutputListOn = all.OutputListOn;
All.CourantFac = all.CourantFac;
All.OutputListLength = all.OutputListLength;
memcpy(All.OutputListTimes, all.OutputListTimes, sizeof(double) * All.OutputListLength);
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);
strcpy(All.InfoFile, all.InfoFile);
strcpy(All.CpuFile, all.CpuFile);
strcpy(All.TimingsFile, all.TimingsFile);
strcpy(All.SnapshotFileBase, all.SnapshotFileBase);
if(All.TimeMax != all.TimeMax)
readjust_timebase(All.TimeMax, all.TimeMax);
}
}
static void Begrun2()
{
if(RestartFlag == 0 || RestartFlag == 2)
Init(); /* ... read in initial model */
#ifdef PMGRID
long_range_init_regionsize();
#endif
if(All.ComovingIntegrationOn)
init_drift_table();
//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;
}
/************************************************************/
/* PYTHON INTERFACE */
/************************************************************/
static PyObject *gadget_Info(PyObject *self, PyObject *args, PyObject *kwds)
{
printf("I am proc %d among %d procs.\n",ThisTask,NTask);
return Py_BuildValue("i",1);
}
static PyObject *gadget_InitMPI(PyObject *self, PyObject *args, PyObject *kwds)
{
//MPI_Init(0, 0); /* this is done in mpi4py */
MPI_Comm_rank(MPI_COMM_WORLD, &ThisTask);
MPI_Comm_size(MPI_COMM_WORLD, &NTask);
for(PTask = 0; NTask > (1 << PTask); PTask++);
return Py_BuildValue("i",1);
}
static PyObject * gadget_InitDefaultParameters(PyObject* self)
{
/* list of Gadget parameters */
/*
All.InitCondFile ="ICs/cluster_littleendian.dat";
All.OutputDir ="cluster/";
All.EnergyFile ="energy.txt";
All.InfoFile ="info.txt";
All.TimingsFile ="timings.txt";
All.CpuFile ="cpu.txt";
All.RestartFile ="restart";
All.SnapshotFileBase ="snapshot";
All.OutputListFilename ="parameterfiles/outputs_lcdm_gas.txt";
*/
/* CPU time -limit */
All.TimeLimitCPU = 36000; /* = 10 hours */
All.ResubmitOn = 0;
//All.ResubmitCommand = "my-scriptfile";
All.ICFormat = 1;
All.SnapFormat = 1;
All.ComovingIntegrationOn = 0;
All.TypeOfTimestepCriterion = 0;
All.OutputListOn = 0;
All.PeriodicBoundariesOn = 0;
/* Caracteristics of run */
All.TimeBegin = 0.0; /*% Begin of the simulation (z=23)*/
All.TimeMax = 1.0;
All.Omega0 = 0;
All.OmegaLambda = 0;
All.OmegaBaryon = 0;
All.HubbleParam = 0;
All.BoxSize = 0;
/* Output frequency */
All.TimeBetSnapshot = 0.1;
All.TimeOfFirstSnapshot = 0.0; /*% 5 constant steps in log(a) */
All.CpuTimeBetRestartFile = 36000.0; /* here in seconds */
All.TimeBetStatistics = 0.05;
All.NumFilesPerSnapshot = 1;
All.NumFilesWrittenInParallel = 1;
/* Accuracy of time integration */
All.ErrTolIntAccuracy = 0.025;
All.MaxRMSDisplacementFac = 0.2;
All.CourantFac = 0.15;
All.MaxSizeTimestep = 0.03;
All.MinSizeTimestep = 0.0;
/* Tree algorithm, force accuracy, domain update frequency */
All.ErrTolTheta = 0.7;
All.TypeOfOpeningCriterion = 0;
All.ErrTolForceAcc = 0.005;
All.TreeDomainUpdateFrequency = 0.1;
/* Further parameters of SPH */
All.DesNumNgb = 50;
All.MaxNumNgbDeviation = 2;
All.ArtBulkViscConst = 0.8;
All.InitGasTemp = 0;
All.MinGasTemp = 0;
/* Memory allocation */
All.PartAllocFactor = 2.0;
All.TreeAllocFactor = 2.0;
All.BufferSize = 30;
/* System of units */
All.UnitLength_in_cm = 3.085678e21; /* 1.0 kpc */
All.UnitMass_in_g = 1.989e43; /* 1.0e10 solar masses */
All.UnitVelocity_in_cm_per_s = 1e5; /* 1 km/sec */
All.GravityConstantInternal = 0;
/* Softening lengths */
All.MinGasHsmlFractional = 0.25;
All.SofteningGas = 0.5;
All.SofteningHalo = 0.5;
All.SofteningDisk = 0.5;
All.SofteningBulge = 0.5;
All.SofteningStars = 0.5;
All.SofteningBndry = 0.5;
All.SofteningGasMaxPhys = 0.5;
All.SofteningHaloMaxPhys = 0.5;
All.SofteningDiskMaxPhys = 0.5;
All.SofteningBulgeMaxPhys = 0.5;
All.SofteningStarsMaxPhys = 0.5;
All.SofteningBndryMaxPhys = 0.5;
return Py_BuildValue("i",1);
}
static PyObject * gadget_GetParameters()
{
PyObject *dict;
PyObject *key;
PyObject *value;
dict = PyDict_New();
/* CPU time -limit */
key = PyString_FromString("TimeLimitCPU");
value = PyFloat_FromDouble(All.TimeLimitCPU);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("ResubmitOn");
value = PyFloat_FromDouble(All.ResubmitOn);
PyDict_SetItem(dict,key,value);
//All.ResubmitCommand
key = PyString_FromString("ICFormat");
value = PyInt_FromLong(All.ICFormat);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("SnapFormat");
value = PyInt_FromLong(All.SnapFormat);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("ComovingIntegrationOn");
value = PyInt_FromLong(All.ComovingIntegrationOn);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("TypeOfTimestepCriterion");
value = PyInt_FromLong(All.TypeOfTimestepCriterion);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("OutputListOn");
value = PyInt_FromLong(All.OutputListOn);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("PeriodicBoundariesOn");
value = PyInt_FromLong(All.PeriodicBoundariesOn);
PyDict_SetItem(dict,key,value);
/* Caracteristics of run */
key = PyString_FromString("TimeBegin");
value = PyFloat_FromDouble(All.TimeBegin);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("TimeMax");
value = PyFloat_FromDouble(All.TimeMax);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("Omega0");
value = PyFloat_FromDouble(All.Omega0);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("OmegaLambda");
value = PyFloat_FromDouble(All.OmegaLambda);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("OmegaBaryon");
value = PyFloat_FromDouble(All.OmegaBaryon);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("HubbleParam");
value = PyFloat_FromDouble(All.HubbleParam);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("BoxSize");
value = PyFloat_FromDouble(All.BoxSize);
PyDict_SetItem(dict,key,value);
/* Output frequency */
key = PyString_FromString("TimeBetSnapshot");
value = PyFloat_FromDouble(All.TimeBetSnapshot);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("TimeOfFirstSnapshot");
value = PyFloat_FromDouble(All.TimeOfFirstSnapshot);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("CpuTimeBetRestartFile");
value = PyFloat_FromDouble(All.CpuTimeBetRestartFile);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("TimeBetStatistics");
value = PyFloat_FromDouble(All.TimeBetStatistics);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("NumFilesPerSnapshot");
value = PyInt_FromLong(All.NumFilesPerSnapshot);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("NumFilesWrittenInParallel");
value = PyInt_FromLong(All.NumFilesWrittenInParallel);
PyDict_SetItem(dict,key,value);
/* Accuracy of time integration */
key = PyString_FromString("ErrTolIntAccuracy");
value = PyFloat_FromDouble(All.ErrTolIntAccuracy);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("MaxRMSDisplacementFac");
value = PyFloat_FromDouble(All.MaxRMSDisplacementFac);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("CourantFac");
value = PyFloat_FromDouble(All.CourantFac);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("MaxSizeTimestep");
value = PyFloat_FromDouble(All.MaxSizeTimestep);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("MinSizeTimestep");
value = PyFloat_FromDouble(All.MinSizeTimestep);
PyDict_SetItem(dict,key,value);
/* Tree algorithm, force accuracy, domain update frequency */
key = PyString_FromString("ErrTolTheta");
value = PyFloat_FromDouble(All.ErrTolTheta);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("TypeOfOpeningCriterion");
value = PyInt_FromLong(All.TypeOfOpeningCriterion);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("ErrTolForceAcc");
value = PyFloat_FromDouble(All.ErrTolForceAcc);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("TreeDomainUpdateFrequency");
value = PyFloat_FromDouble(All.TreeDomainUpdateFrequency);
PyDict_SetItem(dict,key,value);
/* Further parameters of SPH */
key = PyString_FromString("DesNumNgb");
value = PyInt_FromLong(All.DesNumNgb);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("MaxNumNgbDeviation");
value = PyInt_FromLong(All.MaxNumNgbDeviation);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("ArtBulkViscConst");
value = PyInt_FromLong(All.ArtBulkViscConst);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("InitGasTemp");
value = PyInt_FromLong(All.InitGasTemp);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("MinGasTemp");
value = PyInt_FromLong(All.MinGasTemp);
PyDict_SetItem(dict,key,value);
/* Memory allocation */
key = PyString_FromString("PartAllocFactor");
value = PyFloat_FromDouble(All.PartAllocFactor);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("TreeAllocFactor");
value = PyFloat_FromDouble(All.TreeAllocFactor);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("BufferSize");
value = PyInt_FromLong(All.BufferSize);
PyDict_SetItem(dict,key,value);
/* System of units */
key = PyString_FromString("UnitLength_in_cm");
value = PyFloat_FromDouble(All.UnitLength_in_cm);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("UnitMass_in_g");
value = PyFloat_FromDouble(All.UnitMass_in_g);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("UnitVelocity_in_cm_per_s");
value = PyFloat_FromDouble(All.UnitVelocity_in_cm_per_s);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("GravityConstantInternal");
value = PyFloat_FromDouble(All.GravityConstantInternal);
PyDict_SetItem(dict,key,value);
/* Softening lengths */
key = PyString_FromString("MinGasHsmlFractional");
value = PyFloat_FromDouble(All.MinGasHsmlFractional);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("SofteningGas");
value = PyFloat_FromDouble(All.SofteningGas);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("SofteningHalo");
value = PyFloat_FromDouble(All.SofteningHalo);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("SofteningDisk");
value = PyFloat_FromDouble(All.SofteningDisk);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("SofteningBulge");
value = PyFloat_FromDouble(All.SofteningBulge);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("SofteningStars");
value = PyFloat_FromDouble(All.SofteningStars);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("SofteningBndry");
value = PyFloat_FromDouble(All.SofteningBndry);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("SofteningGasMaxPhys");
value = PyFloat_FromDouble(All.SofteningGasMaxPhys);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("SofteningHaloMaxPhys");
value = PyFloat_FromDouble(All.SofteningHaloMaxPhys);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("SofteningDiskMaxPhys");
value = PyFloat_FromDouble(All.SofteningDiskMaxPhys);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("SofteningBulgeMaxPhys");
value = PyFloat_FromDouble(All.SofteningBulgeMaxPhys);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("SofteningStarsMaxPhys");
value = PyFloat_FromDouble(All.SofteningStarsMaxPhys);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("SofteningBndryMaxPhys");
value = PyFloat_FromDouble(All.SofteningBndryMaxPhys);
PyDict_SetItem(dict,key,value);
/*
key = PyString_FromString("OutputInfo");
value = PyFloat_FromDouble(All.OutputInfo);
PyDict_SetItem(dict,key,value);
key = PyString_FromString("PeanoHilbertOrder");
value = PyFloat_FromDouble(All.PeanoHilbertOrder);
PyDict_SetItem(dict,key,value);
*/
return Py_BuildValue("O",dict);
}
static PyObject * gadget_SetParameters(PyObject *self, PyObject *args)
{
PyObject *dict;
PyObject *key;
PyObject *value;
int ivalue;
float fvalue;
double dvalue;
/* here, we can have either arguments or dict directly */
if(PyDict_Check(args))
{
dict = args;
}
else
{
if (! PyArg_ParseTuple(args, "O",&dict))
return NULL;
}
/* check that it is a PyDictObject */
if(!PyDict_Check(dict))
{
PyErr_SetString(PyExc_AttributeError, "argument is not a dictionary.");
return NULL;
}
Py_ssize_t pos=0;
while(PyDict_Next(dict,&pos,&key,&value))
{
if(PyString_Check(key))
{
/* CPU time -limit */
if(strcmp(PyString_AsString(key), "TimeLimitCPU")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.TimeLimitCPU = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "ResubmitOn")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.ResubmitOn = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "ICFormat")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.ICFormat = PyInt_AsLong(value);
}
if(strcmp(PyString_AsString(key), "SnapFormat")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.SnapFormat = PyInt_AsLong(value);
}
if(strcmp(PyString_AsString(key), "ComovingIntegrationOn")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.ComovingIntegrationOn = PyInt_AsLong(value);
}
if(strcmp(PyString_AsString(key), "TypeOfTimestepCriterion")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.TypeOfTimestepCriterion = PyInt_AsLong(value);
}
if(strcmp(PyString_AsString(key), "OutputListOn")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.OutputListOn = PyInt_AsLong(value);
}
if(strcmp(PyString_AsString(key), "PeriodicBoundariesOn")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.PeriodicBoundariesOn = PyInt_AsLong(value);
}
/* Caracteristics of run */
if(strcmp(PyString_AsString(key), "TimeBegin")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.TimeBegin = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "TimeMax")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.TimeMax = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "Omega0")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.Omega0 = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "OmegaLambda")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.OmegaLambda = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "OmegaBaryon")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.OmegaBaryon = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "HubbleParam")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.HubbleParam = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "BoxSize")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.BoxSize = PyFloat_AsDouble(value);
}
/* Output frequency */
if(strcmp(PyString_AsString(key), "TimeBetSnapshot")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.TimeBetSnapshot = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "TimeOfFirstSnapshot")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.TimeOfFirstSnapshot = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "CpuTimeBetRestartFile")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.CpuTimeBetRestartFile = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "TimeBetStatistics")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.TimeBetStatistics = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "NumFilesPerSnapshot")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.NumFilesPerSnapshot = PyInt_AsLong(value);
}
if(strcmp(PyString_AsString(key), "NumFilesWrittenInParallel")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.NumFilesWrittenInParallel = PyInt_AsLong(value);
}
/* Accuracy of time integration */
if(strcmp(PyString_AsString(key), "ErrTolIntAccuracy")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.ErrTolIntAccuracy = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "MaxRMSDisplacementFac")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.MaxRMSDisplacementFac = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "CourantFac")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.CourantFac = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "MaxSizeTimestep")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.MaxSizeTimestep = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "MinSizeTimestep")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.MinSizeTimestep = PyFloat_AsDouble(value);
}
/* Tree algorithm, force accuracy, domain update frequency */
if(strcmp(PyString_AsString(key), "ErrTolTheta")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.ErrTolTheta = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "TypeOfOpeningCriterion")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.TypeOfOpeningCriterion = PyInt_AsLong(value);
}
if(strcmp(PyString_AsString(key), "ErrTolForceAcc")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.ErrTolForceAcc = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "TreeDomainUpdateFrequency")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.TreeDomainUpdateFrequency = PyFloat_AsDouble(value);
}
/* Further parameters of SPH */
if(strcmp(PyString_AsString(key), "DesNumNgb")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.DesNumNgb = PyInt_AsLong(value);
}
if(strcmp(PyString_AsString(key), "MaxNumNgbDeviation")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.MaxNumNgbDeviation = PyInt_AsLong(value);
}
if(strcmp(PyString_AsString(key), "ArtBulkViscConst")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.ArtBulkViscConst = PyInt_AsLong(value);
}
if(strcmp(PyString_AsString(key), "InitGasTemp")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.InitGasTemp = PyInt_AsLong(value);
}
if(strcmp(PyString_AsString(key), "MinGasTemp")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.MinGasTemp = PyInt_AsLong(value);
}
/* Memory allocation */
if(strcmp(PyString_AsString(key), "PartAllocFactor")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.PartAllocFactor = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "TreeAllocFactor")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.TreeAllocFactor = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "BufferSize")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.BufferSize = PyInt_AsLong(value);
}
/* System of units */
if(strcmp(PyString_AsString(key), "UnitLength_in_cm")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.UnitLength_in_cm = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "UnitMass_in_g")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.UnitMass_in_g = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "UnitVelocity_in_cm_per_s")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.UnitVelocity_in_cm_per_s = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "GravityConstantInternal")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.GravityConstantInternal = PyFloat_AsDouble(value);
}
/* Softening lengths */
if(strcmp(PyString_AsString(key), "MinGasHsmlFractional")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.MinGasHsmlFractional = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "SofteningGas")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.SofteningGas = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "SofteningHalo")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.SofteningHalo = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "SofteningDisk")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.SofteningDisk = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "SofteningBulge")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.SofteningBulge = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "SofteningStars")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.SofteningStars = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "SofteningBndry")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.SofteningBndry = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "SofteningGasMaxPhys")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.SofteningGasMaxPhys = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "SofteningHaloMaxPhys")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.SofteningHaloMaxPhys = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "SofteningDiskMaxPhys")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.SofteningDiskMaxPhys = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "SofteningBulgeMaxPhys")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.SofteningBulgeMaxPhys = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "SofteningStarsMaxPhys")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.SofteningStarsMaxPhys = PyFloat_AsDouble(value);
}
if(strcmp(PyString_AsString(key), "SofteningBndryMaxPhys")==0)
{
if(PyInt_Check(value)||PyLong_Check(value)||PyFloat_Check(value))
All.SofteningBndryMaxPhys = PyFloat_AsDouble(value);
}
}
}
return Py_BuildValue("i",1);
}
static PyObject *
gadget_check_parser(PyObject *self, PyObject *args, PyObject *keywds)
{
int voltage;
char *state = "a stiff";
char *action = "voom";
char *type = "Norwegian Blue";
static char *kwlist[] = {"voltage", "state", "action", "type", NULL};
if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,
&voltage, &state, &action, &type))
return NULL;
printf("-- This parrot wouldn't %s if you put %i Volts through it.\n",
action, voltage);
printf("-- Lovely plumage, the %s -- It's %s!\n", type, state);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *gadget_Free(PyObject *self, PyObject *args, PyObject *kwds)
{
free_memory();
ngb_treefree();
force_treefree();
free(Exportflag );
free(DomainStartList);
free(DomainEndList);
free(TopNodes);
free(DomainWork);
free(DomainCount);
free(DomainCountSph);
free(DomainTask);
free(DomainNodeIndex);
free(DomainTreeNodeLen);
free(DomainHmax);
free(DomainMoment);
free(CommBuffer);
gsl_rng_free(random_generator);
return Py_BuildValue("i",1);
}
static PyObject *gadget_LoadParticles(PyObject *self, PyObject *args, PyObject *kwds)
{
int i,j;
size_t bytes;
PyArrayObject *ntype=Py_None;
PyArrayObject *pos=Py_None;
PyArrayObject *vel=Py_None;
PyArrayObject *mass=Py_None;
PyArrayObject *num=Py_None;
PyArrayObject *tpe=Py_None;
PyArrayObject *u=Py_None;
PyArrayObject *rho=Py_None;
static char *kwlist[] = {"npart", "pos","vel","mass","num","tpe","u","rho", NULL};
if (! PyArg_ParseTupleAndKeywords(args,kwds, "OOOOOO|OO",kwlist,&ntype,&pos,&vel,&mass,&num,&tpe,&u,&rho ))
return NULL;
/* check type */
if (!(PyArray_Check(pos)))
{
PyErr_SetString(PyExc_ValueError,"aruments 2 must be array.");
return NULL;
}
/* check type */
if (!(PyArray_Check(mass)))
{
PyErr_SetString(PyExc_ValueError,"aruments 3 must be array.");
return NULL;
}
/* check dimension */
if ( (pos->nd!=2))
{
PyErr_SetString(PyExc_ValueError,"Dimension of argument 2 must be 2.");
return NULL;
}
/* check dimension */
if ( (mass->nd!=1))
{
PyErr_SetString(PyExc_ValueError,"Dimension of argument 3 must be 1.");
return NULL;
}
/* check size */
if ( (pos->dimensions[1]!=3))
{
PyErr_SetString(PyExc_ValueError,"First size of argument must be 3.");
return NULL;
}
/* check size */
if ( (pos->dimensions[0]!=mass->dimensions[0]))
{
PyErr_SetString(PyExc_ValueError,"Size of argument 2 must be similar to argument 3.");
return NULL;
}
/* ensure double */
ntype = TO_INT(ntype);
pos = TO_FLOAT(pos);
vel = TO_FLOAT(vel);
mass = TO_FLOAT(mass);
num = TO_FLOAT(num);
tpe = TO_FLOAT(tpe);
/* optional variables */
if (u!=Py_None)
u = TO_FLOAT(u);
if (rho!=Py_None)
rho = TO_FLOAT(rho);
/***************************************
* some inits *
/***************************************/
RestartFlag = 0;
Begrun1();
/***************************************
* LOAD PARTILES *
/***************************************/
NumPart = 0;
N_gas = *(int*) (ntype->data + 0*(ntype->strides[0]));
for (i = 0; i < 6; i++)
NumPart += *(int*) (ntype->data + i*(ntype->strides[0]));
if (NumPart!=pos->dimensions[0])
{
PyErr_SetString(PyExc_ValueError,"Numpart != pos->dimensions[0].");
return NULL;
}
MPI_Allreduce(&NumPart, &All.TotNumPart, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&N_gas, &All.TotN_gas, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
All.MaxPart = All.PartAllocFactor * (All.TotNumPart / NTask);
All.MaxPartSph = All.PartAllocFactor * (All.TotN_gas / NTask);
/*********************/
/* allocate P */
/*********************/
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);
}
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);
}
/*********************/
/* init P */
/*********************/
for (i = 0; i < NumPart; i++)
{
P[i].Pos[0] = *(float *) (pos->data + i*(pos->strides[0]) + 0*pos->strides[1]);
P[i].Pos[1] = *(float *) (pos->data + i*(pos->strides[0]) + 1*pos->strides[1]);
P[i].Pos[2] = *(float *) (pos->data + i*(pos->strides[0]) + 2*pos->strides[1]);
P[i].Vel[0] = *(float *) (vel->data + i*(vel->strides[0]) + 0*vel->strides[1]);
P[i].Vel[1] = *(float *) (vel->data + i*(vel->strides[0]) + 1*vel->strides[1]);
P[i].Vel[2] = *(float *) (vel->data + i*(vel->strides[0]) + 2*vel->strides[1]);
P[i].Mass = *(float *) (mass->data + i*(mass->strides[0]));
P[i].ID = *(unsigned int *) (num->data + i*(num->strides[0]));
P[i].Type = *(int *) (tpe->data + i*(tpe->strides[0]));
//P[i].Active = 1;
}
/*********************/
/* init SphP */
/*********************/
if (u!=Py_None)
for (i = 0; i < NumPart; i++)
{
SphP[i].Entropy = *(float *) (u->data + i*(u->strides[0]));
//#ifndef ISOTHERM_EQS
// SphP[i].Entropy = GAMMA_MINUS1 * SphP[i].Entropy / pow(SphP[i].Density / a3, GAMMA_MINUS1);
//#endif
}
if (rho!=Py_None)
for (i = 0; i < NumPart; i++)
{
SphP[i].Density = *(float *) (rho->data + i*(rho->strides[0]));
}
/***************************************
* END LOAD PARTICLES *
/***************************************/
/***************************************
* finish inits *
/***************************************/
Begrun2();
/***************************************
* free memory *
/***************************************/
/* free the memory allocated,
because these vectors where casted
and their memory is now handeled by the C part */
Py_DECREF(ntype);
Py_DECREF(pos);
Py_DECREF(vel);
Py_DECREF(mass);
Py_DECREF(num);
Py_DECREF(tpe);
/* optional variables */
if (u!=Py_None)
Py_DECREF(u);
if (rho!=Py_None)
Py_DECREF(rho);
return Py_BuildValue("i",1);
}
static PyObject *gadget_LoadParticlesQ(PyObject *self, PyObject *args, PyObject *kwds)
{
int i,j;
size_t bytes;
PyArrayObject *ntype,*pos,*vel,*mass,*num,*tpe;
static char *kwlist[] = {"npart", "pos","vel","mass","num","tpe", NULL};
if (! PyArg_ParseTupleAndKeywords(args, kwds, "|OOOOOO",kwlist,&ntype,&pos,&vel,&mass,&num,&tpe))
return Py_BuildValue("i",1);
/* check type */
if (!(PyArray_Check(pos)))
{
PyErr_SetString(PyExc_ValueError,"aruments 1 must be array.");
return NULL;
}
/* check type */
if (!(PyArray_Check(mass)))
{
PyErr_SetString(PyExc_ValueError,"aruments 2 must be array.");
return NULL;
}
/* check dimension */
if ( (pos->nd!=2))
{
PyErr_SetString(PyExc_ValueError,"Dimension of argument 1 must be 2.");
return NULL;
}
/* check dimension */
if ( (mass->nd!=1))
{
PyErr_SetString(PyExc_ValueError,"Dimension of argument 2 must be 1.");
return NULL;
}
/* check size */
if ( (pos->dimensions[1]!=3))
{
PyErr_SetString(PyExc_ValueError,"First size of argument must be 3.");
return NULL;
}
/* check size */
if ( (pos->dimensions[0]!=mass->dimensions[0]))
{
PyErr_SetString(PyExc_ValueError,"Size of argument 1 must be similar to argument 2.");
return NULL;
}
/* ensure double */
ntype = TO_INT(ntype);
pos = TO_FLOAT(pos);
vel = TO_FLOAT(vel);
mass = TO_FLOAT(mass);
num = TO_FLOAT(num);
tpe = TO_FLOAT(tpe);
/***************************************
* some inits *
/***************************************/
allocate_commbuffersQ();
/***************************************
* LOAD PARTILES *
/***************************************/
NumPartQ = 0;
N_gasQ = *(int*) (ntype->data + 0*(ntype->strides[0]));
for (i = 0; i < 6; i++)
NumPartQ += *(int*) (ntype->data + i*(ntype->strides[0]));
if (NumPartQ!=pos->dimensions[0])
{
PyErr_SetString(PyExc_ValueError,"NumpartQ != pos->dimensions[0].");
return NULL;
}
MPI_Allreduce(&NumPartQ, &All.TotNumPartQ, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&N_gasQ, &All.TotN_gasQ, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
All.MaxPartQ = All.PartAllocFactor * (All.TotNumPartQ / NTask);
All.MaxPartSphQ = All.PartAllocFactor * (All.TotN_gasQ / NTask);
/*********************/
/* allocate Q */
/*********************/
if(!(Q = malloc(bytes = All.MaxPartQ * sizeof(struct particle_data))))
{
printf("failed to allocate memory for `Q' (%g MB).\n", bytes / (1024.0 * 1024.0));
endrun(1);
}
if(!(SphQ = malloc(bytes = All.MaxPartSphQ * sizeof(struct sph_particle_data))))
{
printf("failed to allocate memory for `SphQ' (%g MB) %d.\n", bytes / (1024.0 * 1024.0), sizeof(struct sph_particle_data));
endrun(1);
}
/*********************/
/* init P */
/*********************/
for (i = 0; i < NumPartQ; i++)
{
Q[i].Pos[0] = *(float *) (pos->data + i*(pos->strides[0]) + 0*pos->strides[1]);
Q[i].Pos[1] = *(float *) (pos->data + i*(pos->strides[0]) + 1*pos->strides[1]);
Q[i].Pos[2] = *(float *) (pos->data + i*(pos->strides[0]) + 2*pos->strides[1]);
Q[i].Vel[0] = *(float *) (vel->data + i*(vel->strides[0]) + 0*vel->strides[1]);
Q[i].Vel[1] = *(float *) (vel->data + i*(vel->strides[0]) + 1*vel->strides[1]);
Q[i].Vel[2] = *(float *) (vel->data + i*(vel->strides[0]) + 2*vel->strides[1]);
Q[i].Mass = *(float *) (mass->data + i*(mass->strides[0]));
Q[i].ID = *(unsigned int *) (num->data + i*(num->strides[0]));
Q[i].Type = *(int *) (tpe->data + i*(tpe->strides[0]));
//Q[i].Active = 1;
}
/***************************************
* END LOAD PARTILES *
/***************************************/
domain_DecompositionQ();
/***************************************
* finish inits *
/***************************************/
return Py_BuildValue("i",1);
}
static PyObject *gadget_AllPotential(PyObject *self)
{
compute_potential();
return Py_BuildValue("i",1);
}
static PyObject * gadget_GetAllPotential(PyObject* self)
{
PyArrayObject *pot;
npy_intp ld[1];
int i;
ld[0] = NumPart;
pot = (PyArrayObject *) PyArray_SimpleNew(1,ld,PyArray_FLOAT);
for (i = 0; i < pot->dimensions[0]; i++)
{
*(float *) (pot->data + i*(pot->strides[0])) = P[i].Potential;
}
return PyArray_Return(pot);
}
static PyObject *gadget_AllAcceleration(PyObject *self)
{
NumForceUpdate = NumPart;
gravity_tree();
return Py_BuildValue("i",1);
}
static PyObject * gadget_GetAllAcceleration(PyObject* self)
{
PyArrayObject *acc;
npy_intp ld[2];
int i;
ld[0] = NumPart;
ld[1] = 3;
acc = (PyArrayObject *) PyArray_SimpleNew(2,ld,PyArray_FLOAT);
for (i = 0; i < acc->dimensions[0]; i++)
{
*(float *) (acc->data + i*(acc->strides[0]) + 0*acc->strides[1]) = P[i].GravAccel[0];
*(float *) (acc->data + i*(acc->strides[0]) + 1*acc->strides[1]) = P[i].GravAccel[1];
*(float *) (acc->data + i*(acc->strides[0]) + 2*acc->strides[1]) = P[i].GravAccel[2];
}
return PyArray_Return(acc);
}
static PyObject *gadget_GetAllDensities(PyObject* self)
{
PyArrayObject *rho;
npy_intp ld[1];
int i;
ld[0] = N_gas;
rho = (PyArrayObject *) PyArray_SimpleNew(1,ld,PyArray_FLOAT);
for (i = 0; i < rho->dimensions[0]; i++)
{
*(float *) (rho->data + i*(rho->strides[0])) = SphP[i].Density;
}
return PyArray_Return(rho);
}
static PyObject *gadget_GetAllHsml(PyObject* self)
{
PyArrayObject *hsml;
npy_intp ld[1];
int i;
ld[0] = N_gas;
hsml = (PyArrayObject *) PyArray_SimpleNew(1,ld,PyArray_FLOAT);
for (i = 0; i < hsml->dimensions[0]; i++)
{
*(float *) (hsml->data + i*(hsml->strides[0])) = SphP[i].Hsml;
}
return PyArray_Return(hsml);
}
static PyObject *gadget_GetAllPositions(PyObject* self)
{
PyArrayObject *pos;
npy_intp ld[2];
int i;
ld[0] = NumPart;
ld[1] = 3;
pos = (PyArrayObject *) PyArray_SimpleNew(2,ld,PyArray_FLOAT);
for (i = 0; i < pos->dimensions[0]; i++)
{
*(float *) (pos->data + i*(pos->strides[0]) + 0*pos->strides[1]) = P[i].Pos[0];
*(float *) (pos->data + i*(pos->strides[0]) + 1*pos->strides[1]) = P[i].Pos[1];
*(float *) (pos->data + i*(pos->strides[0]) + 2*pos->strides[1]) = P[i].Pos[2];
}
return PyArray_Return(pos);
}
static PyObject *gadget_GetAllVelocities(PyObject* self)
{
PyArrayObject *vel;
npy_intp ld[2];
int i;
ld[0] = NumPart;
ld[1] = 3;
vel = (PyArrayObject *) PyArray_SimpleNew(2,ld,PyArray_FLOAT);
for (i = 0; i < vel->dimensions[0]; i++)
{
*(float *) (vel->data + i*(vel->strides[0]) + 0*vel->strides[1]) = P[i].Vel[0];
*(float *) (vel->data + i*(vel->strides[0]) + 1*vel->strides[1]) = P[i].Vel[1];
*(float *) (vel->data + i*(vel->strides[0]) + 2*vel->strides[1]) = P[i].Vel[2];
}
return PyArray_Return(vel);
}
static PyObject *gadget_GetAllMasses(PyObject* self)
{
PyArrayObject *mass;
npy_intp ld[1];
int i;
ld[0] = NumPart;
mass = (PyArrayObject *) PyArray_SimpleNew(1,ld,PyArray_FLOAT);
for (i = 0; i < mass->dimensions[0]; i++)
{
*(float *) (mass->data + i*(mass->strides[0])) = P[i].Mass;
}
return PyArray_Return(mass);
}
static PyObject *gadget_GetAllEntropy(PyObject* self)
{
PyArrayObject *entropy;
npy_intp ld[1];
int i;
ld[0] = NumPart;
entropy = (PyArrayObject *) PyArray_SimpleNew(1,ld,PyArray_FLOAT);
for (i = 0; i < entropy->dimensions[0]; i++)
{
*(float *) (entropy->data + i*(entropy->strides[0])) = SphP[i].Entropy;
}
return PyArray_Return(entropy);
}
static PyObject *gadget_GetAllEnergySpec(PyObject* self)
{
PyArrayObject *energy;
npy_intp ld[1];
int i;
double a3inv;
ld[0] = NumPart;
energy = (PyArrayObject *) PyArray_SimpleNew(1,ld,PyArray_FLOAT);
if(All.ComovingIntegrationOn)
{
a3inv = 1 / (All.Time * All.Time * All.Time);
}
else
a3inv = 1;
for (i = 0; i < energy->dimensions[0]; i++)
{
#ifdef ISOTHERM_EQS
*(float *) (energy->data + i*(energy->strides[0])) = SphP[i].Entropy;
#else
a3inv = 1.;
*(float *) (energy->data + i*(energy->strides[0])) = dmax(All.MinEgySpec,SphP[i].Entropy / GAMMA_MINUS1 * pow(SphP[i].Density * a3inv, GAMMA_MINUS1));
#endif
}
return PyArray_Return(energy);
}
static PyObject *gadget_GetAllID(PyObject* self)
{
PyArrayObject *id;
npy_intp ld[1];
int i;
ld[0] = NumPart;
id = (PyArrayObject *) PyArray_SimpleNew(1,ld,PyArray_INT);
for (i = 0; i < id->dimensions[0]; i++)
{
*(float *) (id->data + i*(id->strides[0])) = P[i].ID;
}
return PyArray_Return(id);
}
static PyObject *gadget_GetAllTypes(PyObject* self)
{
PyArrayObject *type;
npy_intp ld[1];
int i;
ld[0] = NumPart;
type = (PyArrayObject *) PyArray_SimpleNew(1,ld,PyArray_INT);
for (i = 0; i < type->dimensions[0]; i++)
{
*(int *) (type->data + i*(type->strides[0])) = P[i].Type;
}
return PyArray_Return(type);
}
static PyObject *gadget_GetAllPositionsQ(PyObject* self)
{
PyArrayObject *pos;
npy_intp ld[2];
int i;
ld[0] = NumPartQ;
ld[1] = 3;
pos = (PyArrayObject *) PyArray_SimpleNew(2,ld,PyArray_FLOAT);
for (i = 0; i < pos->dimensions[0]; i++)
{
*(float *) (pos->data + i*(pos->strides[0]) + 0*pos->strides[1]) = Q[i].Pos[0];
*(float *) (pos->data + i*(pos->strides[0]) + 1*pos->strides[1]) = Q[i].Pos[1];
*(float *) (pos->data + i*(pos->strides[0]) + 2*pos->strides[1]) = Q[i].Pos[2];
}
return PyArray_Return(pos);
}
static PyObject *gadget_GetAllVelocitiesQ(PyObject* self)
{
PyArrayObject *vel;
npy_intp ld[2];
int i;
ld[0] = NumPartQ;
ld[1] = 3;
vel = (PyArrayObject *) PyArray_SimpleNew(2,ld,PyArray_FLOAT);
for (i = 0; i < vel->dimensions[0]; i++)
{
*(float *) (vel->data + i*(vel->strides[0]) + 0*vel->strides[1]) = Q[i].Vel[0];
*(float *) (vel->data + i*(vel->strides[0]) + 1*vel->strides[1]) = Q[i].Vel[1];
*(float *) (vel->data + i*(vel->strides[0]) + 2*vel->strides[1]) = Q[i].Vel[2];
}
return PyArray_Return(vel);
}
static PyObject *gadget_GetAllMassesQ(PyObject* self)
{
PyArrayObject *mass;
npy_intp ld[1];
int i;
ld[0] = NumPartQ;
mass = (PyArrayObject *) PyArray_SimpleNew(1,ld,PyArray_FLOAT);
for (i = 0; i < mass->dimensions[0]; i++)
{
*(float *) (mass->data + i*(mass->strides[0])) = Q[i].Mass;
}
return PyArray_Return(mass);
}
static PyObject *gadget_GetAllIDQ(PyObject* self)
{
PyArrayObject *id;
npy_intp ld[1];
int i;
ld[0] = NumPartQ;
id = (PyArrayObject *) PyArray_SimpleNew(1,ld,PyArray_INT);
for (i = 0; i < id->dimensions[0]; i++)
{
*(float *) (id->data + i*(id->strides[0])) = Q[i].ID;
}
return PyArray_Return(id);
}
static PyObject *gadget_GetAllTypesQ(PyObject* self)
{
PyArrayObject *type;
npy_intp ld[1];
int i;
ld[0] = NumPartQ;
type = (PyArrayObject *) PyArray_SimpleNew(1,ld,PyArray_INT);
for (i = 0; i < type->dimensions[0]; i++)
{
*(int *) (type->data + i*(type->strides[0])) = Q[i].Type;
}
return PyArray_Return(type);
}
static PyObject *gadget_GetPos(PyObject *self, PyObject *args, PyObject *kwds)
{
int i,j;
size_t bytes;
PyArrayObject *pos;
if (! PyArg_ParseTuple(args, "O",&pos))
return PyString_FromString("error : GetPos");
for (i = 0; i < pos->dimensions[0]; i++)
{
*(float *) (pos->data + i*(pos->strides[0]) + 0*pos->strides[1]) = P[i].Pos[0];
*(float *) (pos->data + i*(pos->strides[0]) + 1*pos->strides[1]) = P[i].Pos[1];
*(float *) (pos->data + i*(pos->strides[0]) + 2*pos->strides[1]) = P[i].Pos[2];
}
//return PyArray_Return(Py_None);
return Py_BuildValue("i",1);
}
static PyObject * gadget_Potential(PyObject* self, PyObject *args)
{
PyArrayObject *pos;
float eps;
if (! PyArg_ParseTuple(args, "Of",&pos,&eps))
return PyString_FromString("error");
PyArrayObject *pot;
int i;
npy_intp ld[1];
int input_dimension;
size_t bytes;
input_dimension =pos->nd;
if (input_dimension != 2)
PyErr_SetString(PyExc_ValueError,"dimension of first argument must be 2");
pos = TO_FLOAT(pos);
/* create a NumPy object */
ld[0]=pos->dimensions[0];
pot = (PyArrayObject *) PyArray_SimpleNew(1,ld,PyArray_FLOAT);
NumPartQ = pos->dimensions[0];
All.ForceSofteningQ = eps;
if(!(Q = malloc(bytes = NumPartQ * sizeof(struct particle_data))))
{
printf("failed to allocate memory for `Q' (%g MB).\n", bytes / (1024.0 * 1024.0));
endrun(1);
}
if(!(SphQ = malloc(bytes = NumPartQ * sizeof(struct sph_particle_data))))
{
printf("failed to allocate memory for `SphQ' (%g MB).\n", bytes / (1024.0 * 1024.0));
endrun(1);
}
for (i = 0; i < pos->dimensions[0]; i++)
{
Q[i].Pos[0] = *(float *) (pos->data + i*(pos->strides[0]) + 0*pos->strides[1]);
Q[i].Pos[1] = *(float *) (pos->data + i*(pos->strides[0]) + 1*pos->strides[1]);
Q[i].Pos[2] = *(float *) (pos->data + i*(pos->strides[0]) + 2*pos->strides[1]);
Q[i].Type = 0;
Q[i].Mass = 0;
Q[i].Potential = 0;
}
compute_potential_sub();
for (i = 0; i < pos->dimensions[0]; i++)
{
*(float *)(pot->data + i*(pot->strides[0])) = Q[i].Potential;
}
free(Q);
free(SphQ);
return PyArray_Return(pot);
}
static PyObject * gadget_Acceleration(PyObject* self, PyObject *args)
{
PyArrayObject *pos;
float eps;
if (! PyArg_ParseTuple(args, "Of",&pos,&eps))
return PyString_FromString("error");
PyArrayObject *acc;
int i;
int input_dimension;
size_t bytes;
input_dimension =pos->nd;
if (input_dimension != 2)
PyErr_SetString(PyExc_ValueError,"dimension of first argument must be 2");
pos = TO_FLOAT(pos);
/* create a NumPy object */
acc = (PyArrayObject *) PyArray_SimpleNew(pos->nd,pos->dimensions,PyArray_FLOAT);
NumPartQ = pos->dimensions[0];
All.ForceSofteningQ = eps;
if(!(Q = malloc(bytes = NumPartQ * sizeof(struct particle_data))))
{
printf("failed to allocate memory for `Q' (%g MB).\n", bytes / (1024.0 * 1024.0));
endrun(1);
}
if(!(SphQ = malloc(bytes = NumPartQ * sizeof(struct sph_particle_data))))
{
printf("failed to allocate memory for `SphQ' (%g MB).\n", bytes / (1024.0 * 1024.0));
endrun(1);
}
for (i = 0; i < pos->dimensions[0]; i++)
{
Q[i].Pos[0] = *(float *) (pos->data + i*(pos->strides[0]) + 0*pos->strides[1]);
Q[i].Pos[1] = *(float *) (pos->data + i*(pos->strides[0]) + 1*pos->strides[1]);
Q[i].Pos[2] = *(float *) (pos->data + i*(pos->strides[0]) + 2*pos->strides[1]);
Q[i].Type = 0;
Q[i].Mass = 0;
Q[i].GravAccel[0] = 0;
Q[i].GravAccel[1] = 0;
Q[i].GravAccel[2] = 0;
}
gravity_tree_sub();
for (i = 0; i < pos->dimensions[0]; i++)
{
*(float *)(acc->data + i*(acc->strides[0]) + 0*acc->strides[1]) = Q[i].GravAccel[0];
*(float *)(acc->data + i*(acc->strides[0]) + 1*acc->strides[1]) = Q[i].GravAccel[1];
*(float *)(acc->data + i*(acc->strides[0]) + 2*acc->strides[1]) = Q[i].GravAccel[2];
}
free(Q);
free(SphQ);
return PyArray_Return(acc);
}
static PyObject * gadget_InitHsml(PyObject* self, PyObject *args)
{
PyArrayObject *pos,*hsml;
if (! PyArg_ParseTuple(args, "OO",&pos,&hsml))
return PyString_FromString("error");
int i;
int input_dimension;
size_t bytes;
int ld[1];
PyArrayObject *vden,*vhsml;
input_dimension =pos->nd;
if (input_dimension != 2)
PyErr_SetString(PyExc_ValueError,"dimension of first argument must be 2");
if (pos->dimensions[0] != hsml->dimensions[0])
PyErr_SetString(PyExc_ValueError,"pos and hsml must have the same dimension.");
pos = TO_FLOAT(pos);
hsml = TO_FLOAT(hsml);
/* create a NumPy object */
ld[0]=pos->dimensions[0];
vden = (PyArrayObject *) PyArray_SimpleNew(1,pos->dimensions,pos->descr->type_num);
vhsml = (PyArrayObject *) PyArray_SimpleNew(1,pos->dimensions,pos->descr->type_num);
NumPartQ = pos->dimensions[0];
N_gasQ = NumPartQ;
All.Ti_Current=1; /* need to flag active particles */
if(!(Q = malloc(bytes = NumPartQ * sizeof(struct particle_data))))
{
printf("failed to allocate memory for `Q' (%g MB).\n", bytes / (1024.0 * 1024.0));
endrun(1);
}
if(!(SphQ = malloc(bytes = NumPartQ * sizeof(struct sph_particle_data))))
{
printf("failed to allocate memory for `SphQ' (%g MB).\n", bytes / (1024.0 * 1024.0));
endrun(1);
}
for (i = 0; i < pos->dimensions[0]; i++)
{
Q[i].Pos[0] = *(float *) (pos->data + i*(pos->strides[0]) + 0*pos->strides[1]);
Q[i].Pos[1] = *(float *) (pos->data + i*(pos->strides[0]) + 1*pos->strides[1]);
Q[i].Pos[2] = *(float *) (pos->data + i*(pos->strides[0]) + 2*pos->strides[1]);
SphQ[i].Hsml = *(float *) (hsml->data + i*(hsml->strides[0]));
}
setup_smoothinglengths_sub();
for (i = 0; i < pos->dimensions[0]; i++)
{
*(float *)(vhsml->data + i*(vhsml->strides[0])) = SphQ[i].Hsml;
*(float *)(vden->data + i*(vden->strides[0])) = SphQ[i].Density;
}
free(Q);
free(SphQ);
return Py_BuildValue("OO",vden,vhsml);
}
static PyObject * gadget_Density(PyObject* self, PyObject *args)
{
PyArrayObject *pos,*hsml;
if (! PyArg_ParseTuple(args, "OO",&pos,&hsml))
return PyString_FromString("error");
int i;
int input_dimension;
size_t bytes;
int ld[1];
PyArrayObject *vden,*vhsml;
input_dimension =pos->nd;
if (input_dimension != 2)
PyErr_SetString(PyExc_ValueError,"dimension of first argument must be 2");
if (pos->dimensions[0] != hsml->dimensions[0])
PyErr_SetString(PyExc_ValueError,"pos and hsml must have the same dimension.");
pos = TO_FLOAT(pos);
hsml = TO_FLOAT(hsml);
/* create a NumPy object */
ld[0]=pos->dimensions[0];
vden = (PyArrayObject *) PyArray_SimpleNew(1,pos->dimensions,pos->descr->type_num);
vhsml = (PyArrayObject *) PyArray_SimpleNew(1,pos->dimensions,pos->descr->type_num);
NumPartQ = pos->dimensions[0];
N_gasQ = NumPartQ;
All.Ti_Current=1; /* need to flag active particles */
if(!(Q = malloc(bytes = NumPartQ * sizeof(struct particle_data))))
{
printf("failed to allocate memory for `Q' (%g MB).\n", bytes / (1024.0 * 1024.0));
endrun(1);
}
if(!(SphQ = malloc(bytes = NumPartQ * sizeof(struct sph_particle_data))))
{
printf("failed to allocate memory for `SphQ' (%g MB).\n", bytes / (1024.0 * 1024.0));
endrun(1);
}
for (i = 0; i < pos->dimensions[0]; i++)
{
Q[i].Pos[0] = *(float *) (pos->data + i*(pos->strides[0]) + 0*pos->strides[1]);
Q[i].Pos[1] = *(float *) (pos->data + i*(pos->strides[0]) + 1*pos->strides[1]);
Q[i].Pos[2] = *(float *) (pos->data + i*(pos->strides[0]) + 2*pos->strides[1]);
SphQ[i].Hsml = *(float *) (hsml->data + i*(hsml->strides[0]));
}
density_sub();
for (i = 0; i < pos->dimensions[0]; i++)
{
*(float *)(vhsml->data + i*(vhsml->strides[0])) = SphQ[i].Hsml;
*(float *)(vden->data + i*(vden->strides[0])) = SphQ[i].Density;
}
free(Q);
free(SphQ);
return Py_BuildValue("OO",vden,vhsml);
}
static PyObject * gadget_SphEvaluate(PyObject* self, PyObject *args)
{
PyArrayObject *pos,*hsml,*obs;
if (! PyArg_ParseTuple(args, "OOO",&pos,&hsml,&obs))
return PyString_FromString("error");
int i;
int input_dimension;
size_t bytes;
int ld[1];
PyArrayObject *vobs;
input_dimension =pos->nd;
if (input_dimension != 2)
PyErr_SetString(PyExc_ValueError,"dimension of first argument must be 2");
if (pos->dimensions[0] != hsml->dimensions[0])
PyErr_SetString(PyExc_ValueError,"pos and hsml must have the same dimension.");
if (obs->nd != 1)
PyErr_SetString(PyExc_ValueError,"dimension of obs must be 1.");
if (obs->dimensions[0] != NumPart)
PyErr_SetString(PyExc_ValueError,"The size of obs must be NumPart.");
pos = TO_FLOAT(pos);
hsml = TO_FLOAT(hsml);
obs = TO_FLOAT(obs);
/* create a NumPy object */
ld[0]=pos->dimensions[0];
vobs = (PyArrayObject *) PyArray_SimpleNew(1,pos->dimensions,pos->descr->type_num);
NumPartQ = pos->dimensions[0];
N_gasQ = NumPartQ;
All.Ti_Current=1; /* need to flag active particles */
if(!(Q = malloc(bytes = NumPartQ * sizeof(struct particle_data))))
{
printf("failed to allocate memory for `Q' (%g MB).\n", bytes / (1024.0 * 1024.0));
endrun(1);
}
if(!(SphQ = malloc(bytes = NumPartQ * sizeof(struct sph_particle_data))))
{
printf("failed to allocate memory for `SphQ' (%g MB).\n", bytes / (1024.0 * 1024.0));
endrun(1);
}
for (i = 0; i < pos->dimensions[0]; i++)
{
Q[i].Pos[0] = *(float *) (pos->data + i*(pos->strides[0]) + 0*pos->strides[1]);
Q[i].Pos[1] = *(float *) (pos->data + i*(pos->strides[0]) + 1*pos->strides[1]);
Q[i].Pos[2] = *(float *) (pos->data + i*(pos->strides[0]) + 2*pos->strides[1]);
SphQ[i].Hsml = *(float *) (hsml->data + i*(hsml->strides[0]));
}
/* now, give observable value for P */
for (i = 0; i < NumPart; i++)
{
SphP[i].Observable = *(float *) (obs->data + i*(obs->strides[0]));
}
sph_sub();
for (i = 0; i < pos->dimensions[0]; i++)
{
*(float *)(vobs->data + i*(vobs->strides[0])) = SphQ[i].Observable;
}
free(Q);
free(SphQ);
return Py_BuildValue("O",vobs);
}
static PyObject * gadget_Ngbs(PyObject* self, PyObject *args)
{
PyArrayObject *pos;
float eps;
if (! PyArg_ParseTuple(args, "Of",&pos,&eps))
return PyString_FromString("error");
PyArrayObject *poss;
int i,j,n,nn;
int input_dimension;
size_t bytes;
int startnode,numngb;
int phase=0;
FLOAT searchcenter[3];
double dx,dy,dz,r2,eps2;
input_dimension =pos->nd;
if (input_dimension != 1)
PyErr_SetString(PyExc_ValueError,"dimension of first argument must be 1");
pos = TO_FLOAT(pos);
eps2 = eps*eps;
searchcenter[0] = (FLOAT)*(float *) (pos->data + 0*(pos->strides[0]));
searchcenter[1] = (FLOAT)*(float *) (pos->data + 1*(pos->strides[0]));
searchcenter[2] = (FLOAT)*(float *) (pos->data + 2*(pos->strides[0]));
startnode = All.MaxPart;
/* ici, il faut faire une fct qui fonctionne en //, cf hydra --> Exportflag */
numngb = ngb_treefind_pairs(&searchcenter[0], (FLOAT)eps, phase, &startnode);
nn=0;
for(n = 0;n < numngb; n++)
{
j = Ngblist[n];
dx = searchcenter[0] - P[j].Pos[0];
dy = searchcenter[1] - P[j].Pos[1];
dz = searchcenter[2] - P[j].Pos[2];
r2 = dx * dx + dy * dy + dz * dz;
if (r2<=eps2)
{
printf("%d r=%g\n",nn,sqrt(r2));
nn++;
}
}
return PyArray_Return(pos);
}
static PyObject * gadget_SphEvaluateOrigAll(PyObject* self, PyObject *args)
{
PyArrayObject *obs;
if (! PyArg_ParseTuple(args, "O",&obs))
return PyString_FromString("error");
int i;
size_t bytes;
int ld[1];
PyArrayObject *vobs;
if (obs->nd != 1)
PyErr_SetString(PyExc_ValueError,"dimension of obs must be 1.");
if (obs->dimensions[0] != NumPart)
PyErr_SetString(PyExc_ValueError,"The size of obs must be NumPart.");
obs = TO_FLOAT(obs);
/* create a NumPy object */
ld[0]=NumPart;
vobs = (PyArrayObject *) PyArray_SimpleNew(1,ld,PyArray_FLOAT);
/* flag all particles as active */
for (i = 0; i < NumPart; i++)
P[i].Ti_endstep == All.Ti_Current;
/* now, give observable value for P */
for (i = 0; i < NumPart; i++)
{
SphP[i].Observable = *(float *) (obs->data + i*(obs->strides[0]));
}
sph_orig();
for (i = 0; i < NumPart; i++)
{
*(float *)(vobs->data + i*(vobs->strides[0])) = SphP[i].Observable;
}
return Py_BuildValue("O",vobs);
}
static PyObject * gadget_SphEvaluateAll(PyObject* self, PyObject *args)
{
PyArrayObject *obs;
if (! PyArg_ParseTuple(args, "O",&obs))
return PyString_FromString("error");
int i;
size_t bytes;
int ld[1];
PyArrayObject *vobs;
if (obs->nd != 1)
PyErr_SetString(PyExc_ValueError,"dimension of obs must be 1.");
if (obs->dimensions[0] != NumPart)
PyErr_SetString(PyExc_ValueError,"The size of obs must be NumPart.");
obs = TO_FLOAT(obs);
/* create a NumPy object */
ld[0]=NumPart;
vobs = (PyArrayObject *) PyArray_SimpleNew(1,ld,PyArray_FLOAT);
/* flag all particles as active */
for (i = 0; i < NumPart; i++)
P[i].Ti_endstep == All.Ti_Current;
/* now, give observable value for P */
for (i = 0; i < NumPart; i++)
{
SphP[i].Observable = *(float *) (obs->data + i*(obs->strides[0]));
}
sph();
for (i = 0; i < NumPart; i++)
{
*(float *)(vobs->data + i*(vobs->strides[0])) = SphP[i].Observable;
}
return Py_BuildValue("O",vobs);
}
static PyObject * gadget_SphEvaluateGradientAll(PyObject* self, PyObject *args)
{
PyArrayObject *obs;
if (! PyArg_ParseTuple(args, "O",&obs))
return PyString_FromString("error");
int i;
size_t bytes;
npy_intp ld[2];
PyArrayObject *grad;
if (obs->nd != 1)
PyErr_SetString(PyExc_ValueError,"dimension of obs must be 1.");
if (obs->dimensions[0] != NumPart)
PyErr_SetString(PyExc_ValueError,"The size of obs must be NumPart.");
obs = TO_FLOAT(obs);
All.Ti_Current=1; /* need to flag active particles */
/* now, give observable value for P */
for (i = 0; i < NumPart; i++)
{
SphP[i].Observable = *(float *) (obs->data + i*(obs->strides[0]));
}
sph();
/* create a NumPy object */
ld[0] = NumPart;
ld[1] = 3;
grad = (PyArrayObject *) PyArray_SimpleNew(2,ld,PyArray_FLOAT);
for (i = 0; i < NumPart; i++)
{
*(float *) (grad->data + i*(grad->strides[0]) + 0*grad->strides[1]) = SphP[i].GradObservable[0];
*(float *) (grad->data + i*(grad->strides[0]) + 1*grad->strides[1]) = SphP[i].GradObservable[1];
*(float *) (grad->data + i*(grad->strides[0]) + 2*grad->strides[1]) = SphP[i].GradObservable[2];
}
return PyArray_Return(grad);
}
static PyObject * gadget_DensityEvaluateAll(PyObject* self, PyObject *args)
{
int i;
/* flag all particles as active */
//All.Ti_Current=1; /* need to flag active particles */
for (i = 0; i < NumPart; i++)
P[i].Ti_endstep == All.Ti_Current;
density(0);
return Py_BuildValue("i",1);
}
static PyObject * gadget_DensityEvaluateGradientAll(PyObject* self, PyObject *args)
{
PyArrayObject *obs;
if (! PyArg_ParseTuple(args, "O",&obs))
return PyString_FromString("error");
int i;
size_t bytes;
npy_intp ld[2];
PyArrayObject *grad;
if (obs->nd != 1)
PyErr_SetString(PyExc_ValueError,"dimension of obs must be 1.");
if (obs->dimensions[0] != NumPart)
PyErr_SetString(PyExc_ValueError,"The size of obs must be NumPart.");
obs = TO_FLOAT(obs);
//All.Ti_Current=1; /* need to flag active particles */
for (i = 0; i < NumPart; i++)
P[i].Ti_endstep == All.Ti_Current;
/* now, give observable value for P */
for (i = 0; i < NumPart; i++)
{
SphP[i].Observable = *(float *) (obs->data + i*(obs->strides[0]));
}
density_sph_gradient();
/* create a NumPy object */
ld[0] = NumPart;
ld[1] = 3;
grad = (PyArrayObject *) PyArray_SimpleNew(2,ld,PyArray_FLOAT);
for (i = 0; i < NumPart; i++)
{
*(float *) (grad->data + i*(grad->strides[0]) + 0*grad->strides[1]) = SphP[i].GradObservable[0];
*(float *) (grad->data + i*(grad->strides[0]) + 1*grad->strides[1]) = SphP[i].GradObservable[1];
*(float *) (grad->data + i*(grad->strides[0]) + 2*grad->strides[1]) = SphP[i].GradObservable[2];
}
return PyArray_Return(grad);
}
static PyObject * gadget_EvaluateThermalConductivity(PyObject* self, PyObject *args)
{
PyArrayObject *obs;
if (! PyArg_ParseTuple(args, "O",&obs))
return PyString_FromString("error");
int i;
size_t bytes;
npy_intp ld[2];
PyArrayObject *grad;
if (obs->nd != 1)
PyErr_SetString(PyExc_ValueError,"dimension of obs must be 1.");
if (obs->dimensions[0] != NumPart)
PyErr_SetString(PyExc_ValueError,"The size of obs must be NumPart.");
obs = TO_FLOAT(obs);
//All.Ti_Current=1; /* need to flag active particles */
for (i = 0; i < NumPart; i++)
P[i].Ti_endstep == All.Ti_Current;
/* now, give observable value for P */
for (i = 0; i < NumPart; i++)
{
SphP[i].Observable = *(float *) (obs->data + i*(obs->strides[0]));
}
density_sph_gradient();
// equivalent of SphP[i].GradEnergyInt[0] is now in
//SphP[i].GradObservable[0]
//SphP[i].GradObservable[1]
//SphP[i].GradObservable[2]
/* now, compute thermal conductivity */
sph_thermal_conductivity();
/* create a NumPy object */
ld[0] = NumPart;
ld[1] = 3;
grad = (PyArrayObject *) PyArray_SimpleNew(2,ld,PyArray_FLOAT);
for (i = 0; i < NumPart; i++)
{
*(float *) (grad->data + i*(grad->strides[0]) + 0*grad->strides[1]) = SphP[i].GradObservable[0];
*(float *) (grad->data + i*(grad->strides[0]) + 1*grad->strides[1]) = SphP[i].GradObservable[1];
*(float *) (grad->data + i*(grad->strides[0]) + 2*grad->strides[1]) = SphP[i].GradObservable[2];
}
return PyArray_Return(grad);
}
static PyObject *gadget_LoadParticles2(PyObject *self, PyObject *args, PyObject *kwds)
{
int i,j;
size_t bytes;
PyArrayObject *ntype,*pos,*vel,*mass,*num,*tpe;
static char *kwlist[] = {"npart", "pos","vel","mass","num","tpe", NULL};
if (! PyArg_ParseTupleAndKeywords(args, kwds, "|OOOOOO",kwlist,&ntype,&pos,&vel,&mass,&num,&tpe))
return Py_BuildValue("i",1);
/* check type */
if (!(PyArray_Check(pos)))
{
PyErr_SetString(PyExc_ValueError,"aruments 1 must be array.");
return NULL;
}
/* check type */
if (!(PyArray_Check(mass)))
{
PyErr_SetString(PyExc_ValueError,"aruments 2 must be array.");
return NULL;
}
/* check dimension */
if ( (pos->nd!=2))
{
PyErr_SetString(PyExc_ValueError,"Dimension of argument 1 must be 2.");
return NULL;
}
/* check dimension */
if ( (mass->nd!=1))
{
PyErr_SetString(PyExc_ValueError,"Dimension of argument 2 must be 1.");
return NULL;
}
/* check size */
if ( (pos->dimensions[1]!=3))
{
PyErr_SetString(PyExc_ValueError,"First size of argument must be 3.");
return NULL;
}
/* check size */
if ( (pos->dimensions[0]!=mass->dimensions[0]))
{
PyErr_SetString(PyExc_ValueError,"Size of argument 1 must be similar to argument 2.");
return NULL;
}
/* ensure double */
// ntype = TO_INT(ntype);
// pos = TO_FLOAT(pos);
// vel = TO_FLOAT(vel);
// mass = TO_FLOAT(mass);
// num = TO_FLOAT(num);
// tpe = TO_FLOAT(tpe);
/***************************************
* some inits *
/***************************************/
RestartFlag = 0;
Begrun1();
/***************************************
* LOAD PARTILES *
/***************************************/
NumPart = 0;
N_gas = *(int*) (ntype->data + 0*(ntype->strides[0]));
for (i = 0; i < 6; i++)
NumPart += *(int*) (ntype->data + i*(ntype->strides[0]));
if (NumPart!=pos->dimensions[0])
{
PyErr_SetString(PyExc_ValueError,"Numpart != pos->dimensions[0].");
return NULL;
}
MPI_Allreduce(&NumPart, &All.TotNumPart, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&N_gas, &All.TotN_gas, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
All.MaxPart = All.PartAllocFactor * (All.TotNumPart / NTask);
All.MaxPartSph = All.PartAllocFactor * (All.TotN_gas / NTask);
/*********************/
/* allocate P */
/*********************/
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);
}
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);
}
/*********************/
/* init P */
/*********************/
float * fpt;
for (i = 0; i < NumPart; i++)
{
//P[i].Pos[0] = *(float *) (pos->data + i*(pos->strides[0]) + 0*pos->strides[1]);
//P[i].Pos[1] = *(float *) (pos->data + i*(pos->strides[0]) + 1*pos->strides[1]);
//P[i].Pos[2] = *(float *) (pos->data + i*(pos->strides[0]) + 2*pos->strides[1]);
//&P[i].Pos[0] = (float *) (pos->data + i*(pos->strides[0]) + 0*pos->strides[1]);
//&P[i].Pos[1] = (float *) (pos->data + i*(pos->strides[0]) + 1*pos->strides[1]);
//&P[i].Pos[2] = (float *) (pos->data + i*(pos->strides[0]) + 2*pos->strides[1]);
fpt = (float *) (pos->data + i*(pos->strides[0]) + 0*pos->strides[1]);
P[i].Vel[0] = *(float *) (vel->data + i*(vel->strides[0]) + 0*vel->strides[1]);
P[i].Vel[1] = *(float *) (vel->data + i*(vel->strides[0]) + 1*vel->strides[1]);
P[i].Vel[2] = *(float *) (vel->data + i*(vel->strides[0]) + 2*vel->strides[1]);
P[i].Mass = *(float *) (mass->data + i*(mass->strides[0]));
P[i].ID = *(unsigned int *) (num->data + i*(num->strides[0]));
P[i].Type = *(int *) (tpe->data + i*(tpe->strides[0]));
//P[i].Active = 1;
}
/***************************************
* END LOAD PARTILES *
/***************************************/
/***************************************
* finish inits *
/***************************************/
Begrun2();
return Py_BuildValue("i",1);
}
#ifdef TESSEL
static PyObject *gadget_ConstructDelaunay(PyObject *self, PyObject *args, PyObject *kwds)
{
ConstructDelaunay();
return Py_BuildValue("i",1);
}
static PyObject *gadget_ComputeVoronoi(PyObject *self, PyObject *args, PyObject *kwds)
{
ComputeVoronoi();
return Py_BuildValue("i",1);
}
#endif /*TESSEL*/
/* definition of the method table */
static PyMethodDef gadgetMethods[] = {
{"Info", (PyCFunction)gadget_Info, METH_VARARGS,
"give some info"},
{"InitMPI", (PyCFunction)gadget_InitMPI, METH_VARARGS,
"Init MPI"},
{"InitDefaultParameters", (PyCFunction)gadget_InitDefaultParameters, METH_VARARGS,
"Init default parameters"},
{"GetParameters", (PyCFunction)gadget_GetParameters, METH_VARARGS,
"get gadget parameters"},
{"SetParameters", (PyCFunction)gadget_SetParameters, METH_VARARGS,
"Set gadget parameters"},
{"check_parser", (PyCFunction)gadget_check_parser, METH_VARARGS|METH_KEYWORDS,
"check the parser"},
{"LoadParticles", (PyCFunction)gadget_LoadParticles, METH_VARARGS|METH_KEYWORDS,
"LoadParticles partilces"},
{"LoadParticlesQ", (PyCFunction)gadget_LoadParticlesQ, METH_VARARGS,
"LoadParticles partilces Q"},
{"LoadParticles2", (PyCFunction)gadget_LoadParticles2, METH_VARARGS,
"LoadParticles partilces"},
{"AllPotential", (PyCFunction)gadget_AllPotential, METH_VARARGS,
"Computes the potential for each particle"},
{"AllAcceleration", (PyCFunction)gadget_AllAcceleration, METH_VARARGS,
"Computes the gravitational acceleration for each particle"},
{"GetAllAcceleration", (PyCFunction)gadget_GetAllAcceleration, METH_VARARGS,
"get the gravitational acceleration for each particle"},
{"GetAllPotential", (PyCFunction)gadget_GetAllPotential, METH_VARARGS,
"get the potential for each particle"},
{"GetAllDensities", (PyCFunction)gadget_GetAllDensities, METH_VARARGS,
"get the densities for each particle"},
{"GetAllHsml", (PyCFunction)gadget_GetAllHsml, METH_VARARGS,
"get the sph smoothing length for each particle"},
{"GetAllPositions", (PyCFunction)gadget_GetAllPositions, METH_VARARGS,
"get the position for each particle"},
{"GetAllVelocities", (PyCFunction)gadget_GetAllVelocities, METH_VARARGS,
"get the velocities for each particle"},
{"GetAllMasses", (PyCFunction)gadget_GetAllMasses, METH_VARARGS,
"get the mass for each particle"},
{"GetAllEnergySpec", (PyCFunction)gadget_GetAllEnergySpec, METH_VARARGS,
"get the specific energy for each particle"},
{"GetAllEntropy", (PyCFunction)gadget_GetAllEntropy, METH_VARARGS,
"get the entropy for each particle"},
{"GetAllID", (PyCFunction)gadget_GetAllID, METH_VARARGS,
"get the ID for each particle"},
{"GetAllTypes", (PyCFunction)gadget_GetAllTypes, METH_VARARGS,
"get the type for each particle"},
{"GetPos", (PyCFunction)gadget_GetPos, METH_VARARGS,
"get the position for each particle (no memory overhead)"},
{"Potential", (PyCFunction)gadget_Potential, METH_VARARGS,
"get the potential for a givent sample of points"},
{"Acceleration", (PyCFunction)gadget_Acceleration, METH_VARARGS,
"get the acceleration for a givent sample of points"},
{"SphEvaluateOrigAll", (PyCFunction)gadget_SphEvaluateOrigAll, METH_VARARGS,
"run the original sph routine."},
{"SphEvaluateAll", (PyCFunction)gadget_SphEvaluateAll, METH_VARARGS,
"compute mean value of a given field based on the sph convolution for all points."},
{"SphEvaluateGradientAll", (PyCFunction)gadget_SphEvaluateGradientAll, METH_VARARGS,
"compute the gradient of a given field based on the sph convolution for all points."},
{"DensityEvaluateAll", (PyCFunction)gadget_DensityEvaluateAll, METH_VARARGS,
"simply run the density function"},
{"DensityEvaluateGradientAll", (PyCFunction)gadget_DensityEvaluateGradientAll, METH_VARARGS,
"run the modified density function and compute a gradient from the given value"},
{"EvaluateThermalConductivity", (PyCFunction)gadget_EvaluateThermalConductivity, METH_VARARGS,
"evaluate the thermal coductivity for each particle"},
{"SphEvaluate", (PyCFunction)gadget_SphEvaluate, METH_VARARGS,
"compute mean value based on the sph convolution for a given number of points"},
{"InitHsml", (PyCFunction)gadget_InitHsml, METH_VARARGS,
"Init hsml based on the three for a given number of points"},
{"Density", (PyCFunction)gadget_Density, METH_VARARGS,
"compute Density based on the three for a given number of points"},
{"Ngbs", (PyCFunction)gadget_Ngbs, METH_VARARGS,
"return the position of the neighbors for a given point"},
{"GetAllPositionsQ", (PyCFunction)gadget_GetAllPositionsQ, METH_VARARGS,
"get the position for each particle Q"},
{"GetAllVelocitiesQ", (PyCFunction)gadget_GetAllVelocitiesQ, METH_VARARGS,
"get the velocities for each particle Q"},
{"GetAllMassesQ", (PyCFunction)gadget_GetAllMassesQ, METH_VARARGS,
"get the mass for each particle Q"},
{"GetAllIDQ", (PyCFunction)gadget_GetAllIDQ, METH_VARARGS,
"get the ID for each particle Q"},
{"GetAllTypesQ", (PyCFunction)gadget_GetAllTypesQ, METH_VARARGS,
"get the type for each particle Q"},
{"Free", (PyCFunction)gadget_Free, METH_VARARGS,
"release memory"},
#ifdef TESSEL
{"ConstructDelaunay", (PyCFunction)gadget_ConstructDelaunay, METH_VARARGS,
"Construct the Delaunay tesselation"},
{"ComputeVoronoi", (PyCFunction)gadget_ComputeVoronoi, METH_VARARGS,
"Compute the Voronoi tesselation"},
{"GetAllDelaunayTriangles", (PyCFunction)gadget_GetAllDelaunayTriangles, METH_VARARGS,
"Get all the Delaunay Triangles"},
{"GetAllvPoints", gadget_GetAllvPoints, METH_VARARGS,
"Get voronoi points"},
{"GetAllvDensities", gadget_GetAllvDensities, METH_VARARGS,
"Get voronoi density of all points"},
{"GetAllvVolumes", gadget_GetAllvVolumes, METH_VARARGS,
"Get voronoi volumes of all points"},
{"GetvPointsForOnePoint", gadget_GetvPointsForOnePoint, METH_VARARGS,
"Get voronoi points for a given point"},
{"GetAllGhostPositions", gadget_GetAllGhostPositions, METH_VARARGS,
- "Get all positions of the ghosts points"},
+ "Get all positions of the ghosts points"},
+
+ {"GetAllGhostvDensities", gadget_GetAllGhostvDensities, METH_VARARGS,
+ "Get all densities of the ghosts points"},
+
+ {"GetAllGhostvVolumes", gadget_GetAllGhostvVolumes, METH_VARARGS,
+ "Get all volumes of the ghosts points"},
#endif
{NULL, NULL, 0, NULL} /* Sentinel */
};
void initgadget(void)
{
(void) Py_InitModule("gadget", gadgetMethods);
import_array();
}
#endif /*PY_INTERFACE*/
diff --git a/src/tessel.c b/src/tessel.c
index 2020a36..5794638 100644
--- a/src/tessel.c
+++ b/src/tessel.c
@@ -1,1783 +1,1833 @@
#ifdef TESSEL
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <allvars.h>
struct Face /* a list of edges (only for 3d tesselation) */
{
};
struct Triangle
{
struct particle_data Pt1[3];
struct particle_data Pt2[3];
struct particle_data Pt3[3];
};
struct TriangleInList
{
int idx; /* index of current triangle (used for checks) */
struct particle_data* P[3]; /* pointers towards the 3 point */
struct TriangleInList* T[3]; /* pointers towards the 3 triangles */
int idxe[3]; /* index of point in the first triangle, opposite to the common edge */
struct Median* Med[3]; /* pointers towards 3 medians */
};
struct Median
{
double a; /* params for the equation of the segemnt */
double b; /* params for the equation of the segemnt */
double c; /* params for the equation of the segemnt */
struct vPoint *vPs; /* pointer towards starting vPoint of the segment */
struct vPoint *vPe; /* pointer towards stoping vPoint of the segment */
struct particle_data *Pa; /* pointer towards point A*/
struct particle_data *Pb; /* pointer towards point B*/
};
/* a voronoi point */
struct vPoint
{
double Pos[3];
int next;
};
/*
LOCAL VARIABLES
*/
#define MAXNUMTRIANGLES 1000000
int nT=0,numTinStack=0; /* number of triangles in the list */
struct TriangleInList Triangles[MAXNUMTRIANGLES]; /* list of triangles */
struct TriangleInList *TStack[MAXNUMTRIANGLES]; /* index of triangles to check */
struct Median MediansList[3*MAXNUMTRIANGLES][3];
int nvPoints=0; /* number of Voronoi Points */
int nMedians=0; /* number of Medians */
struct vPoint vPoints[5*MAXNUMTRIANGLES];
struct Median Medians[5*MAXNUMTRIANGLES];
double tesselDomainRadius,tesselDomainCenter[3];
struct particle_data Pe[3]; /* edges */
void setup_searching_radius()
{
int i;
for(i=0;i<NumPart;i++)
- P[i].rSearch=0.1;
+ P[i].rSearch=0.3;
}
void lines_intersections(double a0, double b0, double c0, double a1, double b1, double c1, double *x, double *y)
{
*x = (c1*b0 - c0*b1)/(a0*b1 - a1*b0);
*y = (c1*a0 - c0*a1)/(a1*b0 - a0*b1);
}
/*!
*/
struct Triangle TriangleInList2Triangle(struct TriangleInList Tl)
{
struct Triangle T;
T.Pt1->Pos[0] = Tl.P[0]->Pos[0];
T.Pt1->Pos[1] = Tl.P[0]->Pos[1];
T.Pt2->Pos[0] = Tl.P[1]->Pos[0];
T.Pt2->Pos[1] = Tl.P[1]->Pos[1];
T.Pt3->Pos[0] = Tl.P[2]->Pos[0];
T.Pt3->Pos[1] = Tl.P[2]->Pos[1];
return T;
}
/*! For a set of three points, construct a triangle
*/
struct Triangle MakeTriangleFromPoints(struct particle_data Pt1,struct particle_data Pt2,struct particle_data Pt3)
{
struct Triangle T;
T.Pt1->Pos[0] = Pt1.Pos[0];
T.Pt1->Pos[1] = Pt1.Pos[1];
T.Pt2->Pos[0] = Pt2.Pos[0];
T.Pt2->Pos[1] = Pt2.Pos[1];
T.Pt3->Pos[0] = Pt3.Pos[0];
T.Pt3->Pos[1] = Pt3.Pos[1];
return T;
}
/*! For a set of three points, this function computes the 3 medians.
*/
void TriangleMedians(struct particle_data Pt1,struct particle_data Pt2,struct particle_data Pt3,struct particle_data *Pmm1,struct particle_data *Pmm2,struct particle_data *Pmm3,struct particle_data *Pme1,struct particle_data *Pme2,struct particle_data *Pme3)
{
double ma1,mb1,mc1;
double ma2,mb2,mc2;
double ma3,mb3,mc3;
/* median 0-1 */
ma1 = 2*(Pt2.Pos[0] - Pt1.Pos[0]);
mb1 = 2*(Pt2.Pos[1] - Pt1.Pos[1]);
mc1 = (Pt1.Pos[0]*Pt1.Pos[0]) - (Pt2.Pos[0]*Pt2.Pos[0]) + (Pt1.Pos[1]*Pt1.Pos[1]) - (Pt2.Pos[1]*Pt2.Pos[1]);
/* median 1-2 */
ma2 = 2*(Pt3.Pos[0] - Pt2.Pos[0]);
mb2 = 2*(Pt3.Pos[1] - Pt2.Pos[1]);
mc2 = (Pt2.Pos[0]*Pt2.Pos[0]) - (Pt3.Pos[0]*Pt3.Pos[0]) + (Pt2.Pos[1]*Pt2.Pos[1]) - (Pt3.Pos[1]*Pt3.Pos[1]);
/* median 2-0 */
ma3 = 2*(Pt1.Pos[0] - Pt3.Pos[0]);
mb3 = 2*(Pt1.Pos[1] - Pt3.Pos[1]);
mc3 = (Pt3.Pos[0]*Pt3.Pos[0]) - (Pt1.Pos[0]*Pt1.Pos[0]) + (Pt3.Pos[1]*Pt3.Pos[1]) - (Pt1.Pos[1]*Pt1.Pos[1]);
/* intersection m0-1 -- m1-2 */
Pmm1->Pos[0] = (mc2*mb1 - mc1*mb2)/(ma1*mb2 - ma2*mb1);
Pmm1->Pos[1] = (mc2*ma1 - mc1*ma2)/(ma2*mb1 - ma1*mb2);
/* intersection m1-2 -- m2-0 */
Pmm2->Pos[0] = (mc2*mb1 - mc1*mb2)/(ma1*mb2 - ma2*mb1);
Pmm2->Pos[1] = (mc2*ma1 - mc1*ma2)/(ma2*mb1 - ma1*mb2);
/* intersection m2-0 -- m0-1 */
Pmm3->Pos[0] = (mc2*mb1 - mc1*mb2)/(ma1*mb2 - ma2*mb1);
Pmm3->Pos[1] = (mc2*ma1 - mc1*ma2)/(ma2*mb1 - ma1*mb2);
/* intersection m1-2 -- e1-2 */
Pme1->Pos[0] = 0.5*(Pt1.Pos[0] + Pt2.Pos[0]);
Pme1->Pos[1] = 0.5*(Pt1.Pos[1] + Pt2.Pos[1]);
/* intersection m2-3 -- e3-1 */
Pme2->Pos[0] = 0.5*(Pt2.Pos[0] + Pt3.Pos[0]);
Pme2->Pos[1] = 0.5*(Pt2.Pos[1] + Pt3.Pos[1]);
/* intersection m3-1 -- e1-2 */
Pme3->Pos[0] = 0.5*(Pt3.Pos[0] + Pt1.Pos[0]);
Pme3->Pos[1] = 0.5*(Pt3.Pos[1] + Pt1.Pos[1]);
}
/*! For a set of three points, this function computes their cirum-circle.
* Its radius is return, while the center is return using pointers.
*/
double CircumCircleProperties(struct particle_data Pt1,struct particle_data Pt2,struct particle_data Pt3, double *xc, double *yc)
{
double r;
double x21,x32,y21,y32;
double x12mx22,y12my22,x22mx32,y22my32;
double c1,c2;
x21 = Pt2.Pos[0]-Pt1.Pos[0];
x32 = Pt3.Pos[0]-Pt2.Pos[0];
y21 = Pt2.Pos[1]-Pt1.Pos[1];
y32 = Pt3.Pos[1]-Pt2.Pos[1];
x12mx22 = (Pt1.Pos[0]*Pt1.Pos[0])-(Pt2.Pos[0]*Pt2.Pos[0]);
y12my22 = (Pt1.Pos[1]*Pt1.Pos[1])-(Pt2.Pos[1]*Pt2.Pos[1]);
x22mx32 = (Pt2.Pos[0]*Pt2.Pos[0])-(Pt3.Pos[0]*Pt3.Pos[0]);
y22my32 = (Pt2.Pos[1]*Pt2.Pos[1])-(Pt3.Pos[1]*Pt3.Pos[1]);
c1 = x12mx22 + y12my22;
c2 = x22mx32 + y22my32;
*xc = (y32*c1 - y21*c2)/2.0/( x32*y21 - x21*y32 );
*yc = (x32*c1 - x21*c2)/2.0/( x21*y32 - x32*y21 );
r = sqrt( (Pt1.Pos[0]-*xc)*(Pt1.Pos[0]-*xc) + (Pt1.Pos[1]-*yc)*(Pt1.Pos[1]-*yc) ) ;
return r;
}
/*! For a given triangle T, the routine tells if the point P4
is in the circum circle of the triangle or not.
*/
int InCircumCircle(struct Triangle T,struct particle_data Pt4)
{
double a,b,c;
double d,e,f;
double g,h,i;
double det;
/*
a = T.Pt1->Pos[0] - Pt4.Pos[0];
b = T.Pt1->Pos[1] - Pt4.Pos[1];
c = (T.Pt1->Pos[0]*T.Pt1->Pos[0] - Pt4.Pos[0]*Pt4.Pos[0]) + (T.Pt1->Pos[1]*T.Pt1->Pos[1] - Pt4.Pos[1]*Pt4.Pos[1]);
d = T.Pt2->Pos[0] - Pt4.Pos[0];
e = T.Pt2->Pos[1] - Pt4.Pos[1];
f = (T.Pt2->Pos[0]*T.Pt2->Pos[0] - Pt4.Pos[0]*Pt4.Pos[0]) + (T.Pt2->Pos[1]*T.Pt2->Pos[1] - Pt4.Pos[1]*Pt4.Pos[1]);
g = T.Pt3->Pos[0] - Pt4.Pos[0];
h = T.Pt3->Pos[1] - Pt4.Pos[1];
i = (T.Pt3->Pos[0]*T.Pt3->Pos[0] - Pt4.Pos[0]*Pt4.Pos[0]) + (T.Pt3->Pos[1]*T.Pt3->Pos[1] - Pt4.Pos[1]*Pt4.Pos[1]);
*/
/*
Volker Formula
*/
a = T.Pt2->Pos[0] - T.Pt1->Pos[0];
b = T.Pt2->Pos[1] - T.Pt1->Pos[1];
c = a*a + b*b;
d = T.Pt3->Pos[0] - T.Pt1->Pos[0];
e = T.Pt3->Pos[1] - T.Pt1->Pos[1];
f = d*d + e*e;
g = Pt4.Pos[0] - T.Pt1->Pos[0];
h = Pt4.Pos[1] - T.Pt1->Pos[1];
i = g*g + h*h;
det = a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
if (det<0)
return 1; /* inside */
else
return 0; /* outside */
}
/*! For a given triangle T, the routine tells if the point P4
lie inside the triangle or not.
*/
int InTriangle(struct Triangle T,struct particle_data Pt4)
{
double c1,c2,c3;
/* here, we use the cross product */
c1 = (T.Pt2->Pos[0]-T.Pt1->Pos[0])*(Pt4.Pos[1]-T.Pt1->Pos[1]) - (T.Pt2->Pos[1]-T.Pt1->Pos[1])*(Pt4.Pos[0]-T.Pt1->Pos[0]);
c2 = (T.Pt3->Pos[0]-T.Pt2->Pos[0])*(Pt4.Pos[1]-T.Pt2->Pos[1]) - (T.Pt3->Pos[1]-T.Pt2->Pos[1])*(Pt4.Pos[0]-T.Pt2->Pos[0]);
c3 = (T.Pt1->Pos[0]-T.Pt3->Pos[0])*(Pt4.Pos[1]-T.Pt3->Pos[1]) - (T.Pt1->Pos[1]-T.Pt3->Pos[1])*(Pt4.Pos[0]-T.Pt3->Pos[0]);
if ( (c1>0) && (c2>0) && (c3>0) ) /* inside */
return 1;
else
return 0;
}
int InTriangleOrOutside(struct Triangle T,struct particle_data Pt4)
{
double c1,c2,c3;
c1 = (T.Pt2->Pos[0]-T.Pt1->Pos[0])*(Pt4.Pos[1]-T.Pt1->Pos[1]) - (T.Pt2->Pos[1]-T.Pt1->Pos[1])*(Pt4.Pos[0]-T.Pt1->Pos[0]);
if (c1<0)
return 2; /* to triangle T[2] */
c2 = (T.Pt3->Pos[0]-T.Pt2->Pos[0])*(Pt4.Pos[1]-T.Pt2->Pos[1]) - (T.Pt3->Pos[1]-T.Pt2->Pos[1])*(Pt4.Pos[0]-T.Pt2->Pos[0]);
if (c2<0)
return 0; /* to triangle T[1] */
c3 = (T.Pt1->Pos[0]-T.Pt3->Pos[0])*(Pt4.Pos[1]-T.Pt3->Pos[1]) - (T.Pt1->Pos[1]-T.Pt3->Pos[1])*(Pt4.Pos[0]-T.Pt3->Pos[0]);
if (c3<0)
return 1; /* to triangle T[0] */
return -1; /* the point is inside */
}
/*! For a given triangle, orient it positively.
*/
struct Triangle OrientTriangle(struct Triangle T)
{
double a,b,c,d;
double det;
struct particle_data Ptsto;
a = T.Pt2->Pos[0] - T.Pt1->Pos[0];
b = T.Pt2->Pos[1] - T.Pt1->Pos[1];
c = T.Pt3->Pos[0] - T.Pt1->Pos[0];
d = T.Pt3->Pos[1] - T.Pt1->Pos[1];
det = (a*d) - (b*c);
if (det<0)
{
Ptsto.Pos[0] = T.Pt1->Pos[0];
Ptsto.Pos[1] = T.Pt1->Pos[1];
T.Pt1->Pos[0] = T.Pt3->Pos[0];
T.Pt1->Pos[1] = T.Pt3->Pos[1];
T.Pt3->Pos[0] = Ptsto.Pos[0];
T.Pt3->Pos[1] = Ptsto.Pos[1];
T = OrientTriangle(T);
}
return T;
}
/*! For a given triangle, orient it positively.
*/
struct TriangleInList OrientTriangleInList(struct TriangleInList T)
{
double a,b,c,d;
double det;
struct particle_data Ptsto;
a = T.P[1]->Pos[0] - T.P[0]->Pos[0];
b = T.P[1]->Pos[1] - T.P[0]->Pos[1];
c = T.P[2]->Pos[0] - T.P[0]->Pos[0];
d = T.P[2]->Pos[1] - T.P[0]->Pos[1];
det = (a*d) - (b*c);
if (det<0)
{
Ptsto.Pos[0] = T.P[0]->Pos[0];
Ptsto.Pos[1] = T.P[0]->Pos[1];
T.P[0]->Pos[0] = T.P[2]->Pos[0];
T.P[0]->Pos[1] = T.P[2]->Pos[1];
T.P[2]->Pos[0] = Ptsto.Pos[0];
T.P[2]->Pos[1] = Ptsto.Pos[1];
T = OrientTriangleInList(T);
}
return T;
}
/*! This function computes the extension of the domain.
* It computes:
* len : max-min
* tesselDomainCenter : min + 0.5*len
* tesselDomainRadius = len*1.5;
*/
void FindTesselExtent()
{
int i,j;
double xmin[3], xmax[3],len;
/* determine local extension */
for(j = 0; j < 3; j++)
{
xmin[j] = MAX_REAL_NUMBER;
xmax[j] = -MAX_REAL_NUMBER;
}
for(i = 0; i < NumPart; i++)
{
for(j = 0; j < 3; j++)
{
if(xmin[j] > P[i].Pos[j])
xmin[j] = P[i].Pos[j];
if(xmax[j] < P[i].Pos[j])
xmax[j] = P[i].Pos[j];
}
}
len = 0;
for(j = 0; j < 3; j++)
{
if(xmax[j] - xmin[j] > len)
len = xmax[j] - xmin[j];
}
for(j = 0; j < 3; j++)
tesselDomainCenter[j] = xmin[j] + len/2.;
tesselDomainRadius = len*2;
printf("tesselDomainRadius = %g\n",tesselDomainRadius);
printf("tesselDomainCenter = (%g %g)\n",tesselDomainCenter[0],tesselDomainCenter[1]);
}
int FindSegmentInTriangle(struct TriangleInList *T,double v,struct particle_data P[3])
{
double v0,v1,v2;
double x0,x1,x2;
double y0,y1,y2;
double f;
double x,y;
int iP;
/* if the triangle as an edge point, do nothing */
if ( (T->P[0]==&Pe[0]) || (T->P[1]==&Pe[0]) || (T->P[2]==&Pe[0]) )
return 0;
/* if the triangle as an edge point, do nothing */
if ( (T->P[0]==&Pe[1]) || (T->P[1]==&Pe[1]) || (T->P[2]==&Pe[1]) )
return 0;
/* if the triangle as an edge point, do nothing */
if ( (T->P[0]==&Pe[2]) || (T->P[1]==&Pe[2]) || (T->P[2]==&Pe[2]) )
return 0;
iP = 0;
v0 = T->P[0]->Mass;
v1 = T->P[1]->Mass;
v2 = T->P[2]->Mass;
//printf("Triangle %d : %g %g %g\n",T->idx,v0,v1,v2);
/* we could also use the sign v-v0 * v-v1 ??? */
if (( ((v>v0)&&(v<v1)) || ((v>v1)&&(v<v0)) )&& (v0 != v1)) /* in 0-1 */
{
x0 = T->P[0]->Pos[0];
y0 = T->P[0]->Pos[1];
x1 = T->P[1]->Pos[0];
y1 = T->P[1]->Pos[1];
f = (v-v0)/(v1-v0);
P[iP].Pos[0] = f*(x1-x0) + x0;
P[iP].Pos[1] = f*(y1-y0) + y0;
iP++;
}
if (( ((v>v1)&&(v<v2)) || ((v>v2)&&(v<v1)) )&& (v1 != v2)) /* in 1-2 */
{
x0 = T->P[1]->Pos[0];
y0 = T->P[1]->Pos[1];
x1 = T->P[2]->Pos[0];
y1 = T->P[2]->Pos[1];
f = (v-v1)/(v2-v1);
P[iP].Pos[0] = f*(x1-x0) + x0;
P[iP].Pos[1] = f*(y1-y0) + y0;
iP++;
}
if (( ((v>v2)&&(v<v0)) || ((v>v0)&&(v<v2)) )&& (v2 != v0)) /* in 2-0 */
{
x0 = T->P[2]->Pos[0];
y0 = T->P[2]->Pos[1];
x1 = T->P[0]->Pos[0];
y1 = T->P[0]->Pos[1];
f = (v-v2)/(v0-v2);
P[iP].Pos[0] = f*(x1-x0) + x0;
P[iP].Pos[1] = f*(y1-y0) + y0;
iP++;
}
return iP;
}
void CheckTriangles(void)
{
int iT;
struct TriangleInList *T,*Te;
for (iT=0;iT<nT;iT++)
{
T = &Triangles[iT];
Te = T->T[0];
if (Te!=NULL)
{
if ((Te->T[0]!=NULL)&&(Te->T[0] == T))
{
}
else
if ((Te->T[1]!=NULL)&&(Te->T[1] == T))
{
}
else
if ((Te->T[2]!=NULL)&&(Te->T[2] == T))
{
}
else
{
printf("Triangle %d does not point towards %d, while T->T2=%d\n",Te->idx,T->idx,T->T[0]->idx);
exit(-1);
}
}
Te = T->T[1];
if (Te!=NULL)
{
if ((Te->T[0]!=NULL)&&(Te->T[0] == T))
{
}
else
if ((Te->T[1]!=NULL)&&(Te->T[1] == T))
{
}
else
if ((Te->T[2]!=NULL)&&(Te->T[2] == T))
{
}
else
{
printf("Triangle %d does not point towards %d, while T->T2=%d\n",Te->idx,T->idx,T->T[1]->idx);
exit(-1);
}
}
Te = T->T[2];
if (Te!=NULL)
{
if ((Te->T[0]!=NULL)&&(Te->T[0] == T))
{
}
else
if ((Te->T[1]!=NULL)&&(Te->T[1] == T))
{
}
else
if ((Te->T[2]!=NULL)&&(Te->T[2] == T))
{
}
else
{
printf("Triangle %d does not point towards %d, while T->T2=%d\n",Te->idx,T->idx,T->T[2]->idx);
exit(-1);
}
}
}
}
/*! Flip two triangles.
Te = T.T[i]
*/
void FlipTriangle(int i,struct TriangleInList *T,struct TriangleInList *Te,struct TriangleInList *T1,struct TriangleInList *T2)
{
struct TriangleInList Ts1,Ts2;
int i0,i1,i2;
int j0,j1,j2;
int j;
Ts1 = *T; /* save the content of the pointed triangle */
Ts2 = *Te; /* save the content of the pointed triangle */
j = T->idxe[i]; /* index of point opposite to i */
i0= i;
i1= (i+1) % 3;
i2= (i+2) % 3;
j0= j;
j1= (j+1) % 3;
j2= (j+2) % 3;
/* triangle 1 */
T1->P[0] = Ts1.P[i0];
T1->P[1] = Ts1.P[i1];
T1->P[2] = Ts2.P[j0];
T1->T[0] = Ts2.T[j1];
T1->T[1] = T2;
T1->T[2] = Ts1.T[i2];
T1->idxe[0] = Ts2.idxe[j1];
T1->idxe[1] = 1;
T1->idxe[2] = Ts1.idxe[i2];
/* triangle 2 */
T2->P[0] = Ts2.P[j0];
T2->P[1] = Ts2.P[j1];
T2->P[2] = Ts1.P[i0];
T2->T[0] = Ts1.T[i1];
T2->T[1] = T1;
T2->T[2] = Ts2.T[j2];
T2->idxe[0] = Ts1.idxe[i1];
T2->idxe[1] = 1;
T2->idxe[2] = Ts2.idxe[j2];
/* restore links with adjacents triangles */
if (Ts1.T[i1]!=NULL)
{
Ts1.T[i1]->T[ Ts1.idxe[i1] ] = T2;
Ts1.T[i1]->idxe[ Ts1.idxe[i1] ] = 0;
}
if (Ts1.T[i2] !=NULL)
{
Ts1.T[i2]->T[ Ts1.idxe[i2] ] = T1;
Ts1.T[i2]->idxe[ Ts1.idxe[i2] ] = 2;
}
if (Ts2.T[j1] !=NULL)
{
Ts2.T[j1]->T[ Ts2.idxe[j1] ] = T1;
Ts2.T[j1]->idxe[ Ts2.idxe[j1] ] = 0;
}
if (Ts2.T[j2] !=NULL)
{
Ts2.T[j2]->T[ Ts2.idxe[j2] ] = T2;
Ts2.T[j2]->idxe[ Ts2.idxe[j2] ] = 2;
}
}
void DoTrianglesInStack(void)
{
struct TriangleInList *T,*Te,*T1,*T2,*Tee;
struct TriangleInList Ts1,Ts2;
struct particle_data P;
int istack;
int idx1,idx2;
int i;
istack=0;
while(numTinStack>0)
{
int insphere=0;
T = TStack[istack];
//printf(" DoInStack T=%d (istack=%d, numTinStack=%d)\n",T->idx,istack,numTinStack);
/* find the opposite point of the 3 adjacent triangles */
/*******************/
/* triangle 1 */
/*******************/
i = 0;
Te = T->T[i];
if (Te!=NULL)
{
/* index of opposite point */
P = *Te->P[T->idxe[i]];
insphere = InCircumCircle(TriangleInList2Triangle(*T),P);
if (insphere)
{
//printf("insphere (1)... %g %g %g in T=%d\n",P.Pos[0],P.Pos[1],P.Pos[2],T->idx);
/* index of the new triangles */
idx1 = T->idx;
idx2 = Te->idx;
T1 = &Triangles[idx1];
T2 = &Triangles[idx2];
FlipTriangle(i,T,Te,T1,T2);
/* add triangles in stack */
if (numTinStack+1>MAXNUMTRIANGLES)
{
printf("\nNo more memory !\n");
printf("numTinStack+1=%d > MAXNUMTRIANGLES=%d\n",numTinStack+1,MAXNUMTRIANGLES);
printf("You should increase MAXNUMTRIANGLES\n\n");
exit(-1);
}
TStack[istack ] = T1;
TStack[istack+numTinStack] = T2;
numTinStack++;
continue;
}
}
/*******************/
/* triangle 2 */
/*******************/
i = 1;
Te = T->T[i];
if (Te!=NULL)
{
/* index of opposite point */
P = *Te->P[T->idxe[i]];
insphere = InCircumCircle(TriangleInList2Triangle(*T),P);
if (insphere)
{
//printf("insphere (2)... %g %g %g in T=%d\n",P.Pos[0],P.Pos[1],P.Pos[2],T->idx);
/* index of the new triangles */
idx1 = T->idx;
idx2 = Te->idx;
T1 = &Triangles[idx1];
T2 = &Triangles[idx2];
FlipTriangle(i,T,Te,T1,T2);
/* add triangles in stack */
if (numTinStack+1>MAXNUMTRIANGLES)
{
printf("\nNo more memory !\n");
printf("numTinStack+1=%d > MAXNUMTRIANGLES=%d\n",numTinStack+1,MAXNUMTRIANGLES);
printf("You should increase MAXNUMTRIANGLES\n\n");
exit(-1);
}
TStack[istack ] = T1;
TStack[istack+numTinStack] = T2;
numTinStack++;
continue;
}
}
/*******************/
/* triangle 3 */
/*******************/
i = 2;
Te = T->T[i];
if (Te!=NULL)
{
/* index of opposite point */
P = *Te->P[T->idxe[i]];
insphere = InCircumCircle(TriangleInList2Triangle(*T),P);
if (insphere)
{
//printf("insphere (3)... %g %g %g in T=%d\n",P.Pos[0],P.Pos[1],P.Pos[2],T->idx);
/* index of the new triangles */
idx1 = T->idx;
idx2 = Te->idx;
T1 = &Triangles[idx1];
T2 = &Triangles[idx2];
FlipTriangle(i,T,Te,T1,T2);
/* add triangles in stack */
if (numTinStack+1>MAXNUMTRIANGLES)
{
printf("\nNo more memory !\n");
printf("numTinStack+1=%d > MAXNUMTRIANGLES=%d\n",numTinStack+1,MAXNUMTRIANGLES);
printf("You should increase MAXNUMTRIANGLES\n\n");
exit(-1);
}
TStack[istack ] = T1;
TStack[istack+numTinStack] = T2;
numTinStack++;
continue;
}
}
numTinStack--;
istack++;
//printf("one triangle less...(istack=%d numTinStack=%d)\n",istack,numTinStack);
}
}
void Check(void)
{
int iT;
printf("===========================\n");
for(iT=0;iT<nT;iT++)
{
printf("* T %d\n",Triangles[iT].idx);
printf("pt1 %g %g %g\n",Triangles[iT].P[0]->Pos[0],Triangles[iT].P[0]->Pos[1],Triangles[iT].P[0]->Pos[2]);
printf("pt2 %g %g %g\n",Triangles[iT].P[1]->Pos[0],Triangles[iT].P[1]->Pos[1],Triangles[iT].P[1]->Pos[2]);
printf("pt3 %g %g %g\n",Triangles[iT].P[2]->Pos[0],Triangles[iT].P[2]->Pos[1],Triangles[iT].P[2]->Pos[2]);
if (Triangles[iT].T[0]!=NULL)
printf("T1 %d\n",Triangles[iT].T[0]->idx);
else
printf("T1 x\n");
if (Triangles[iT].T[1]!=NULL)
printf("T2 %d\n",Triangles[iT].T[1]->idx);
else
printf("T2 x\n");
if (Triangles[iT].T[2]!=NULL)
printf("T3 %d\n",Triangles[iT].T[2]->idx);
else
printf("T3 x\n");
}
printf("===========================\n");
}
/*! Split a triangle in 3, using the point P inside it.
Update the global list.
*/
void SplitTriangle(struct TriangleInList *pT,struct particle_data *Pt)
{
struct TriangleInList T,*T0,*T1,*T2,*Te;
int idx,idx0,idx1,idx2;
T = *pT; /* save the content of the pointed triangle */
idx = T.idx;
/* index of the new triangles */
idx0 = idx;
idx1 = nT;
idx2 = nT+1;
/* increment counter */
nT=nT+2;
/* check memory */
if (nT>MAXNUMTRIANGLES)
{
printf("\nNo more memory !\n");
printf("nT=%d > MAXNUMTRIANGLES=%d\n",nT,MAXNUMTRIANGLES);
printf("You should increase MAXNUMTRIANGLES\n\n");
exit(-1);
}
/* create pointers towards the triangles */
T0 = &Triangles[idx0];
T1 = &Triangles[idx1];
T2 = &Triangles[idx2];
/* first */
T0->idx = idx0;
T0->P[0] = T.P[0];
T0->P[1] = T.P[1];
T0->P[2] = Pt;
/* second */
T1->idx = idx1;
T1->P[0] = T.P[1];
T1->P[1] = T.P[2];
T1->P[2] = Pt;
/* third */
T2->idx = idx2;
T2->P[0] = T.P[2];
T2->P[1] = T.P[0];
T2->P[2] = Pt;
/* add adjacents */
T0->T[0] = T1;
T0->T[1] = T2;
T0->T[2] = T.T[2];
T1->T[0] = T2;
T1->T[1] = T0;
T1->T[2] = T.T[0];
T2->T[0] = T0;
T2->T[1] = T1;
T2->T[2] = T.T[1];
/* add ext point */
T0->idxe[0] = 1;
T0->idxe[1] = 0;
T0->idxe[2] = T.idxe[2];
T1->idxe[0] = 1;
T1->idxe[1] = 0;
T1->idxe[2] = T.idxe[0];
T2->idxe[0] = 1;
T2->idxe[1] = 0;
T2->idxe[2] = T.idxe[1];
/* restore links with adgacents triangles */
Te = T0->T[2];
if (Te!=NULL)
{
Te->T[ T0->idxe[2]] = T0;
Te->idxe[T0->idxe[2]] = 2;
}
Te = T1->T[2];
if (Te!=NULL)
{
Te->T[ T1->idxe[2]] = T1;
Te->idxe[T1->idxe[2]] = 2;
}
Te = T2->T[2];
if (Te!=NULL)
{
Te->T[ T2->idxe[2]] = T2;
Te->idxe[T2->idxe[2]] = 2;
}
/* add the new triangles in the stack */
TStack[numTinStack] = T0;
numTinStack++;
TStack[numTinStack] = T1;
numTinStack++;
TStack[numTinStack] = T2;
numTinStack++;
//printf("--> add in stack %d %d %d\n",T0->idx,T1->idx,T2->idx);
}
int FindTriangle(struct particle_data *Pt)
{
int iT;
/* find triangle containing the point */
for(iT=0;iT<nT;iT++) /* loop over all triangles */
{
if (InTriangle(TriangleInList2Triangle( Triangles[iT] ),*Pt))
break;
}
return iT;
}
int NewFindTriangle(struct particle_data *Pt)
{
int iT;
struct TriangleInList *T;
int e;
iT = 0; /* star with first triangle */
T = &Triangles[iT];
while (1)
{
/* test position of the point relative to the triangle */
e = InTriangleOrOutside(TriangleInList2Triangle( *T ),*Pt);
//printf("T=%d e=%d Te=%d\n",T->idx,e,T->T[e]->idx);
if (e==-1) /* the point is inside */
break;
T = T->T[e];
if (T==NULL)
{
printf("point lie outside the limits.\n");
exit(-1);
}
}
//printf("done with find triangle (T=%d)\n",T->idx);
return T->idx;
}
/*! Add a new point in the tesselation
*/
void AddPoint(struct particle_data *Pt)
{
int iT;
/* find the triangle that contains the point P */
//iT= FindTriangle(Pt);
iT= NewFindTriangle(Pt);
/* create the new triangles */
SplitTriangle(&Triangles[iT],Pt);
/* test the new triangles and divide and modify if necessary */
DoTrianglesInStack();
/* check */
//CheckTriangles();
}
void AddGhostPoints()
{
int i;
if (ThisTask==0)
printf("%d new ghost points\n",NumgPart);
/* loop over all ghostpoints */
- for (i=NumPart;i<NumgPart+NumgPart;i++)
+ for (i=NumPart;i<NumPart+NumgPart;i++)
AddPoint(&P[i]);
}
/*! Add gost points to the tesselation
*/
void ExtendWithGhostPoints()
{
size_t bytes;
/* all particles try to find ngbs particles that lie in another proc */
if (ThisTask==0)
printf("ExtendWithGhostPoints...\n");
-
+
+ All.MaxgPart=All.MaxPart;
NumgPart=0;
-
+/* if(!(gP = malloc(bytes = All.MaxgPart * sizeof(struct ghost_particle_data))))
+ {
+ printf("failed to allocate memory for `gP' (%g MB).\n", bytes / (1024.0 * 1024.0));
+ endrun(1);
+ } */
+
ghost();
-
+/* free(gP);*/
if (ThisTask==0)
printf("ExtendWithGhostPoints done.\n");
}
/*! Compute all medians properties (a,b,c)
* For each triangle, for each edge, the function computes the
* median properties which is stored in MediansList
*/
void ComputeMediansProperties()
{
int iT;
/* loop over all triangles */
for(iT=0;iT<nT;iT++)
{
struct particle_data Pt0,Pt1,Pt2;
Pt0.Pos[0] = Triangles[iT].P[0]->Pos[0];
Pt0.Pos[1] = Triangles[iT].P[0]->Pos[1];
Pt1.Pos[0] = Triangles[iT].P[1]->Pos[0];
Pt1.Pos[1] = Triangles[iT].P[1]->Pos[1];
Pt2.Pos[0] = Triangles[iT].P[2]->Pos[0];
Pt2.Pos[1] = Triangles[iT].P[2]->Pos[1];
/* median 0-1 */
MediansList[iT][2].a = 2*(Pt1.Pos[0] - Pt0.Pos[0]);
MediansList[iT][2].b = 2*(Pt1.Pos[1] - Pt0.Pos[1]);
MediansList[iT][2].c = (Pt0.Pos[0]*Pt0.Pos[0]) - (Pt1.Pos[0]*Pt1.Pos[0]) + (Pt0.Pos[1]*Pt0.Pos[1]) - (Pt1.Pos[1]*Pt1.Pos[1]);
/* median 1-2 */
MediansList[iT][0].a = 2*(Pt2.Pos[0] - Pt1.Pos[0]);
MediansList[iT][0].b = 2*(Pt2.Pos[1] - Pt1.Pos[1]);
MediansList[iT][0].c = (Pt1.Pos[0]*Pt1.Pos[0]) - (Pt2.Pos[0]*Pt2.Pos[0]) + (Pt1.Pos[1]*Pt1.Pos[1]) - (Pt2.Pos[1]*Pt2.Pos[1]);
/* median 2-0 */
MediansList[iT][1].a = 2*(Pt0.Pos[0] - Pt2.Pos[0]);
MediansList[iT][1].b = 2*(Pt0.Pos[1] - Pt2.Pos[1]);
MediansList[iT][1].c = (Pt2.Pos[0]*Pt2.Pos[0]) - (Pt0.Pos[0]*Pt0.Pos[0]) + (Pt2.Pos[1]*Pt2.Pos[1]) - (Pt0.Pos[1]*Pt0.Pos[1]);
/* link The triangle with the MediansList */
Triangles[iT].Med[0] = &MediansList[iT][0]; /* median 1-2 */
Triangles[iT].Med[1] = &MediansList[iT][1]; /* median 2-0 */
Triangles[iT].Med[2] = &MediansList[iT][2]; /* median 0-1 */
}
}
/*! Compute the intersetions of medians around a point of index p (index of the point in the triangle T)
*
*/
void ComputeMediansAroundPoint(struct TriangleInList *Tstart,int iPstart)
{
/*
Tstart : pointer to first triangle
iPstart : index of master point relative to triangle Tstart
if p = 0:
T1 = T0->T[iTn]; pn=1
if p = 1:
T1 = T0->T[iTn]; pn=2
if p = 0:
T1 = T0->T[iTn]; pn=3
iTn = (p+1) % 3;
*/
double x,y;
struct TriangleInList *T0,*T1;
int iP0,iP1;
int iT1;
struct particle_data *initialPoint;
int iM0,iM1;
int next_vPoint=-1; /* index towards next voronoi point */
int next_Median=-1; /* index towards next median */
int number_of_vPoints=0;
int number_of_Medians=0;
int next;
T0 = Tstart;
iP0 = iPstart;
initialPoint = T0->P[iP0];
//printf("\n--> rotating around T=%d p=%d\n",T0->idx,iP0);
/* rotate around the point */
while (1)
{
/* next triangle */
iT1= (iP0+1) % 3;
T1 = T0->T[iT1];
if (T1==NULL)
{
//printf("reach an edge\n");
T0->P[iP0]->IsDone=2;
//printf("%g %g\n",T0->P[iP0]->Pos[0],T0->P[iP0]->Pos[1]);
return;
}
//printf(" next triangle = %d\n",T1->idx);
/* index of point in the triangle */
iP1 = T0->idxe[iT1]; /* index of point opposite to iTn */
iP1 = (iP1+1) % 3; /* next index of point opposite to iTn */
//printf(" initial point=%g %g current point =%g %g iP1=%d\n",initialPoint->Pos[0],initialPoint->Pos[1],T1->P[iP1]->Pos[0],T1->P[iP1]->Pos[1],iP1);
/* check */
if (initialPoint!=T1->P[iP1])
{
printf(" problem : initial point=%g %g current point =%g %g iP1=%d\n",initialPoint->Pos[0],initialPoint->Pos[1],T1->P[iP1]->Pos[0],T1->P[iP1]->Pos[1],iP1);
exit(-1);
}
/* compute the intersection of the two medians */
iM0 = (iP0+1) % 3;
iM1 = (iP1+1) % 3;
lines_intersections(T0->Med[iM0]->a,T0->Med[iM0]->b,T0->Med[iM0]->c,T1->Med[iM1]->a,T1->Med[iM1]->b,T1->Med[iM1]->c,&x,&y);
/* create a new vPoint and put it to the vPoints list */
vPoints[nvPoints].Pos[0] = x;
vPoints[nvPoints].Pos[1] = y;
vPoints[nvPoints].next = next_vPoint;
/* end point for T0 */
T0->Med[iM0]->vPe = &vPoints[nvPoints];
/* here, we could add the point to T0->Med[(iM0+2) % 3] as Ps */
/* start point for T0 */
T1->Med[iM1]->vPs = &vPoints[nvPoints];
/* here, we could add the point to T1->Med[(iM1+2) % 3] as Ps */
/* increment vPoints */
next_vPoint=nvPoints;
nvPoints++;
number_of_vPoints++;
if (T1==Tstart) /* end of loop */
{
//printf(" end of loop\n");
initialPoint->ivPoint = next_vPoint;
initialPoint->nvPoints = number_of_vPoints;
/* create the median list */
/* first vPoint */
// next = initialPoint->ivPoint;
//
// for (j = 0; j < initialPoint->nvPoints; j++)
// {
// Medians[nMedians].vPe = vPoints[prev];
// Medians[nMedians].vPs = vPoints[next];
// next = vPoints[next].next;
// }
break;
}
T0 = T1;
iP0 = iP1;
}
}
/*! Compute all medians intersections and define Ps and Pe
* For each triangle, compute the medians
*/
void ComputeMediansIntersections()
{
int i,p,iT;
- for (i=0;i<NumPart;i++)
+ for (i=0;i<NumPart+NumgPart;i++)
P[i].IsDone = 0;
/* loop over all triangles */
for(iT=0;iT<nT;iT++)
{
/* loop over points in triangle */
for(p=0;p<3;p++)
{
if (!(Triangles[iT].P[p]->IsDone))
{
//printf("in Triangle T %d do point %d\n",iT,p);
Triangles[iT].P[p]->IsDone = 1;
ComputeMediansAroundPoint(&Triangles[iT],p);
}
}
}
}
/*! Compute the density for all particles
*/
int ComputeDensity()
{
int i,j;
int next; /* next voronoi point */
int np;
double x0,y0,x1,y1;
double area;
- for(i=0;i<NumPart;i++)
+ for(i=0;i<NumPart+NumgPart;i++)
{
next = P[i].ivPoint;
np = P[i].nvPoints;
x0 = 0; /* this ensure the first loop to give 0 */
y0 = 0; /* this ensure the first loop to give 0 */
area = 0;
for (j = 0; j < np; j++)
{
x1 = vPoints[next].Pos[0];
y1 = vPoints[next].Pos[1];
area = area + (x0*y1 - x1*y0);
x0 = x1;
y0 = y1;
next = vPoints[next].next;
}
/* connect the last with the first */
next = P[i].ivPoint;
x1 = vPoints[next].Pos[0];
y1 = vPoints[next].Pos[1];
area = area + (x0*y1 - x1*y0);
/* */
area = 0.5*fabs(area);
P[i].Volume=area;
P[i].Density=P[i].Mass/area;
-
+
}
return 0;
}
/*! Construct the Delaunay tesselation
*/
int ConstructDelaunay()
{
int i,j;
if (ThisTask==0)
printf("Start ConstructDelaunay...\n");
/* find domain extent */
FindTesselExtent();
/* set edges Pe, the 3 points are in an equilateral triangle around all particles */
for (j=0;j<3;j++)
{
Pe[j].Pos[0] = tesselDomainCenter[0] + tesselDomainRadius * cos(2./3.*PI*j);
Pe[j].Pos[1] = tesselDomainCenter[1] + tesselDomainRadius * sin(2./3.*PI*j);
Pe[j].Pos[2] = 0;
Pe[j].Mass = 0;
}
/* Triangle list */
Triangles[0].idx = 0;
Triangles[0].P[0] = &Pe[0];
Triangles[0].P[1] = &Pe[1];
Triangles[0].P[2] = &Pe[2];
Triangles[0].T[0] = NULL;
Triangles[0].T[1] = NULL;
Triangles[0].T[2] = NULL;
Triangles[0].idxe[0] = -1;
Triangles[0].idxe[1] = 1;
Triangles[0].idxe[2] = -1;
nT++;
OrientTriangleInList(Triangles[0]);
/* loop over all points */
for (i=0;i<NumPart;i++)
AddPoint(&P[i]);
/* add ghost points */
ExtendWithGhostPoints();
/* check */
CheckTriangles();
if (ThisTask==0)
printf("ConstructDelaunay done.\n");
}
/*! Compute the Voronoi tesselation from the Delonay one
*/
int ComputeVoronoi()
{
if (ThisTask==0)
printf("Start ComputeVoronoi...\n");
ComputeMediansProperties();
ComputeMediansIntersections();
ComputeDensity();
if (ThisTask==0)
printf("ComputeVoronoi done.\n");
}
/************************************************************/
/* */
/* PYTHON INTERFACE */
/* */
/************************************************************/
#ifdef PY_INTERFACE
#include <Python.h>
#include <numpy/arrayobject.h>
PyObject *gadget_GetAllDelaunayTriangles(self, args)
PyObject *self;
PyObject *args;
{
import_array(); /* needed but strange no ? */
PyObject *OutputList;
PyObject *OutputDict;
PyArrayObject *tri = NULL;
npy_intp dim[2];
int iT;
/* loop over all triangles */
OutputList = PyList_New(0);
for (iT=0;iT<nT;iT++)
{
/* 3x3 vector */
dim[0]=3;
dim[1]=3;
tri = (PyArrayObject *) PyArray_SimpleNew(2,dim,PyArray_DOUBLE);
*(double *) (tri->data + 0*(tri->strides[0]) + 0*tri->strides[1]) = Triangles[iT].P[0]->Pos[0];
*(double *) (tri->data + 0*(tri->strides[0]) + 1*tri->strides[1]) = Triangles[iT].P[0]->Pos[1];
*(double *) (tri->data + 0*(tri->strides[0]) + 2*tri->strides[1]) = 0;
*(double *) (tri->data + 1*(tri->strides[0]) + 0*tri->strides[1]) = Triangles[iT].P[1]->Pos[0];
*(double *) (tri->data + 1*(tri->strides[0]) + 1*tri->strides[1]) = Triangles[iT].P[1]->Pos[1];
*(double *) (tri->data + 1*(tri->strides[0]) + 2*tri->strides[1]) = 0;
*(double *) (tri->data + 2*(tri->strides[0]) + 0*tri->strides[1]) = Triangles[iT].P[2]->Pos[0];
*(double *) (tri->data + 2*(tri->strides[0]) + 1*tri->strides[1]) = Triangles[iT].P[2]->Pos[1];
*(double *) (tri->data + 2*(tri->strides[0]) + 2*tri->strides[1]) = 0;
OutputDict = PyDict_New();
PyDict_SetItem(OutputDict,PyString_FromString("id"),PyInt_FromLong(Triangles[iT].idx) );
PyDict_SetItem(OutputDict,PyString_FromString("coord"),(PyObject*)tri);
//(PyObject*)tri
PyList_Append(OutputList, OutputDict );
}
return Py_BuildValue("O",OutputList);
}
PyObject *gadget_GetAllvPoints(self, args)
PyObject *self;
PyObject *args;
{
import_array(); /* needed but strange no ? */
PyArrayObject *pos;
npy_intp ld[2];
int i;
ld[0] = nvPoints;
ld[1] = 3;
pos = (PyArrayObject *) PyArray_SimpleNew(2,ld,PyArray_FLOAT);
for (i = 0; i < pos->dimensions[0]; i++)
{
*(float *) (pos->data + i*(pos->strides[0]) + 0*pos->strides[1]) = vPoints[i].Pos[0];
*(float *) (pos->data + i*(pos->strides[0]) + 1*pos->strides[1]) = vPoints[i].Pos[1];
*(float *) (pos->data + i*(pos->strides[0]) + 2*pos->strides[1]) = 0;
}
return PyArray_Return(pos);
}
PyObject *gadget_GetAllvDensities(PyObject* self)
{
import_array(); /* needed but strange no ? */
PyArrayObject *rho;
npy_intp ld[1];
int i;
ld[0] = NumPart;
rho = (PyArrayObject *) PyArray_SimpleNew(1,ld,PyArray_DOUBLE);
for (i = 0; i < rho->dimensions[0]; i++)
{
*(double *) (rho->data + i*(rho->strides[0])) = P[i].Density;
}
return PyArray_Return(rho);
}
PyObject *gadget_GetAllvVolumes(PyObject* self)
{
import_array(); /* needed but strange no ? */
PyArrayObject *volume;
npy_intp ld[1];
int i;
ld[0] = NumPart;
volume = (PyArrayObject *) PyArray_SimpleNew(1,ld,PyArray_DOUBLE);
for (i = 0; i < volume->dimensions[0]; i++)
{
*(double *) (volume->data + i*(volume->strides[0])) = P[i].Volume;
}
return PyArray_Return(volume);
}
PyObject *gadget_GetvPointsForOnePoint(self, args)
PyObject *self;
PyObject *args;
{
import_array(); /* needed but strange no ? */
PyArrayObject *pos;
npy_intp ld[2];
int i;
int np=0;
if (!PyArg_ParseTuple(args,"i",&i))
return NULL;
int next;
next = P[i].ivPoint;
np = P[i].nvPoints;
ld[0] = np;
ld[1] = 3;
pos = (PyArrayObject *) PyArray_SimpleNew(2,ld,PyArray_FLOAT);
for (i = 0; i < pos->dimensions[0]; i++)
{
*(float *) (pos->data + i*(pos->strides[0]) + 0*pos->strides[1]) = vPoints[next].Pos[0];
*(float *) (pos->data + i*(pos->strides[0]) + 1*pos->strides[1]) = vPoints[next].Pos[1];
*(float *) (pos->data + i*(pos->strides[0]) + 2*pos->strides[1]) = 0;
next = vPoints[next].next;
}
next = vPoints[next].next;
if (next!=0)
{
printf("error in tessel_get_vPointsForOnePoint\n");
return NULL;
}
return PyArray_Return(pos);
}
PyObject *gadget_GetAllGhostPositions(PyObject* self)
{
PyArrayObject *pos;
npy_intp ld[2];
int i;
import_array(); /* needed but strange no ? */
ld[0] = NumgPart;
ld[1] = 3;
pos = (PyArrayObject *) PyArray_SimpleNew(2,ld,PyArray_FLOAT);
for (i = 0; i < pos->dimensions[0]; i++)
{
- *(float *) (pos->data + i*(pos->strides[0]) + 0*pos->strides[1]) = gP[i].Pos[0];
- *(float *) (pos->data + i*(pos->strides[0]) + 1*pos->strides[1]) = gP[i].Pos[1];
- *(float *) (pos->data + i*(pos->strides[0]) + 2*pos->strides[1]) = gP[i].Pos[2];
+ *(float *) (pos->data + i*(pos->strides[0]) + 0*pos->strides[1]) = P[NumPart+i].Pos[0];
+ *(float *) (pos->data + i*(pos->strides[0]) + 1*pos->strides[1]) = P[NumPart+i].Pos[1];
+ *(float *) (pos->data + i*(pos->strides[0]) + 2*pos->strides[1]) = P[NumPart+i].Pos[2];
}
return PyArray_Return(pos);
}
+PyObject *gadget_GetAllGhostvDensities(PyObject* self)
+{
+ import_array(); /* needed but strange no ? */
+
+ PyArrayObject *rho;
+ npy_intp ld[1];
+ int i;
+
+ ld[0] = NumgPart;
+
+ rho = (PyArrayObject *) PyArray_SimpleNew(1,ld,PyArray_DOUBLE);
+
+ for (i = 0; i < rho->dimensions[0]; i++)
+ {
+ *(double *) (rho->data + i*(rho->strides[0])) = P[NumPart+i].Density;
+ }
+
+ return PyArray_Return(rho);
+}
+
+
+
+
+PyObject *gadget_GetAllGhostvVolumes(PyObject* self)
+{
+ import_array(); /* needed but strange no ? */
+
+ PyArrayObject *volume;
+ npy_intp ld[1];
+ int i;
+
+ ld[0] = NumgPart;
+
+ volume = (PyArrayObject *) PyArray_SimpleNew(1,ld,PyArray_DOUBLE);
+
+ for (i = 0; i < volume->dimensions[0]; i++)
+ {
+ *(double *) (volume->data + i*(volume->strides[0])) = P[NumPart+i].Volume;
+ }
+
+ return PyArray_Return(volume);
+}
+
+
#endif /* PY_INTERFACE */
#endif

Event Timeline